生产实践:
调用阿里云aliyun、腾讯云tccli客户端命令获取云服务器磁盘信息
学习技巧:
Python subprocess库、阿里云、腾讯云API使用
脚本内容:
将云服务器机器名写入文件中,使用subprocess库执行本地shell命令调用api获取云服务器磁盘信息,需本地提前安装好阿里云aliyun、腾讯云tccli客户端。
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @FileName: diskinfo.py @Function: 使用subprocess执行shell命令获取阿里云、腾讯云机器磁盘信息 @Author: Zhihe An @Site: https://chegva.com @Time: 2021/8/29 """ from threading import Thread import subprocess import queue import time num_threads=3 q = queue.Queue() host_list = [] with open('tmp', 'r') as f: lines = f.readlines() for l in lines: l = l.strip('\n').strip() host_list.append(l) def diskinfo(host, queue): while True: host = queue.get() # ret=subprocess.call('tccli cvm DescribeInstances --Filters \'[{"Name":"instance-name","Values":["%s"]}]\' --filter "InstanceSet[*]"|jq -r \'.[].DataDisks[0]["DiskSize"],.[].DataDisks[0]["DiskType"]\' | xargs;' % ip,shell=True,stdout=open('result','a'),stderr=subprocess.STDOUT) file = open('disk.txt', "a") if str(host).startswith('ali'): ins_name = subprocess.run('aliyun ecs DescribeInstances --RegionId cn-beijing --InstanceName "%s" | jq -r \'.[].Instance[0]["InstanceId"]\'' % host, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False) # bytes转成字符串 ins_id = (ins_name.stdout.decode('utf-8').strip('\n').strip()) # print(ins_id) time.sleep(0.5) if ins_id != 'null': disk_res = subprocess.run('aliyun ecs DescribeDisks --RegionId cn-beijing --InstanceId "%s" --DiskType data |jq -r \'.[]|.["Disk"][0]["Size"],.[][0]["Category"]\' | xargs' % ins_id, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False) disk_size_category = disk_res.stdout.decode('utf-8').strip('\n').strip() else: disk_size_category = "" print(host, disk_size_category) print(host, disk_size_category, file=file) # file.write(host + "\t" + disk_size_category + "\n") time.sleep(0.5) elif str(host).startswith('qc'): qc_res = subprocess.run('tccli cvm DescribeInstances --Filters \'[{"Name":"instance-name","Values":["%s"]}]\' --filter "InstanceSet[*]"|jq -r \'.[].DataDisks[0]["DiskSize"],.[].DataDisks[0]["DiskType"]\' | xargs;' % host, shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE, check=False) qc_disk = qc_res.stdout.decode('utf-8').strip() if qc_disk: print(host, qc_disk) print(host, qc_disk, file=file) else: print(host, qc_disk) # print(host, qc_disk, file=file) file.write("\n") # file.write(host + "\t" + qc_disk + "\n") time.sleep(0.5) else: print(host) # print(host, file=file) file.write("\n") file.close() queue.task_done() #start num_threads threads for i in range(num_threads): t=Thread(target=diskinfo,args=(i,q)) t.setDaemon(True) t.start() print('main thread waiting...') for host in host_list: q.put(host) q.join() print('Done')
◎查看效果
参考: