难点主要是对获取数据的处理
# waf表格列表:实例id,规格信息,使用情况
import json
import xlwt
# from xxx import xxx as xxx,从某个模块导入某个函数并as换个名字
from alibabacloud_waf_openapi20190910.client import Client as waf_openapi20190910Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_waf_openapi20190910 import models as waf_openapi_20190910_models
# API的AK值
access_key_id = 'access_key_id'
access_key_secret = 'access_key_secret'
def waf_client():
global access_key_id
global access_key_secret
config = open_api_models.Config(access_key_id, access_key_secret)
config.endpoint = f'wafopenapi.cn-hangzhou.aliyuncs.com'
# 需要先实例化一个对象,才能返回一个实例对象
clientwaf = waf_openapi20190910Client(config)
return clientwaf
def waf_specinfo(client):
info_request = waf_openapi_20190910_models.DescribeInstanceSpecInfoRequest()
info = client.describe_instance_spec_info(info_request)
# print(info.body.instance_id)
infos = info.body
return infos
def waf_domain(client, inst_id):
describe_domain_names_request = waf_openapi_20190910_models.DescribeDomainNamesRequest(
instance_id=inst_id
)
domain = client.describe_domain_names(describe_domain_names_request).body.domain_names
print(len(domain))
# print(domain.body)
return domain
def wafusage_excel(infos, domains):
# 创建工作簿的一个对象
execl = xlwt.Workbook(encoding='utf-8')
# 建表,cell_overwrite_ok=True可以重复插入表格
sheet = execl.add_sheet('waf版本规格信息', cell_overwrite_ok=True)
# 参数1行数row,参数2列数column,参数3写入的内容
row = 1 # 在第几行输入
sheet.write(0, 0, '实例id')
sheet.write(0, 1, '版本')
sheet.write(0, 2, '规格')
sheet.write(0, 3, '使用情况')
insID = infos.instance_id
print(insID)
version = infos.version
print(version)
spec_len = len(infos.instance_spec_infos)
spec_dict = {}
# 通过对instance_spec_infos返回的数据循环查找目标数据
for i in range(spec_len):
# 'InstanceSpecInfos'是列表,'Code'是列表里的字典的键
if infos.to_map()['InstanceSpecInfos'][i]['Code'] == '113':
fistdomain = infos.to_map()['InstanceSpecInfos'][i]['Value']
print('fistdomain:', fistdomain)
spec_dict['一级域名数'] = fistdomain
if infos.to_map()['InstanceSpecInfos'][i]['Code'] == '103':
totaldomain = infos.to_map()['InstanceSpecInfos'][i]['Value']
spec_dict['域名总数'] = totaldomain
print('totaldomain', totaldomain)
if infos.to_map()['InstanceSpecInfos'][i]['Code'] == '114':
bandwidth = infos.to_map()['InstanceSpecInfos'][i]['Value']
spec_dict['业务带宽'] = bandwidth
print('bandwidth:', bandwidth)
if infos.to_map()['InstanceSpecInfos'][i]['Code'] == '115':
bindingdomain = infos.to_map()['InstanceSpecInfos'][i]['Value']
spec_dict['独享资源包'] = bindingdomain
print('bindingdomain:', bindingdomain)
sheet.write(row, 0, insID)
sheet.write(row, 1, version)
sheet.write(row, 2, json.dumps(spec_dict, ensure_ascii=False))
sheet.write(row, 3, '已使用域名数:%d/%s' % (len(domains), totaldomain))
execl.save('D:/waf版本规格表.xls')
if __name__ == '__main__':
wafclient = waf_client()
info = waf_specinfo(wafclient)
domain = waf_domain(wafclient, info.instance_id)
wafusage_excel(info, domain)