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