python 协程 - asyncio-subprocess 并发执行命令
2021-03-03 01:29
标签:com sleep cancel pen async cte can exec -o 1. 10秒钟测试ip段所有IP的连通性 python 协程 - asyncio-subprocess 并发执行命令 标签:com sleep cancel pen async cte can exec -o 原文地址:https://www.cnblogs.com/hixiaowei/p/14399637.html(base) [root@wlt-overseas-middleware-master ~]# cat su-asyncio-re-cancel.py
import asyncio
import time
import re
# call shell cmd and get exec return code
async def run(cmd):
proc = await asyncio.subprocess.create_subprocess_shell(
cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await proc.communicate()
# print(‘cmd: {}, returncode: {}‘.format(cmd, proc.returncode))
if stdout:
stdout = str(stdout)
# print("\033[1;{};1m{}\033[0m".format(32, stdout))
re_result = re.findall(‘Escape character is‘, stdout)
if re_result:
print("\033[1;{};1m{}\033[0m".format(32, stdout))
if stderr:
# print("\033[1;{};1m{}\033[0m".format(31, stderr))
pass
# call many machines use run
async def run_cmd_in_all_remotes(ips):
tasks_list = []
for ip in ips:
cmd = "sleep 1 |telnet " + ip + ‘ 22‘
task = asyncio.create_task(run(cmd))
tasks_list.append(task)
await asyncio.sleep(20)
for task in tasks_list:
task.cancel()
# task.cancel() 要在gather之前才能生效
await asyncio.gather(*tasks_list, return_exceptions=True)
def main():
ips = [(‘10.0.0.‘ + str(ip)) for ip in range(1, 256)]
asyncio.run(run_cmd_in_all_remotes(ips))
if __name__ == ‘__main__‘:
start_time = time.perf_counter()
main()
end_time = time.perf_counter()
print(‘main() runtime {}‘.format(end_time - start_time))(base) [root@wlt-overseas-middleware-master ~]# python su-asyncio-re-cancel.py
b"Trying 10.0.0.2...\r\nConnected to 10.0.0.2.\r\nEscape character is ‘^]‘.\r\nSSH-2.0-OpenSSH_7.4\n"
b"Trying 10.0.0.4...\r\nConnected to 10.0.0.4.\r\nEscape character is ‘^]‘.\r\nSSH-2.0-OpenSSH_7.4\n"
b"Trying 10.0.0.7...\r\nConnected to 10.0.0.7.\r\nEscape character is ‘^]‘.\r\nSSH-2.0-OpenSSH_7.4\n"
上一篇:java学习阶段一 运算符
文章标题:python 协程 - asyncio-subprocess 并发执行命令
文章链接:http://soscw.com/index.php/essay/59300.html