Boto在ec2实例上执行shell命令

vib*_*hor 11 python amazon-ec2 boto

我是EC2和boto的新手.我有一个EC2运行实例,我想执行一个shell命令,例如apt-get update通过boto.

我搜索了很多并user_datarun_instances命令中找到了一个解决方案,但是如果实例已经启动了怎么办?

我甚至不知道是否有可能.这篇参考文献中的任何线索都将是一个很大的帮助.

gar*_*aat 21

boto.manage.cmdshell模块可用于执行此操作.要使用它,您必须安装paramiko软件包.一个简单的例子:

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,
                                     '<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')
Run Code Online (Sandbox Code Playgroud)

这是从记忆中输入的,但我认为这是正确的.

您还可以查看Fabric(http://docs.fabfile.org/),它具有类似的功能,但也具有更复杂的功能和特性.