[英]Python piramiko, Connection Timed Out Error While Establishing SSH Connection
我正在使用Python創建一個項目,該項目將創建一個Amazon ec2實例 ,並建立SSH和SFTP連接以在本機和ec2實例之間傳輸文件和命令。
因此,我開始編寫代碼,並編寫了使用boto3庫創建ec2實例的函數。
# creating a file named sefa.pem that will store the private key
outfile = open('sefa.pem', 'w')
keypair = ec2.meta.client.create_key_pair(KeyName='sefakeypair') # creates key pair
keyout= str(keypair['KeyMaterial']) # reads the key material
outfile.write(keyout) # writes the key material in sefa.pem
# creates the instance finally
response = ec2.create_instances(ImageId='ami-34913254', MinCount=1, MaxCount=1, InstanceType='t2.micro')
之后,我應該在機器和ec2實例之間建立SSH連接以發送命令,並且還應該在機器和ec2實例之間傳輸並取回文件。
經過研究,我發現有一個名為piramiko的Python庫,用於在我的計算機和ec2實例之間建立SSH連接和SFTP連接 。
我試圖在我的計算機和ec2實例之間建立SSH連接,但是一天都遇到了“ [Errrno 110]連接超時錯誤” 。 我已經在互聯網上搜索了幾個小時,但是找不到任何有用的信息。 這是出現“連接超時錯誤”的代碼:
con = paramiko.SSHClient() # ssh client using paramiko library
con.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # this is needed because of adding policy automautically
k = paramiko.RSAKey.from_private_key_file("sefa.pem") # k reads sefa.pem and stores private key
time.sleep(30) # added this because ec2 should do 2/2 checks before connecting
print("connecting")
con.connect(hostname=PUB_DNS, username="ubuntu", pkey=k, look_for_keys=True) # HERE IS THE ERROR, I CAN'T CONNECT
print("connected")
stdin, stdout, stderr = con.exec_command('echo "TEST"')
print(stdout.readlines())
con.close()
沒有建立我的機器和ec2實例之間的連接,我就走得更遠。
我設法解決了這個問題。 問題是我的ec2實例。 這些解決了問題:
chmod 400 keypair.pem
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.