问题描述
在某些问题背景下,需要确认是否多台终端在线,也就是会使用我们牛逼的ping这个命令,做一些的ping操作,如果需要确认的设备比较少,也还能承受。倘若,在手中维护的设备很多。那么这无疑会变成一个恼人的问题。脚本的作用就凸显了。另外,我们需要使用多线程的一种措施,否则单线程很难在很短的时间内拿到统计结果。
应用背景
有多台设备需要维护,周期短,重复度高;
单台设备配备多个IP,需要经常确认网络是否通常;
等等其他需要确认网络是否畅通的地方
问题解决
使用python自带threading模块,实现多线程的并发操作。如果本机没有相关的python模块,请使用pip install package name安装之。
threading并发ping操作代码实现
这部分代码取材于网络,忘记是不是stackoverflow,这不重要,重要的是这段代码或者就有价值,代码中部分关键位置做了注释,可以自行定义IP所属的网段,以及使用的线程数量。从鄙人的观点来看是一段相当不错的代码,
# -*- 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模块提供的相关功能。
资源池代码实现
这部分代码,是公司的一个Python方面的大师的作品,鄙人为了这个主题做了小调整。还是那句话,只要代码有价值,有生命力就是对的,就是值得的。
# -*- 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内部。
以上这篇Python获取网段内ping通IP的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
Python,ping,IP
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
RTX 5090要首发 性能要翻倍!三星展示GDDR7显存
三星在GTC上展示了专为下一代游戏GPU设计的GDDR7内存。
首次推出的GDDR7内存模块密度为16GB,每个模块容量为2GB。其速度预设为32 Gbps(PAM3),但也可以降至28 Gbps,以提高产量和初始阶段的整体性能和成本效益。
据三星表示,GDDR7内存的能效将提高20%,同时工作电压仅为1.1V,低于标准的1.2V。通过采用更新的封装材料和优化的电路设计,使得在高速运行时的发热量降低,GDDR7的热阻比GDDR6降低了70%。
更新日志
- 群星2013-青春缤纷辑压箱宝大公开3CD2[新加坡限量版][WAV整轨]
- 林育群.2013-BalladShow(日本版)【环球】【WAV+CUE】
- 陈加洛.1992-痛到感觉不到【宝丽金】【WAV+CUE】
- 群星.2023-宿命之敌电视剧原声带【韶愔音乐】【FLAC分轨】
- 東京事変-大発見[FLAC+CUE]
- 椎名林檎-三文ゴシップ[FLAC+CUE]
- 2024年08月04日
- 裘德《裘德「最后的水族馆」演唱会LIVE》[320K/MP3][228.89MB]
- 裘德《裘德「最后的水族馆」演唱会LIVE》[24bit 48kHz][FLAC/分轨][2.08G]
- 基因三重奏《如果你什么都不说 音乐会现场录音》[320K/MP3][145.37MB]
- 孟庭苇.1996-月亮说话(2020环球24KGOLD限量版)【上华】【WAV+CUE】
- 群星.1997-新艺宝优质音响系列·国语精选监听版【新艺宝】【WAV+CUE】
- 阿桑.2005-寂寞在唱歌(星外星引进版)【华研国际】【WAV+CUE】
- 基因三重奏《如果你什么都不说 音乐会现场录音》[FLAC/分轨][287.43MB]
- 蔡题谦《我爱你,却依然要看你走》[320K/MP3][88.65MB]