在EC2实例上使用Boto执行Shell命令

12 投票
3 回答
16505 浏览
提问于 2025-04-17 19:38

我刚接触EC2和boto。我有一个正在运行的EC2实例,想通过boto执行一个像 apt-get update 这样的命令。

我查了很多资料,发现可以通过在 run_instances 命令中使用 user_data 来解决这个问题,但如果实例已经启动了呢?

我甚至不知道这样做是否可行。如果能提供一些相关的线索,那将非常有帮助。

3 个回答

1

是的,你可以使用AWS系统管理器来做到这一点。AWS系统管理器的运行命令功能允许你远程并安全地在EC2实例和本地服务器上运行一系列命令。下面是实现这一目标的基本步骤。

附加实例IAM角色: EC2实例必须拥有一个带有AmazonSSMFullAccess权限的IAM角色。这个角色让实例能够与系统管理器的API进行通信。

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

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

执行以下命令以获取正在实例上运行的服务。将Instance-ID替换为你的EC2实例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/

3

我觉得你可以用fabric来满足你的需求。你可以先看看fabric的包装器。通过fabric库,你可以在远程服务器的命令行上执行命令。

使用起来非常简单,而且你可以把boto和fabric结合起来用。它们一起工作得非常好。

而且同一个命令可以在多个节点上执行。我想这可能正是你需要的功能。

你可以去看看。

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/),它有类似的功能,但还提供了更复杂的特性和能力。

撰写回答