我正在编写一个Python程序,该程序启动一个AWS EC3实例,然后使用Paramiko将其SSH并运行一些代码。问题是,在我运行代码的大约50%的时间里,我收到此错误:paramiko.ssh_exception.PasswordRequiredException: Private key file is encrypted
然后当我再次运行它时,它将起作用。
这是我的代码:
import sys
import os
import boto3
import time
import paramiko
import pexpect
ec2 = boto3.resource('ec2')
client = boto3.client('ec2')
# create a local file to store keypair
outfile = open('ec2-keypair.pem','w')
# use boto ec2 to create new keypair
key_pair = ec2.create_key_pair(KeyName='ec2-keypair')
# store keypair in a file
key_pair_to_write = str(key_pair.key_material)
outfile.write(key_pair_to_write)
pexpect.run("chmod 400 ec2-keypair.pem")
outfile.close()
instances = ec2.create_instances(
ImageId='ami-0be057a22c63962cb',
MinCount=1,
MaxCount=1,
InstanceType='t2.micro',
KeyName='ec2-keypair',
SecurityGroupIds=[
'<my sec groyp>',
],
)
instance = instances[0]
# Wait for the instance to enter the running state
instance.wait_until_running()
# Reload the instance attributes
instance.load()
dns = instance.public_dns_name
time.sleep(30)
try:
if len(sys.argv) > 2 or len(sys.argv) < 2:
print("Yah dun it wrong")
else:
difficulty = int(sys.argv[1])
ssh_client=paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(dns, username="ubuntu", key_filename=os.path.expanduser('ec2-keypair.pem'))
ftp_client=ssh_client.open_sftp()
ftp_client.put('steps_pow.py','/home/ubuntu/steps_pow.py')
ftp_client.close()
command = "python3 steps_pow.py " + str(difficulty) + " 10"
stdin,stdout,stderr=ssh_client.exec_command(command)
print(stdout.readlines())
finally:
client.delete_key_pair(KeyName='ec2-keypair')
os.remove("ec2-keypair.pem")
client.terminate_instances(InstanceIds=[instance.id])
我只是通过使用try-except语句来重新运行连接,所以进行了[[silly修复,但这有时仍会返回错误。