【发布时间】:2020-03-18 00:56:38
【问题描述】:
我正在编写一个 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])
我做了一个 silly 修复,只是通过使用 try-except 语句重新运行连接,但这有时仍会返回错误。
【问题讨论】:
-
该异常在任何连接打开之前就被抛出。它不能与连接本身相关。而是密钥文件本身以某种方式错误/不同。您是否比较了问题发生时和未发生时的密钥文件的内容/格式?
-
谢谢,我会试一试的。
-
更新:RSA Key 失败时和成功时的格式是一样的。
-
如果文件失败时保留文件并尝试再次使用,是否会出现异常?
标签: python amazon-web-services amazon-ec2 ssh paramiko