【问题标题】:Boto Execute shell command on ec2 instanceBoto 在 ec2 实例上执行 shell 命令
【发布时间】:2013-03-08 06:23:37
【问题描述】:

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

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

我什至不知道这是否可能。此参考资料中的任何线索都会有很大帮助。

【问题讨论】:

标签: python amazon-ec2 boto


【解决方案1】:

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/),它具有类似的功能,但也具有更复杂的特性和功能。

【讨论】:

  • 感谢您的链接和简洁的比较
  • 如果你想使用cmdshell你需要安装paramiko。它没有在 boto 中列为依赖项,因为它可能难以在某些平台上安装,并且 cmdshell 不是 boto 功能的核心。
  • 可能还想签出 EC2 RunCommand (aws.amazon.com/about-aws/whats-new/2015/12/…)
  • 这很好,但是我有一个问题:如果我要在一个循环中为多个实例执行此操作,是否每个 ssh_client.run('ls -al') 都必须在下一个实例运行命令之前完成?跨度>
  • 在第 12 行,如果我想从 boto 获取 ssh 用户怎么办,是否可以不硬编码用户名? :-/
【解决方案2】:

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

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

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

看看就好。

【讨论】:

  • 是的,乔治,你是对的。这确实是一个很大的帮助,但我的问题已经解决了。我只使用织物。无论如何,我这边 +1,我也接受你的回答者
【解决方案3】:

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

例如

kitten run "apt-get update" ubuntu 18.105.107.20

【讨论】:

    【解决方案4】:

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

    附加实例 IAM 角色: ec2 实例必须具有具有策略 AmazonSSMFullAccess 的 IAM 角色。此角色使实例能够与 Systems Manager 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/

    【讨论】:

      猜你喜欢
      • 2016-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-24
      • 2013-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多