python 协程 - asyncio-subprocess 并发执行命令

1. 10秒钟测试ip段所有IP的连通性

(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"

 参考: 官网 官方文档: https://docs.python.org/zh-cn/3.9/library/asyncio-subprocess.html

posted @ 2021-02-13 00:24  littlevigra  阅读(1382)  评论(0编辑  收藏  举报