程序我只做了 基本適配,用來識別 操作系統, 進而程序在 windows 和 linux下都能使用,前提是 需要有python環境
#-*- coding: UTF-8 -*- import time import threading import subprocess from queue import Queue from concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED import platform def get_ip_list(net_segment, ip_num): # 創建一個隊列 IP_QUEUE = Queue() ip_list = [] list_segment = net_segment.split('.') ip_index = 1 # 將需要 ping 的 ip 加入隊列 for i in range(1, 254): list_segment[-1] = str(ip_index + i) addr = ('.').join(list_segment) IP_QUEUE.put(addr) # 定義一個執行 ping 的函數 def ping_ip(ip): os_type=platform.system() if os_type=='Windows': res = subprocess.call('ping -n 2 -w 5 %s' % ip,stdout=subprocess.PIPE) # linux 系統將 '-n' 替換成 '-c',增加 'shell=True' else: res = subprocess.call('ping -c 2 -w 5 %s' % ip,shell=True,stdout=subprocess.PIPE) # linux 系統將 '-n' 替換成 '-c',增加 'shell=True' # windows 系統,則使用 'ping -n 2 -w 5 $s' # 打印運行結果 print(ip, True if res == 0 else False) if res != 0: if lock.acquire(): if len(ip_list) < ip_num: ip_list.append(ip) lock.release() # 創建一個最大任務為100的線程池 pool = ThreadPoolExecutor(max_workers=100) lock = threading.Lock() start_time = time.time() all_task = [] while not IP_QUEUE.empty(): all_task.append(pool.submit(ping_ip, IP_QUEUE.get())) # 等待所有任務結束 wait(all_task, return_when=ALL_COMPLETED) print('ping耗時:%s' % (time.time() - start_time)) if len(ip_list) < ip_num: print("Warning:當前網段可用ip不夠,需要數量:%s,可用數量:%s" % (str(ip_num), str(len(ip_list)))) return ip_list if __name__ == '__main__': print(platform.system()) ip_list = get_ip_list("180.8.53.0", 100) ip_list.sort() print(ip_list) print(len(ip_list)) #ping -n 2 -w 5 127.0.0.1 #ping -n 2 -w 5 127.0.0.1