【问题标题】:Is there a way to find out last restart time for all EC2 instances using Python有没有办法使用 Python 找出所有 EC2 实例的上次重启时间
【发布时间】:2020-11-19 05:25:28
【问题描述】:

我正在尝试获取每个 ec2 实例为“正在运行”的实例运行多长时间。为此,我需要获取所有实例的上次重启时间并将其与今天进行比较。发现我可以从 cloudtrail 获得重新启动或启动事件,但无法弄清楚如何从那里获得仅“开始”时间。有没有办法找到几个地区的信息?

import boto3
import datetime
from datetime import date
import subprocess


regions = ['us-west-2', 'us-west-1', 'us-east-1','us-east-2','ap-south-1', 'ap-southeast-1','ca-central-1','eu-west-1','eu-west-3']


    for region in regions:
        session = boto3.session.Session(region_name=region)
        ec2 = session.resource('ec2')
        cloudtrail = boto3.client('cloudtrail')

        for i in ec2.instances.all():
            Id = i.id
            State = i.state['Name']
            Launchtime = i.launch_time
            InstanceType = i.instance_type
            Platform = str(i.platform)
            currenttime = datetime.datetime.now(Launchtime.tzinfo)
            time_diff = currenttime - Launchtime
            uptime = str(time_diff)

这里的正常运行时间给出了启动时间和当前时间之间的时间差,这是不正确的,因为大多数实例已经重新启动了很多时间。所以我需要找到所有正在运行的实例的最后开始时间。

【问题讨论】:

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


    【解决方案1】:

    我稍微调整了我的代码,然后变成了这样:

    import boto3
    import datetime
    from datetime import date
    import subprocess
    
    
    regions = ['us-west-2', 'us-west-1', 'us-east-1']
    
    
        for region in regions:
            session = boto3.session.Session(region_name=region)
            ec2 = session.resource('ec2')
    
            for i in ec2.instances.all():
                Id = i.id
                State = i.state['Name']
                Launchtime = i.launch_time
                InstanceType = i.instance_type
                Platform = str(i.platform)
                currenttime = datetime.datetime.now(Launchtime.tzinfo)
                time_diff = currenttime - Launchtime
                uptime = str(time_diff)
                if i.state['Name'] == 'stopped':
                    uptime = ' '
    

    这里只显示正在运行的实例的正常运行时间。发现启动时间显示为这些实例上次启动(启动)的时间。在控制台中交叉检查,这些都是正确的。然后检查 Linux 实例 (sudo uptime) 和与输出匹配的实例的时间。

    【讨论】:

      猜你喜欢
      • 2020-04-13
      • 2017-10-04
      • 2021-05-14
      • 1970-01-01
      • 2021-08-13
      • 2017-08-07
      • 2022-01-10
      • 2016-07-01
      • 1970-01-01
      相关资源
      最近更新 更多