我希望能够通过 ssh 连接到 EC2 实例,并在其中运行一些 shell 命令,如下 所示。
我如何在 boto3 中做到这一点?
原文由 Dawny33 发布,翻译遵循 CC BY-SA 4.0 许可协议
我希望能够通过 ssh 连接到 EC2 实例,并在其中运行一些 shell 命令,如下 所示。
我如何在 boto3 中做到这一点?
原文由 Dawny33 发布,翻译遵循 CC BY-SA 4.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 许可协议
2 回答5.2k 阅读✓ 已解决
2 回答1.1k 阅读✓ 已解决
4 回答1.4k 阅读✓ 已解决
3 回答1.3k 阅读✓ 已解决
3 回答1.3k 阅读✓ 已解决
2 回答895 阅读✓ 已解决
1 回答1.8k 阅读✓ 已解决
您可以使用以下代码片段通过 ssh 连接到 EC2 实例并从 boto3 运行一些命令。