简体   繁体   中英

socket.error: [Errno 111] Connection refused while connecting to EC2

I have the following code, which creates and connects an EC2 instance:

from __future__ import print_function

import paramiko
import boto3


#print('Loading function')

paramiko.util.log_to_file("/tmp/Dawny.log")

# List of EC2 variables
region = 'us-east-1'
image = 'ami-<>'
keyname = 'Cypher'
AWS_ACCESS_KEY_ID = ''
AWS_SECRET_ACCESS_KEY = ''

session = boto3.Session(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)

ec2 = session.resource('ec2', region_name='us-east-1')

key = 'Cypher.pem'
k = paramiko.RSAKey.from_private_key_file(key)
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())

instances = ec2.create_instances(ImageId=image, MinCount=1, MaxCount=1, InstanceType = 't2.micro', KeyName = keyname, SubnetId='subnet-<>', SecurityGroupIds = ['sg-<>'])

instance = instances[0]
instance.wait_until_running()

instance.load()

print(instance.public_dns_name)

c.connect(hostname = instance.private_ip_address, username = 'ec2-user', pkey = k)
stdin, stdout, stderr = c.exec_command("ls")

print("stdout: " + stdout.read())
print("stderr: " + stderr.read())

c.close()

When I run this script, it is giving me the following error:

Traceback (most recent call last):
  File "processing.py", line 37, in <module>
    c.connect(hostname = instance.private_ip_address, username = 'ec2-user', pkey = k)
  File "/usr/lib/python2.7/dist-packages/paramiko/client.py", line 251, in connect
    retry_on_signal(lambda: sock.connect(addr))
  File "/usr/lib/python2.7/dist-packages/paramiko/util.py", line 278, in retry_on_signal
    return function()
  File "/usr/lib/python2.7/dist-packages/paramiko/client.py", line 251, in <lambda>
    retry_on_signal(lambda: sock.connect(addr))
  File "/usr/lib64/python2.7/socket.py", line 228, in meth
    return getattr(self._sock,name)(*args)
socket.error: [Errno 111] Connection refused

Is there anything wrong in my script? Or anything which I missed?

Note: I am able to manually ssh into it from the same host.

c.connect(hostname = instance.public_ip_address, username = 'ec2-user', pkey = k)

如果脚本在包含实例的VPC外部的主机上运行,​​则无法使用私有IP地址访问脚本。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM