Python multi-threaded batch ping host IP script

Source: Internet
Author: User

Python writes a multithreaded Ping host IP script 1. Write a script to Ping the host IP first

ping_ip.py

import subprocessimport time# 记录开始执行的时间start_time = time.time()# 定义用来 ping 的254 个 ipip_list = [‘10.3.1.‘+str(i) for i in range(1,255)]  for ip in ip_list:    res = subprocess.call(‘ping -n 2 -w 5 %s‘ % ip,stdout=subprocess.PIPE)  # linux 系统将 ‘-n‘ 替换成 ‘-c‘    print(ip,True if res == 0 else False)print(‘执行所用时间:%s‘ % (time.time() - start_time))
2. Change the script to multiple threads

ping_threading.py

import threadingimport subprocessimport timefrom queue import Queue# 定义工作线程WORD_THREAD = 50# 将需要 ping 的 ip 加入队列IP_QUEUE = Queue() for i in range(1,255):    IP_QUEUE.put(‘10.3.1.‘+str(i))# 定义一个执行 ping 的函数def ping_ip():    while not IP_QUEUE.empty():        ip = IP_QUEUE.get()        res = subprocess.call(‘ping -n 2 -w 5 %s‘ % ip,stdout=subprocess.PIPE)  # linux 系统将 ‘-n‘ 替换成 ‘-c‘        # 打印运行结果        print(ip,True if res == 0 else False)if __name__ == ‘__main__‘:    threads = []    start_time = time.time()    for i in range(WORD_THREAD):        thread = threading.Thread(target=ping_ip)        thread.start()        threads.append(thread)    for thread in threads:        thread.join()    print(‘程序运行耗时:%s‘ % (time.time() - start_time))
3. Comparison of running effect

Single-threaded Run results

Running Results for 50 threads

Python multi-threaded batch ping host IP script

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.