如何使用 boto3 在 EC2 中通过 SSH 和运行命令?

新手上路,请多包涵

我希望能够通过 ssh 连接到 EC2 实例,并在其中运行一些 shell 命令,如下 所示

我如何在 boto3 中做到这一点?

原文由 Dawny33 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 712
2 个回答

您可以使用以下代码片段通过 ssh 连接到 EC2 实例并从 boto3 运行一些命令。

 import boto3
import botocore
import paramiko

key = paramiko.RSAKey.from_private_key_file(path/to/mykey.pem)
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# Connect/ssh to an instance
try:
    # Here 'ubuntu' is user name and 'instance_ip' is public IP of EC2
    client.connect(hostname=instance_ip, username="ubuntu", pkey=key)

    # Execute a command(cmd) after connecting/ssh to an instance
    stdin, stdout, stderr = client.exec_command(cmd)
    print stdout.read()

    # close the client connection once the job is done
    client.close()
    break

except Exception, e:
    print e

原文由 Venkatesh Wadawadagi 发布,翻译遵循 CC BY-SA 3.0 许可协议

这个线程有点旧,但由于我花了一个令人沮丧的下午来发现一个简单的解决方案,所以我不妨分享一下。

注意这不是对 OP 问题的 严格 回答,因为它不使用 ssh。但是,boto3 的一点是你不必这样做——所以我认为在大多数情况下,这将是实现 OP 目标的首选方式,因为他/她可以简单地使用他/她现有的 boto3 配置。

AWS 的 Run Command 内置于 botocore 中(据我所知,这应该适用于 boto 和 boto3)但免责声明: _我只使用 boto3 测试过它_。

 def execute_commands_on_linux_instances(client, commands, instance_ids):
    """Runs commands on remote linux instances
    :param client: a boto/boto3 ssm client
    :param commands: a list of strings, each one a command to execute on the instances
    :param instance_ids: a list of instance_id strings, of the instances on which to execute the command
    :return: the response from the send_command function (check the boto3 docs for ssm client.send_command() )
    """

    resp = client.send_command(
        DocumentName="AWS-RunShellScript", # One of AWS' preconfigured documents
        Parameters={'commands': commands},
        InstanceIds=instance_ids,
    )
    return resp

# Example use:
ssm_client = boto3.client('ssm') # Need your credentials here
commands = ['echo "hello world"']
instance_ids = ['an_instance_id_string']
execute_commands_on_linux_instances(ssm_client, commands, instance_ids)

对于 Windows 实例 powershell 命令,您将使用替代选项:

         DocumentName="AWS-RunPowerShellScript",

原文由 thclark 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题