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

2024-03-28 17:18:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望能够ssh到EC2实例中,并在其中运行一些shell命令,比如this

我怎么用boto3呢?


Tags: 实例命令shellthisboto3ec2ssh
3条回答

您可以使用下面的代码片段来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

使用boto3来发现实例,fabric来对实例运行命令

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

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

AWS的Run命令内置于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",

相关问题 更多 >