Python 編寫多線程 Ping 主機IP的腳本
1. 先編寫一個 Ping 主機IP的腳本
ping_ip.py
import subprocess
import time
# 記錄開始執行的時間
start_time = time.time()
# 定義用來 ping 的254 個 ip
ip_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. 改造成多線程的腳本
ping_threading.py
import threading
import subprocess
import time
from 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.運行效果對比
單線程的運行結果
50個線程的運行結果