python 协程

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("33[1;{};1m{}33[0m".format(32, stdout))
        re_result = re.findall('Escape character is', stdout)
        if re_result:
            print("33[1;{};1m{}33[0m".format(32, stdout))
    if stderr:
        # print("33[1;{};1m{}33[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...
Connected to 10.0.0.2.
Escape character is '^]'.
SSH-2.0-OpenSSH_7.4
"
b"Trying 10.0.0.4...
Connected to 10.0.0.4.
Escape character is '^]'.
SSH-2.0-OpenSSH_7.4
"
b"Trying 10.0.0.7...
Connected to 10.0.0.7.
Escape character is '^]'.
SSH-2.0-OpenSSH_7.4
"

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

用一个例子来演示会更加清晰
原文地址:https://www.cnblogs.com/hixiaowei/p/14399637.html