如何通过boto3在EC2实例上运行python脚本
我以前读过这个问题。许多答案只是说用户不必使用如何通过boto3在EC2实例上运行python脚本,python,amazon-web-services,amazon-ec2,boto3,Python,Amazon Web Services,Amazon Ec2,Boto3,我以前读过这个问题。许多答案只是说用户不必使用ssh连接到EC2并运行命令。然而,我仍然不知道如何通过boto3运行python脚本。在boto2中,这是一个函数run\u instances,用户可以将脚本传递到EC2节点并运行它,就像下面的代码列表一样 def run(self, **kwargs): ec2 = boto.connect_ec2(settings.PDF_AWS_KEY, settings.PDF_AWS_SECRET) sqs = boto.connect
ssh
连接到EC2并运行命令。然而,我仍然不知道如何通过boto3运行python脚本。在boto2中,这是一个函数run\u instances
,用户可以将脚本传递到EC2节点并运行它,就像下面的代码列表一样
def run(self, **kwargs):
ec2 = boto.connect_ec2(settings.PDF_AWS_KEY, settings.PDF_AWS_SECRET)
sqs = boto.connect_sqs(settings.PDF_AWS_KEY, settings.PDF_AWS_SECRET)
queue = sqs.create_queue(REQUEST_QUEUE)
num = queue.count()
launched = 0
icount = 0
reservations = ec2.get_all_instances()
for reservation in reservations:
for instance in reservation.instances:
if instance.state == "running" and instance.image_id == AMI_ID:
icount += 1
to_boot = min(num - icount, MAX_INSTANCES)
if to_boot > 0:
startup = BOOTSTRAP_SCRIPT % {
'KEY': settings.PDF_AWS_KEY,
'SECRET': settings.PDF_AWS_SECRET,
'RESPONSE_QUEUE': RESPONSE_QUEUE,
'REQUEST_QUEUE': REQUEST_QUEUE}
r = ec2.run_instances(
image_id=AMI_ID,
min_count=to_boot,
max_count=to_boot,
key_name=KEYPAIR,
security_groups=SECURITY_GROUPS,
user_data=startup)
launched = len(r.instances)
return launched
BOOTSTRAP\u脚本是一个python脚本
我用boto3编写了一些代码:
# -*- coding: utf-8 -*-
SCRIPT_TORUN = """
import boto3
bucket = random_str()
image_name = random_str()
s3 = boto3.client('s3')
Somedata = 'hello,update'
upload_path = 'test/' + image_name
s3.put_object(Body=Somedata, Bucket='cloudcomputing.assignment.storage', Key=upload_path)
"""
import boto3
running_instance = []
ec2 = boto3.resource('ec2')
for instance in ec2.instances.all():
if instance.state['Name'] == 'running': # Choose running instance and save their instance_id
running_instance.append(instance.id)
print instance.id, instance.state
print running_instance
我可以获得运行实例的详细信息,有人能告诉我在boto3
中是否有类似run\u instances
的函数,我可以使用它在我运行的一个EC2实例中运行脚本script\u TORUN
。请参阅:
您要查找的参数是:UserData='string'
UserData(字符串)
--
要使实例可用的用户数据。欲了解更多信息,
请参阅启动时在Linux实例上运行命令(Linux)和
正在添加用户数据(Windows)。如果您使用的是命令行工具,
base64编码是为您执行的,您可以从
文件否则,必须提供base64编码文本
此值将自动进行base64编码。在执行该操作之前,不要对该值进行base64编码。如果要运行脚本一次且仅运行一次,特别是在EC2启动时,则可以在调用时在userdata中提供脚本
但是,如果您希望在一个(或多个)EC2实例上运行脚本,那么您应该查看EC2系统管理器(the)或类似()的内容
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()
except:
--------
对于凭据,我添加了AWSCLI包,即openterminal和run命令
aws configure
然后输入详细信息,boto3将从.aws文件夹中保存并自动读取这些信息。下面是如何使用另一个名为paramiko的python库来执行此操作
import paramiko
user_name='ubuntu'
instance_id='i-08h873123123' #just an example
pem_addr='/Users/folder1/.ssh/jack-aws.pem' # folder path to aws instance key
aws_region='us-east-1'
instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])
for instance in instances:
if (instance.id==instance_id):
p2_instance=instance
break;
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
privkey = paramiko.RSAKey.from_private_key_file(pem_addr)
ssh.connect(p2_instance.public_dns_name,username=user_name,pkey=privkey)
cmd_to_run='dropbox start && source /home/ubuntu/anaconda3/bin/activate py36 && cd /home/ubuntu/xx/yy/ && python3 func1.py' #you can seperate two shell commands by && or ;
stdin4, stdout4, stderr4 = ssh.exec_command(cmd_to_run,timeout=None, get_pty=False)
ssh.close()
这是否意味着我可以在获得一个正在运行的实例后运行脚本,而无需
SSH
?我是否可以指定一个实例来运行脚本,因为我在run\u instances
函数中未找到类似“instance\u id”的参数。我是否可以指定一个实例来运行脚本,因为我在run\u instances函数中未找到类似“instance\u id”的参数?run\u instances函数不将实例id作为输入。该函数将启动新的EC2实例。它返回实例ID。如果我想使用一个已存在的实例来运行脚本,而不是创建一个新实例,该怎么办?如前所述,使用EC2 SSM或类似Fabric的东西。我注意到send\u命令中的参数只接受一个字符串,如果我想将多行脚本传输到实例来运行该怎么办?我查看了官方文档,没有发现send_command
中有类似UserData
的参数。当我尝试导入任何模块时,该参数都不起作用。例如:进口numpy。给出一个错误,表示numpy不存在,但如果我从ec2终端运行相同的代码,它就可以正常工作