zoukankan      html  css  js  c++  java
  • 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

    用一个例子来演示会更加清晰
  • 相关阅读:
    JS计算字符串长度(兼容后端PHP)
    使用iview-admin2构建的项目,热更新无法启动
    关于HSTS的总结
    (转)javascript兼容问题总结
    js写一个通讯录
    HTML5+通讯录获取指定多个人的信息
    MUI封装的选择器调用
    心得小细节(一)
    读后感(一) web运作原理探析
    码农和软件开发工程师
  • 原文地址:https://www.cnblogs.com/hixiaowei/p/14399637.html
Copyright © 2011-2022 走看看