国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python獲取網段內ping通IP的方法

2020-02-16 01:01:04
字體:
來源:轉載
供稿:網友

問題描述

在某些問題背景下,需要確認是否多臺終端在線,也就是會使用我們牛逼的ping這個命令,做一些的ping操作,如果需要確認的設備比較少,也還能承受。倘若,在手中維護的設備很多。那么這無疑會變成一個惱人的問題。腳本的作用就凸顯了。另外,我們需要使用多線程的一種措施,否則單線程很難在很短的時間內拿到統計結果。

應用背景

有多臺設備需要維護,周期短,重復度高;

單臺設備配備多個IP,需要經常確認網絡是否通常;

等等其他需要確認網絡是否暢通的地方

問題解決

使用python自帶threading模塊,實現多線程的并發操作。如果本機沒有相關的python模塊,請使用pip install package name安裝之。

threading并發ping操作代碼實現

這部分代碼取材于網絡,忘記是不是stackoverflow,這不重要,重要的是這段代碼或者就有價值,代碼中部分關鍵位置做了注釋,可以自行定義IP所屬的網段,以及使用的線程數量。從鄙人的觀點來看是一段相當不錯的代碼,

# -*- coding: utf-8 -*-import sysimport osimport platformimport subprocessimport Queueimport threadingimport ipaddressimport redef 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 = 14plat = 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 = 0while 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()            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 望城县| 西城区| 巴塘县| 东丽区| 公主岭市| 游戏| 樟树市| 郧西县| 黑山县| 贺州市| 白朗县| 宜兰市| 湘西| 吴川市| 信阳市| 于都县| 怀仁县| 华池县| 青神县| 仙桃市| 海城市| 濮阳市| 辛集市| 缙云县| 蕉岭县| 西昌市| 囊谦县| 靖宇县| 阿尔山市| 资兴市| 砚山县| 靖边县| 宾川县| 沐川县| 乐业县| 长海县| 肥西县| 岳阳市| 资阳市| 纳雍县| 九寨沟县|