

Python3使用subprocess执行shell命令
source link: https://chegva.com/4793.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Python3使用subprocess执行shell命令
生产实践:
调用阿里云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')
◎查看效果
参考:
Recommend
-
151
inf-clojure This package provides basic interaction with a Clojure subprocess (REPL). It's based on ideas from the popular inferior-lisp package. inf-clojure has two components - a nice REPL buffer (...
-
84
inf-crystal.el Run a Inferior-Crystal process in a buffer inf-crystal provides a REPL buffer connected to a icr subprocess. It's based on ideas...
-
47
*本文原创作者:ForrestX386,本文属FreeBuf原创奖励计划,未经许可禁止转载 0×00. 前言 在各大热门语言排行榜中,Python语言多次名列前茅,其高效的开发效率和优雅的编程风格吸引不少开发人员的青睐,不少公司将技...
-
12
gobox中的编解码和执行shell命令 May 11, 2018 今天来说下gobox中的encoding和shell两个box。 encoding encoding的主要作用是完成编解码工作,目前支持了base64编解码。
-
8
linux下的C语言开发19,使用C语言执行shell命令 发表于 2019-01-07 18:01:11...
-
10
无需电脑如何执行 adb shell 命令无需电脑如何执行 adb shell 命令 02 月 15 日 Matrix 首页推荐Matrix 是少数派的写作社区,我...
-
5
.py | python.subprocess执行bash命令 Jul 8, 2022 笔记本的触摸屏被我摔了道裂纹,一开始还不影响使用,但是最近几周情况恶化,有时鼠标光标会突然暴走,不听指挥。所以...
-
20
【笔记】Java中执行Shell命令 2022-10-25 1...
-
13
【笔记】Go 语言执行 Shell 命令 捕捉一只爱折腾的绯鞠 ...
-
4
操作系统 :CentOS 7.6_x64 FreeSWITCH版本 :1.10.9 python版本:3.9.12 libpcap版本:1.11.0b7 FreeSWITCH的ESL模块用起来很方便,可以控制FreeSWITCH实现具体业务需求,但该模块没有提供ESL命令执行日志,...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK