2013-03-19 54 views
10

我是EC2和boto的新手。我有一个EC2运行实例,我想执行一个shell命令,例如通过博托apt-get updateBoto在ec2实例上执行shell命令

我寻觅了一番,发现在run_instances命令使用user_data一个解决方案,但如果实例已经启动呢?

我甚至不知道它是否可能。此参考文献中的任何线索都会对您有所帮助。

+0

感谢Steffen的编辑。请记住更正。 – vibhor 2013-03-21 18:41:59

+0

相关:[如何使用boto3 SSH和运行EC2中的命令?](https://stackoverflow.com/q/42645196/55075) – kenorb 2018-02-07 16:41:54

回答

20

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') 

,这是从内存类型,但我认为这是正确的。

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

+0

非常感谢garnaat。它看起来不错,需要检查。 – vibhor 2013-03-19 17:01:42

+0

感谢您的链接和简洁的比较 – Forethinker 2013-07-08 18:34:44

+0

如果你想使用cmdshell你需要安装paramiko。它并未在boto中列为依赖项,因为它可能难以在某些平台上安装,并且'cmdshell'不是boto功能的核心。 – garnaat 2015-07-14 12:28:17

2

我认为你可以使用面料来满足你的要求。只需检查一次织物包装。您可以通过结构库在远程服务器shell上执行该命令。

这是非常容易使用,你可以集成博托和织物。他们一起工作辉煌。

加上相同的命令可以执行n个节点。我相信这可能是你的要求

只需检查出来。

+0

是的乔治你是对的。这真的是一个很好的帮助,但我的问题已经解决了。我只使用布料。反正从我身边+1,我也接受你的答案 – vibhor 2013-03-21 18:34:47