【玩转Lighthouse】利用Python调用云Api实现多地域快速导出轻量应用服务器详细信息

December 16, 2023
测试
测试
测试
测试
16 分钟阅读

0.准备工作

使用本代码请先进行子用户创建并授权云API与轻量应用服务器全部权限

请注意 为了保障您的账户以及云上资产的安全 请谨慎保管SecretId 与 SecretKey 并定期更新 删除无用权限

前往创建子用户:https://console.cloud.tencent.com/cam

1.SDK下载

请确保Python版本为3.6+

查看Python版本

python3 -V

安装腾讯云Python SDK

pip install -i https://mirrors.tencent.com/pypi/simple/ --upgrade tencentcloud-sdk-python

安装pandas

pip install -i https://mirrors.tencent.com/pypi/simple/ pandas

2.代码部分

import json
import pandas as pd
from time import time, strftime, localtime
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.lighthouse.v20200324 import lighthouse_client, models

start = time()
aria = ['ap-beijing', 'ap-chengdu', 'ap-guangzhou', 'ap-hongkong', 'ap-shanghai', 'ap-singapore',
        'na-siliconvalley','eu-moscow', 'ap-tokyo', 'ap-nanjing', 'ap-mumbai', 'eu-frankfurt']
aria_zh = ['北京', '成都', '广州', '中国香港', '上海', '新加坡', '硅谷', '莫斯科', '东京', '南京', '孟买', '法兰克福']

# 此处添加SecretId 与 SecretKey
cred = credential.Credential("SecretId", "SecretKey")

httpProfile = HttpProfile()
httpProfile.endpoint = "lighthouse.tencentcloudapi.com"
clientProfile = ClientProfile()
clientProfile.httpProfile = httpProfile

lh_id = []
lh_name = []
lh_state = []
lh_aria = []
lh_zone = []
lh_cpu = []
lh_memory = []
lh_os = []
lh_bandwidth = []
lh_public_ip = []
lh_private_ip = []
lh_disk_size = []
lh_created_time = []
lh_expired_time = []
lh_tft = []
lh_tfu = []
lh_tfr = []

print('代码运行中 预计30s导出完毕')

for i in range(12):
    client = lighthouse_client.LighthouseClient(cred, aria[i], clientProfile)
    # 获取实例信息
    try:
        # 查看所有实例
        req = models.DescribeInstancesRequest()
        params = {}
        req.from_json_string(json.dumps(params))
        resp = client.DescribeInstances(req)
        response = json.loads(resp.to_json_string())
        # print(response)
        # 实例详细信息

        # 判断地域是否含有实例
        if response['TotalCount'] > 0:
            # print(aria_zh[i] + '实例数为' + str(response['TotalCount']))
            # 提取返回的json信息
            for ii in range(response['TotalCount']):
                lh_id.append(response['InstanceSet'][ii]['InstanceId'])
                lh_name.append(response['InstanceSet'][ii]['InstanceName'])
                lh_state.append(response['InstanceSet'][ii]['InstanceState'])
                lh_aria.append(aria_zh[i])
                zone = response['InstanceSet'][ii]['Zone']
                zone_rep = zone.replace('{0}-'.format(aria[i]), '')
                lh_zone.append(zone_rep)
                lh_cpu.append(response['InstanceSet'][ii]['CPU'])
                lh_memory.append(response['InstanceSet'][ii]['Memory'])
                lh_os.append(response['InstanceSet'][ii]['OsName'])
                lh_bandwidth.append(response['InstanceSet'][ii]['InternetAccessible']['InternetMaxBandwidthOut'])
                lh_public_ip.append(response['InstanceSet'][ii]['PublicAddresses'][0])
                lh_private_ip.append(response['InstanceSet'][ii]['PrivateAddresses'][0])
                lh_disk_size.append(response['InstanceSet'][ii]['SystemDisk']['DiskSize'])
                lh_created_time.append(response['InstanceSet'][ii]['CreatedTime'])
                lh_expired_time.append(response['InstanceSet'][ii]['ExpiredTime'])
                # 查看流量包
                try:
                    req1 = models.DescribeInstancesTrafficPackagesRequest()

                    params1 = {"InstanceIds": [response['InstanceSet'][ii]['InstanceId']]}

                    req1.from_json_string(json.dumps(params1))

                    resp1 = client.DescribeInstancesTrafficPackages(req1)

                    response1 = json.loads(resp1.to_json_string())
                    tf = response1['InstanceTrafficPackageSet'][0]['TrafficPackageSet'][0]
                    # 总流量
                    tft = str(round(tf['TrafficPackageTotal'] / 1073741824, 2))
                    lh_tft.append(tft)
                    # 已用流量
                    tfu = str(round(tf['TrafficUsed'] / 1073741824, 2))
                    lh_tfu.append(tfu)
                    # 剩余流量
                    tfr = str(round(tf['TrafficPackageRemaining'] / 1073741824, 2))
                    lh_tfr.append(tfr)

                except TencentCloudSDKException as err:
                    print(err)

    except TencentCloudSDKException as err:
        print(err)

