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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42645196/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 21:59:29  来源:igfitidea点击:

How to SSH and run commands in EC2 using boto3?

pythonamazon-ec2boto3

提问by Dawny33

I want to be able to ssh into an EC2 instance, and run some shell commands in it, like this.

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

How do I do it in boto3?

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

采纳答案by Venkatesh

You can use the following code snippet to ssh to an EC2 instance and run some command from boto3.

您可以使用以下代码片段通过 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

回答by thclark

This thread is a bit old, but since I've spent a frustrating afternoon discovering a simple solution, I might as well share it.

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

NB This is not a strictanswer to the OP's question, as it doesn't use ssh. But, one point of boto3 is that you don't have to - so I think in most circumstances this would be the preferred way of achieving the OP's goal, as s/he can use his/her existing boto3 configuration trivially.

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

AWS' Run Command is built into botocore (so this should apply to both boto and boto3, as far as I know) but disclaimer: I've only tested this with 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)

For windows instance powershell commands you'd use an alternative option:

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

        DocumentName="AWS-RunPowerShellScript",

回答by Lakshya Srivastava

Here is how I have done

这是我的做法

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()

For the credentails, I have added AWSCLI package, then in the terminal run

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

aws configure

enter the credentials. All of them will be saved in .aws folder, u can change the path too.

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

回答by Carles Mitjans

You don't SSH from python. You can use boto3module to interact with the EC2 instance.

你不是从 python SSH 的。您可以使用boto3模块与 EC2 实例交互。

Hereyou have a complete documentation of boto3and what commands you can run with it.

在这里你有一个完整的文档,boto3以及你可以用它运行哪些命令。

回答by garnaat

Boto provided a way to SSH into EC2 instances programmatically using Paramiko and then run commands. Boto3 does not include this functionality. You could probably modify the boto code to work with boto3 without a huge amount of effort. Or you could look into using something like fabric or ansible which provide a much more powerful way to remotely execute commands on EC2 instances.

Boto 提供了一种使用 Paramiko 以编程方式通过 SSH 连接到 EC2 实例然后运行命令的方法。Boto3 不包含此功能。您可能无需花费大量精力就可以修改 boto 代码以使用 boto3。或者您可以考虑使用诸如 fabric 或 ansible 之类的东西,它们提供了一种在 EC2 实例上远程执行命令的更强大的方法。

回答by James Soubry

use boto3 to discover instances and fabricto run commands on the instances

使用 boto3 发现实例并使用结构在实例上运行命令