宝途的EC2实例执行shell命令 [英] Boto Execute shell command on ec2 instance
问题描述
我是新手,以EC2和博托。我有运行实例的EC2,我想执行例如像一个shell命令易于得到通过博托更新
。
I am newbie to EC2 and boto. I have an EC2 running instance and I want to execute a shell command like e.g. apt-get update
through boto.
我搜索了很多,发现使用 USER_DATA
的<一个解决方案href="http://boto.s3.amazonaws.com/ref/ec2.html#boto.ec2.connection.EC2Connection.run_instances">run_instances命令,但如果该实例已经启动?
I searched a lot and found a solution using user_data
in the run_instances command, but what if the instance is already launched?
我甚至不知道这是否是可能的。任何线索在这个参考值将是一个很大的帮助。
I don't even know if it is possible. Any clue in this reference will be a great help.
推荐答案
该boto.manage.cmdshell模块可以做到这一点。要使用它,您必须安装的paramiko包。它的一个简单的例子是使用:
The boto.manage.cmdshell module can be used to do this. To use it, you must have the paramiko package installed. A simple example of it's use:
import boto.ec2
from boto.manage.cmdshell import sshclient_from_instance
# Connect to your region of choice
conn = boto.ec2.connect_to_region('us-west-2')
# Find the instance object related to my instanceId
instance = conn.get_all_instances(['i-12345678'])[0].instances[0]
# Create an SSH client for our instance
# key_path is the path to the SSH private key associated with instance
# user_name is the user to login as on the instance (e.g. ubuntu, ec2-user, etc.)
ssh_client = sshclient_from_instance(instance,
key_path='<path to SSH keyfile>',
user_name='ec2-user')
# Run the command. Returns a tuple consisting of:
# The integer status of the command
# A string containing the output of the command
# A string containing the stderr output of the command
status, stdout, stderr = ssh_client.run('ls -al')
这是从内存类型,但我认为这是正确的。
That was typed from memory but I think it's correct.
您也可以检查出布( http://docs.fabfile.org/ ),它具有类似功能,但也有复杂得多的特性和功能。
You could also check out Fabric (http://docs.fabfile.org/) which has similar functionality but also has much more sophisticated features and capabilities.
这篇关于宝途的EC2实例执行shell命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!