1. 程式人生 > 其它 >獲取網段中ping不通的IP,並將其順序儲存至txt

獲取網段中ping不通的IP,並將其順序儲存至txt

 

import time
import threading
import subprocess
from queue import Queue
from concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED

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): 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 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__': # 網段 10.1.24.0, 你需要的IP數 ip_list = get_ip_list("10.1.24.0", 200) print() # 排序 :reverse = False 是升序,True 是降序 list2 = sorted(ip_list,reverse = False) # 儲存至檔案,儲存的IP換行了,最後一個也換行了,所以有一個空行 with open("D:/file/ip.txt",mode='a',encoding='utf-8') as write_file: for ip in list2: write_file.write(ip+'\n') write_file.close()