Python获取网段内ping通IP的方法
作者:前进吧-程序员 时间:2022-01-02 07:26:11
问题描述
在某些问题背景下,需要确认是否多台终端在线,也就是会使用我们牛逼的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内部。
来源:https://blog.csdn.net/u011233383/article/details/51099183
标签:Python,ping,IP
0
投稿
猜你喜欢
利用CSS改善网站可访问性
2010-10-20 20:12:00
MySQL 按指定字段自定义列表排序的实现
2024-01-16 08:09:22
浅谈ES6 模板字符串的具体使用方法
2024-04-18 10:02:01
mysql 5.7.13 安装配置方法图文教程(win10)
2024-01-14 06:51:48
举例讲解Python中装饰器的用法
2022-12-26 17:02:23
js断点调试心得分享(必看篇)
2023-07-06 22:13:25
C++/Php/Python/Shell 程序按行读取文件或者控制台的实现
2021-12-20 06:36:18
Golang依赖注入工具digo的使用详解
2023-08-27 13:00:43
Django的get_absolute_url方法的使用
2023-05-28 02:38:14
Python中Requests-get方法的使用
2021-05-31 08:35:31
python实现爬取百度图片的方法示例
2021-11-22 00:46:04
VSCode必装Go语言以下插件的思路详解
2024-04-30 09:53:42
Python使用回溯法子集树模板获取最长公共子序列(LCS)的方法
2021-04-14 04:55:49
python语言是免费还是收费的?
2021-12-30 10:04:48
Python 实现文件的全备份和差异备份详解
2023-07-16 20:20:36
详解python实现多张多格式图片转PDF并打包成exe
2022-06-16 15:43:38
Python图像处理之直线和曲线的拟合与绘制【curve_fit()应用】
2021-01-28 10:30:49
Django中对通过测试的用户进行限制访问的方法
2021-08-27 16:42:46
Ubuntu18.0.4下mysql 8.0.20 安装配置方法图文教程
2024-01-21 07:10:03
使用Python中PIL库给图片添加文本水印
2021-09-07 19:09:52