【问题标题】:To check whether AWS instance is up after reboot using python使用python检查重启后AWS实例是否启动
【发布时间】:2016-08-04 02:16:13
【问题描述】:

有没有办法使用 boto3 或其他方式检查 AWS 实例是否最终在 python 中出现。运行状态不区分重新启动和最终启动阶段。

【问题讨论】:

  • 你对“向上”的定义是什么?
  • 所有应该启动的进程都已经启动(如果我通过 putty 重新启动,最后启动意味着允许我再次登录)
  • 所以你的意思是端口 22 是开放的?
  • 是的。如果boto3中有一些API可以直接告诉我实例,那就更好了
  • 这部分可以用socket代替boto

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


【解决方案1】:

如果您只想检查远程端口是否打开,您可以使用内置的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)

【讨论】:

  • 我刚刚意识到,并不是所有的节点都有公共IP。在这种情况下我能做什么?我希望仅将公共 ip 提供给可以内部访问其他节点的节点之一
  • 或许将此脚本放入 AWS Lambda 中,与 VPC 子网交互。
【解决方案2】:

所有信息都可以在 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.

其实文档里面并没有代码状态显示“rebo​​oting”。我无法在我自己的 EC2 实例上对其进行真正的测试,因为在我重新启动后,实例似乎重新启动得如此之快,以至于 AWS 控制台没有机会显示“重新启动”状态。

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

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

系统状态检查失败

网络或启动配置不正确

内存耗尽

文件系统损坏

内核不兼容

【讨论】:

    【解决方案3】:

    您也可以在 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'!")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-01
      • 2017-06-10
      • 2014-05-20
      • 1970-01-01
      • 2018-08-30
      • 1970-01-01
      • 2021-04-09
      相关资源
      最近更新 更多