新聞中心
問(wèn)題描述
在某些問(wèn)題背景下,需要確認(rèn)是否多臺(tái)終端在線,也就是會(huì)使用我們牛逼的ping這個(gè)命令,做一些的ping操作,如果需要確認(rèn)的設(shè)備比較少,也還能承受。倘若,在手中維護(hù)的設(shè)備很多。那么這無(wú)疑會(huì)變成一個(gè)惱人的問(wèn)題。腳本的作用就凸顯了。另外,我們需要使用多線程的一種措施,否則單線程很難在很短的時(shí)間內(nèi)拿到統(tǒng)計(jì)結(jié)果。
應(yīng)用背景
有多臺(tái)設(shè)備需要維護(hù),周期短,重復(fù)度高;
單臺(tái)設(shè)備配備多個(gè)IP,需要經(jīng)常確認(rèn)網(wǎng)絡(luò)是否通常;
等等其他需要確認(rèn)網(wǎng)絡(luò)是否暢通的地方
問(wèn)題解決
使用python自帶threading模塊,實(shí)現(xiàn)多線程的并發(fā)操作。如果本機(jī)沒(méi)有相關(guān)的python模塊,請(qǐng)使用pip install package name安裝之。
threading并發(fā)ping操作代碼實(shí)現(xiàn)
這部分代碼取材于網(wǎng)絡(luò),忘記是不是stackoverflow,這不重要,重要的是這段代碼或者就有價(jià)值,代碼中部分關(guān)鍵位置做了注釋?zhuān)梢宰孕卸xIP所屬的網(wǎng)段,以及使用的線程數(shù)量。從鄙人的觀點(diǎn)來(lái)看是一段相當(dāng)不錯(cuò)的代碼,
# -*- coding: utf-8 -*- import sys import os import platform import subprocess import Queue import threading import ipaddress import re def worker_func(pingArgs, pending, done): try: while True: # Get the next address to ping. address = pending.get_nowait() ping = subprocess.Popen(pingArgs + [address], stdout = subprocess.PIPE, stderr = subprocess.PIPE ) out, error = ping.communicate() if re.match(r".*, 0% packet loss.*", out.replace("\n", "")): done.put(address) # Output the result to the 'done' queue. except Queue.Empty: # No more addresses. pass finally: # Tell the main thread that a worker is about to terminate. done.put(None) # The number of workers. NUM_WORKERS = 14 plat = platform.system() scriptDir = sys.path[0] hosts = os.path.join(scriptDir, 'hosts.txt') # The arguments for the 'ping', excluding the address. if plat == "Windows": pingArgs = ["ping", "-n", "1", "-l", "1", "-w", "100"] elif plat == "Linux": pingArgs = ["ping", "-c", "1", "-l", "1", "-s", "1", "-W", "1"] else: raise ValueError("Unknown platform") # The queue of addresses to ping. pending = Queue.Queue() # The queue of results. done = Queue.Queue() # Create all the workers. workers = [] for _ in range(NUM_WORKERS): workers.append(threading.Thread(target=worker_func, args=(pingArgs, pending, done))) # Put all the addresses into the 'pending' queue. for ip in list(ipaddress.ip_network(u"10.69.69.0/24").hosts()): pending.put(str(ip)) # Start all the workers. for w in workers: w.daemon = True w.start() # Print out the results as they arrive. numTerminated = 0 while numTerminated < NUM_WORKERS: result = done.get() if result is None: # A worker is about to terminate. numTerminated += 1 else: print result # print out the ok ip # Wait for all the workers to terminate. for w in workers: w.join()
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無(wú)理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國(guó)服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡(jiǎn)單易用、服務(wù)可用性高、性?xún)r(jià)比高”等特點(diǎn)與優(yōu)勢(shì),專(zhuān)為企業(yè)上云打造定制,能夠滿足用戶(hù)豐富、多元化的應(yīng)用場(chǎng)景需求。
當(dāng)前標(biāo)題:Python獲取網(wǎng)段內(nèi)ping通IP的方法-創(chuàng)新互聯(lián)
URL鏈接:http://fisionsoft.com.cn/article/cohjgj.html