dataframe = pd.DataFrame({'ID': lh_id, '实例名': lh_name, '状态':lh_state, '地域': lh_aria, '可用区': lh_zone,
                          'CPU(核数)': lh_cpu, '内存(GB)': lh_memory, '操作系统': lh_os, '带宽(Mbps)': lh_bandwidth,
                          'IPv4公网IP': lh_public_ip, 'IPv4内网IP': lh_private_ip, '系统盘大小(GB)': lh_disk_size,
                          '创建时间': lh_created_time, '到期时间': lh_expired_time, '流量包大小(GB)': lh_tft, '流量包已用流量(GB)': lh_tfu,
                          '流量包剩余流量(GB)': lh_tfr})
csv_name = 'lh_{0}.csv'.format(strftime('%Y-%m-%d %H_%M_%S', localtime()))
dataframe.to_csv(csv_name, encoding='utf_8_sig')

print('导出完毕 文件名为{0}'.format(csv_name))
end = time()
print('本次代码执行共耗时:', round(end - start, 2), 's')

打开生成的文件 我们可以看到所有的轻量应用服务器配置均已被导出

(部分涉及隐私已以’” * “替代,请以实际导出文件为准)

ID

实例名

状态

地域

可用区

CPU(核数)

内存(GB)

操作系统

带宽(Mbps)

IPv4公网IP

IPv4内网IP

系统盘大小(GB)

创建时间

到期时间

流量包大小(GB)

流量包已用流量(GB)

流量包剩余流量(GB)

0

lhins-d*******

轻量2c4g8m免费升配

RUNNING

北京

3

4

4

Windows Server 2019 DataCenter 64bitCN

8

81.*.*.*

10.0.8.12

80

2021-02-22T05:30:46Z

2024-08-22T05:30:46Z

1200

0.39

1199.61

1

lhins-4*******

参与轻量征文活动拿好礼

RUNNING

中国香港

3

2

2

CentOS 7.9 64bit

30

43.*.*.*

10.0.8.12

30

2022-04-13T02:04:52Z

2022-05-13T02:07:38Z

1024

0.18

1023.82

2

lhins-1*******

参与轻量征文活动拿好礼

RUNNING

中国香港

3

2

2

CentOS 7.9 64bit

30

43.*.*.*

10.0.8.14

30

2022-04-13T02:04:45Z

2022-05-13T02:08:13Z

1024

0.23

1023.77

3

lhins-j*******

为居家程序员「送服」

RUNNING

上海

5

4

4

Windows Server 2019 DataCenter 64bitCN

8

124.*.*.*

10.0.16.8

80

2022-03-15T10:35:26Z

2022-04-15T10:35:26Z

1200

0.16

1199.84

4

lhins-j*******

轻量无忧计划

RUNNING

上海

4

1

2

CentOS 7.6 64bit

5

49.*.*.*

10.0.12.7

50

2021-10-23T11:24:58Z

2025-08-23T11:24:58Z

500

0.07

499.93

5

lhins-n*******

参与轻量征文活动拿好礼

RUNNING

新加坡

1

1

1

Ubuntu Server 20.04 LTS 64bit

30

43.*.*.*

10.0.0.10

25

2022-01-17T08:01:13Z

2022-06-17T08:01:13Z

1024

0.01

1023.99

6

lhins-1*******

参与轻量征文活动拿好礼

RUNNING

硅谷

2

2

2

CentOS 7.6 64bit

30

43.*.*.*

10.0.4.10

30

2022-01-17T08:01:20Z

2022-06-17T08:01:20Z

1024

0

1024

7

lhins-6*******

参与轻量征文活动拿好礼

RUNNING

东京

2

1

2

Ubuntu Server 20.04 LTS 64bit

30

43.*.*.*

10.0.4.6

50

2021-11-24T16:57:44Z

2022-11-24T16:57:44Z

2048

1.01

2046.99

8

lhins-0*******

参与轻量征文活动拿好礼

RUNNING

孟买

1

2

2

Ubuntu Server 20.04 LTS 64bit

30

129.*.*.*

10.0.0.9

30

2022-03-29T05:14:20Z

2022-06-29T05:14:20Z

1024

0.49

1023.51

9

lhins-b*******

参与轻量征文活动拿好礼

RUNNING

法兰克福

1

1

1

CentOS 7.6 64bit

30

162.*.*.*

10.0.0.9

25

2021-11-20T12:30:52Z

2022-06-20T12:30:52Z

1024

0.71

1023.29

继续阅读

更多来自我们博客的帖子

如何安装 BuddyPress
由 测试 December 17, 2023
经过差不多一年的开发,BuddyPress 这个基于 WordPress Mu 的 SNS 插件正式版终于发布了。BuddyPress...
阅读更多
Filter如何工作
由 测试 December 17, 2023
在 web.xml...
阅读更多
如何理解CGAffineTransform
由 测试 December 17, 2023
CGAffineTransform A structure for holding an affine transformation matrix. ...
阅读更多