要检查使用python的重新启动后,AWS实例是否启动

问题描述 投票:1回答:3

有没有一种方法来检查,如果一个AWS实例终于拿出在Python或者使用boto3或以其他方式。运行状态犯规重启最后阶段区分。

python python-3.x amazon-web-services boto3 aws-ec2
3个回答
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)

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.

事实上,没有任何代码状态显示“重新启动”的文件中。我真的不能测试它在我自己的EC2实例,因为我做重启后,似乎情况下重新启动如此之快,AWS控制台不会有机会显示“重新引导”状态。

然而,http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/monitoring-system-instance-status-check.html

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

失败的系统状态检查

不正确的网络或启动配置

内存用尽

损坏的文件系统

内核不兼容


2
投票

你也可以使用InstanceStatusOk waiter在boto3或任何waiter是approprate。

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'!")
© www.soinside.com 2019 - 2024. All rights reserved.