Python獲取網(wǎng)段內(nèi)ping通IP的方法
問題描述
在某些問題背景下,需要確認(rèn)是否多臺(tái)終端在線,也就是會(huì)使用我們牛逼的ping這個(gè)命令,做一些的ping操作,如果需要確認(rèn)的設(shè)備比較少,也還能承受。倘若,在手中維護(hù)的設(shè)備很多。那么這無疑會(huì)變成一個(gè)惱人的問題。腳本的作用就凸顯了。另外,我們需要使用多線程的一種措施,否則單線程很難在很短的時(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ò)是否暢通的地方
問題解決
使用python自帶threading模塊,實(shí)現(xiàn)多線程的并發(fā)操作。如果本機(jī)沒有相關(guān)的python模塊,請(qǐng)使用pip install package name安裝之。
threading并發(fā)ping操作代碼實(shí)現(xiàn)
這部分代碼取材于網(wǎng)絡(luò),忘記是不是stackoverflow,這不重要,重要的是這段代碼或者就有價(jià)值,代碼中部分關(guān)鍵位置做了注釋,可以自行定義IP所屬的網(wǎng)段,以及使用的線程數(shù)量。從鄙人的觀點(diǎn)來看是一段相當(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()
使用資源池的概念,直接使用gevent這么python模塊提供的相關(guān)功能。
資源池代碼實(shí)現(xiàn)
這部分代碼,是公司的一個(gè)Python方面的大師的作品,鄙人為了這個(gè)主題做了小調(diào)整。還是那句話,只要代碼有價(jià)值,有生命力就是對(duì)的,就是值得的。
# -*- coding: utf-8 -*-
from gevent import subprocess
import itertools
from gevent.pool import Pool
pool = Pool(100) # concurrent action count
ips = itertools.product((10, ), (69, ), (69, ), range(1, 255))
def get_response_time(ip):
try:
out = subprocess.check_output('ping -c 1 -W 1 {}.{}.{}.{}'.format(*ip).split())
for line in out.splitlines():
if '0% packet loss' in line:
return ip
except subprocess.CalledProcessError:
pass
return None
resps = pool.map(get_response_time, ips)
reachable_resps = filter(lambda (ip): ip != None, resps)
for ip in reachable_resps:
print ip
github目錄:git@github.com:qcq/Code.git 下的子目錄utils內(nèi)部。
以上這篇Python獲取網(wǎng)段內(nèi)ping通IP的方法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python自動(dòng)化測(cè)試基礎(chǔ)必備知識(shí)點(diǎn)總結(jié)
在本篇文章里小編給大家分享的是一篇關(guān)于Python自動(dòng)化測(cè)試基礎(chǔ)必備知識(shí)點(diǎn)總結(jié)內(nèi)容,有興趣的朋友們可以學(xué)習(xí)下。2021-02-02
對(duì)Python中GIL(全局解釋器鎖)的一點(diǎn)理解淺析
首先需要明確的一點(diǎn)是GIL并不是Python的特性,它是在實(shí)現(xiàn)Python解析器(CPython)時(shí)所引入的一個(gè)概念,下面這篇文章主要給大家介紹了關(guān)于對(duì)Python中GIL的一點(diǎn)理解,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-05-05
Python實(shí)現(xiàn)AVIF圖片與其他圖片格式間的批量轉(zhuǎn)換
這篇文章主要為大家詳細(xì)介紹了如何使用 Pillow 庫(kù)實(shí)現(xiàn)AVIF與其他格式的相互轉(zhuǎn)換,即將AVIF轉(zhuǎn)換為常見的格式,比如 JPG 或 PNG,需要的小伙伴可以參考下2025-04-04

