我希望能够ssh到EC2实例,并在其中运行一些shell命令,像这样 。
我该怎么做它boto3?
我希望能够ssh到EC2实例,并在其中运行一些shell命令,像这样 。
我该怎么做它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
这个线程是有点老了,但因为我已经花了一个令人沮丧的下午发现一个简单的解决办法,我也可以分享。
注意这不是一个严格的答案OP的问题,因为它不使用ssh。 但是,boto3的一点是,你不必 - 因此,我认为在大多数情况下,这将是实现OP的目标的首选方法,因为他/她可以平凡使用他/她现有的boto3配置。
AWS的运行命令被内置到botocore(所以这应该同时适用于伯特和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",
使用boto3发现实例和面料上运行的情况下,命令
你不从蟒蛇SSH协议。 您可以使用boto3
模块与EC2实例进行交互。
在这里 ,你有一个完整的文档boto3
什么命令,你可以用它运行。
宝途提供一种方法来SSH到编程方式使用的paramiko EC2实例,然后运行命令。 Boto3不包含此功能。 你也许可以修改博托代码boto3工作没有大量的精力。 或者你可以考虑使用像织物或ansible它提供了一个更强大的方式来对EC2实例远程执行命令。
下面是我做
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()
对于credentails,我加AWSCLI包,然后在终端运行
aws configure
输入凭据。 他们都将被保存在文件夹.aws,U可以更改路径了。