Python piramiko,建立SSH连接时连接超时错误

时间:2016-11-26 22:23:46

标签: python linux amazon-web-services amazon-ec2 boto3

我正在开发 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实例之间建立连接,我就无法继续了。

  • 您有什么建议可以解决这个问题吗?
  • piramiko还有其他库吗?

2 个答案:

答案 0 :(得分:2)

我设法解决了这个问题。问题是我的ec2实例。这些解决了这个问题:

  • 确保实例的安全组具有ssh deamon并允许您连接。
  • 确保您拥有在创建实例时创建的密钥对。
  • 确保执行chmod 400 keypair.pem

答案 1 :(得分:1)

我遇到了同样的错误,这是我解决它的方法:-

  1. 在客户端 VM 上安装 openssh-client,在服务器 VM 上安装 openssh-server

  2. 不要执行ssh@ip address,因为这会使您登录到您的主机虚拟机,然后您的客户端和服务器上的 IP 将相同,这是主要原因对于错误。

3.改为使用

ssh-keyscan ip_address >> ~/.ssh/known_hosts

所以知道主机密钥在已知主机中,而原始 IP 仍然存在。