Boto在ec2实例上执行shell命令

时间:2013-03-19 14:11:51

标签: python amazon-ec2 boto

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

我搜索了很多,并在run_instances命令中使用user_data找到了解决方案,但是如果实例已经启动了怎么办?

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

4 个答案:

答案 0 :(得分: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')

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

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

答案 1 :(得分:3)

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

它非常易于使用,您可以集成boto和fabric。他们一起工作很棒。

另外,可以对n个节点执行相同的命令。我相信这可能是你的要求

看看吧。

答案 2 :(得分:2)

最简单的方法是使用 kitten python 实用程序,它只是 boto3 的包装器。

例如

kitten run "apt-get update" ubuntu 18.105.107.20

答案 3 :(得分:1)

是的,您可以使用AWS Systems Manager进行此操作。 AWS Systems Manager运行命令允许您在EC2以及本地服务器上远程安全地运行命令集。以下是实现此目的的高级步骤。

附加实例IAM角色: ec2实例必须具有带策略AmazonSSMFullAccess的IAM角色。该角色使实例能够与Systems Manager API进行通信。

安装SSM代理: EC2实例上必须安装了SSM代理。 SSM代理处理运行命令请求并根据命令配置实例。

执行命令: 通过AWS CLI的示例用法:

执行以下命令以检索在实例上运行的服务。用ec2实例ID替换Instance-ID。

aws ssm send-command --document-name "AWS-RunShellScript" --comment "listing services" --instance-ids "Instance-ID" --parameters commands="service --status-all" --region us-west-2 --output text

更多详细信息:https://www.justdocloud.com/2018/04/01/run-commands-remotely-ec2-instances/

相关问题