坚持亚马逊ec2实例的状态检查

时间:2013-12-26 06:58:37

标签: python amazon-web-services ssh amazon-ec2

我正在使用Python来启动ec2实例,在我获得实例的“运行”状态后,我正在尝试使用SCP脚本并通过ssh运行它。

我收到以下错误

“ssh:连接到主机ec2-xx-xxx-xxx-xxx.compute-1.amazonaws.com端口22:连接被拒绝”

当我在控制台中检查时,状态检查是“正在初始化”,一旦它改变了“2/2检查通过”,我就可以ssh或运行任何脚本。

有什么办法可以通过python boto API获得“状态检查”吗?

我使用的是Python 2.7.5+, boto 2.19.0

提前致谢。

2 个答案:

答案 0 :(得分:4)

简单的方法是使用socket模块检查新创建的实例的端口22是否可访问

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
     s.connect(('hostname', 22))
     print "Port 22 reachable"
except socket.error as e:
     print "Error on connect: %s" % e
s.close()

当您能够到达端口22时,您可以调用ssh。

答案 1 :(得分:3)

懒惰的方式

import boto.ec2

for region in boto.ec2.regions():
        connection = boto.ec2.connect_to_region(region.name, 
            aws_access_key_id = '<aws access key>', aws_secret_access_key = '<aws secret key>')
        existing_instances = connection.get_all_instance_status()
        print 'Listing instances from region ' + region.name
        for instance in existing_instances:
            print instance.system_status.status + '/' + instance.instance_status.status