在现网中,如果需要一次性检测众多IP中可达和不可达的IP,一个一个手动ping过于繁琐,可以通过python来实现。

MultiPING.py

from queue import Queue
import os, threading
ip_addrs_file = open(r'./src/ips.txt')
ip_addrs = ip_addrs_file.read().splitlines()

num_threads = 8
enclosure_queue = Queue()
print_lock = threading.Lock()

def aping(i,q):
    while True:
        ip = q.get()
        response = os.system("ping -n 2 " + ip + "> NUL")
        with print_lock:
            if response == 0:
                print('\n{}: {} is up'.format(i,ip))
            else:print('\n{}: {} is down'.format(i,ip))
        q.task_done()

def portal():
    for i in range(num_threads):
        thread = threading.Thread(target=aping, args=(i,enclosure_queue,))
        thread.daemon=True
        thread.start()
    for ip_addr in ip_addrs:
        enclosure_queue.put(ip_addr)
    enclosure_queue.join()
    print("*** Script complete ***")

if __name__ == '__main__':
    portal()

IP地址存放在ips.txt文件中,位于和该脚本同一目录下的src文件夹中:

MultiPING_ping

执行MultiPING.py脚本,过程如下:

MultiPING_ping_02