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

Daw*_*y33 12 python amazon-ec2 boto3

我希望能够ssh到EC2实例,并在其中运行一些shell命令,就像这样.

我怎么在boto3中做到这一点?

thc*_*ark 28

这个线程是有点老了,但因为我已经花了一个令人沮丧的下午发现一个简单的解决办法,我也可以分享.

注意:这不是OP问题的严格答案,因为它不使用ssh.但是,boto3的一点是你不必 - 所以我认为在大多数情况下这将是实现OP目标的首选方式,因为他/她可以轻松地使用他/她现有的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)
Run Code Online (Sandbox Code Playgroud)

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

        DocumentName="AWS-RunPowerShellScript",
Run Code Online (Sandbox Code Playgroud)

  • 使用正确的实例 ID 时,我仍然收到客户端错误:ClientError:调用 SendCommand 操作时发生错误 (InvalidInstanceId):我该怎么办?请帮帮我,谢谢。 (2认同)

Ven*_*agi 9

您可以使用以下代码段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
Run Code Online (Sandbox Code Playgroud)

  • 是否有理由在此代码中使用 `import boto3` 或 `import botocore`? (3认同)

Lak*_*ava 6

这是我的做法

import boto3
import botocore
import boto
import paramiko

ec2 = boto3.resource('ec2')

instances = ec2.instances.filter(
    Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])
i = 0
for instance in instances:
    print(instance.id, instance.instance_type)
    i+= 1
x = int(input("Enter your choice: "))
try:
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    privkey = paramiko.RSAKey.from_private_key_file('address to .pem key')
    ssh.connect(instance.public_dns_name,username='ec2-user',pkey=privkey)
    stdin, stdout, stderr = ssh.exec_command('python input_x.py')
    stdin.flush()
    data = stdout.read().splitlines()
    for line in data:
        x = line.decode()
        #print(line.decode())
        print(x,i)
        ssh.close()
Run Code Online (Sandbox Code Playgroud)

对于凭据,我添加了 AWSCLI 包,然后在终端中运行

aws configure
Run Code Online (Sandbox Code Playgroud)

输入凭据。所有这些都将保存在 .aws 文件夹中,您也可以更改路径。