使用python重新启动后检查AWS实例是否已启动

时间:2016-04-13 06:51:58

标签: python python-3.x amazon-web-services boto3 aws-ec2

有没有办法检查AWS实例是否最终使用boto3或其他方式进入python。运行状态不区分重启和最后阶段。

3 个答案:

答案 0 :(得分:4)

如果您只想检查远程端口是否已打开,可以使用内置的socket软件包。

以下是等待远程端口打开的this answer的快速修改:

import socket
import time

def wait_for_socket(host, port, retries, retry_delay=30):
    retry_count = 0
    while retry_count <= retries:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        result = sock.connect_ex((host, port))
        sock.close()
        if result == 0:
            print "Port is open"
            break
        else:
            print "Port is not open, retrying..."
            time.sleep(retry_delay)

答案 1 :(得分:3)

boto3文档中提供了所有信息 http://boto3.readthedocs.org/en/latest/reference/services/ec2.html

这将显示实例的所有信息。

import boto3
reservations = boto3.client("ec2").describe_instances()["Reservations"]
for reservation in reservations:
  for each in reservation["Instances"]:
    print " instance-id{} :  {}".format(each["InstanceId"], each["State"]["Name"])

# or use describe_instance_status, much simpler query
instances = boto3.client("ec2").describe_instance_status()
for each in instances["InstanceStatuses"]: 
  print " instance-id{} :  {}".format(each["InstanceId"], each["InstanceState"]["Name"])

来自文档:

State (dict) --

The current state of the instance.

Code (integer) --

The low byte represents the state. The high byte is an opaque internal value and should be ignored.

0 : pending
16 : running
32 : shutting-down
48 : terminated
64 : stopping
80 : stopped
Name (string) --

The current state of the instance.

事实上,没有代码状态显示&#34;重启&#34;在文档中。我无法在我自己的EC2实例上测试它,因为在重新启动后,实例重启速度太快以至于AWS控制台没有机会显示&#34;重新启动&#34 ;州。

尽管如此,http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/monitoring-system-instance-status-check.html

  

以下是可能导致实例状态的问题示例   检查失败:

     

系统状态检查失败

     

网络或启动配置不正确

     

耗尽内存

     

文件系统损坏

     

不兼容的内核

答案 2 :(得分:2)

您还可以使用boto3中的InstanceStatusOk waiter或其他waiter

import boto3

instance_id = '0-12345abcde'

client = boto3.client('ec2')
client.reboot_instances(InstanceIds=[instance_id])

waiter = client.get_waiter('instance_status_ok')
waiter.wait(InstanceIds=[instance_id])

print("The instance now has a status of 'ok'!")