Python获取网段内ping通IP的方法
作者:前进吧-程序员 发布时间:2022-01-02 07:26:11
标签:Python,ping,IP
问题描述
在某些问题背景下,需要确认是否多台终端在线,也就是会使用我们牛逼的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


猜你喜欢
- 1. OpenCV:模板匹配。 获得小跳棋中心位置2.
- 我们经常会遇到多重查询问题,而长长的SQL语句往往让人丈二和尚摸不着头脑。特别是客户端部分填入查询条件时,如用普通方法将更是难上加难。以下巧
- 随着MYSQL版本的更新以及电脑系统的变化,我们给大家整理了各种电脑环境下安装MYSQL的图解过程,希望我们整理的内容能够帮助到大家:mys
- Python 面向对象编程的三大特性之继承一、继承继承也是面向对象编程三大特性之一继承是类与类的一种关系定义一个新的 class
- 前面简单介绍了Python列表基本操作,这里再来简单讲述一下Python元组相关操作>>> dir(tuple) #查看元
- Python中支持Convex Optimization(凸规划)的模块为CVXOPT,其安装方式为:pip install cvxopt一
- 最近工作中慢慢开始用python协程相关的东西,所以用到了一些相关模块,如aiohttp, aiomysql, aioredis等,用的过程
- 今天修改之前实习小伙伴写的js代码的时候,遇到修改后页面未发生变化的问题。因为我是web开发小白,所以上网查了一波,得以解决~~初次进行we
- 本文实例讲述了Python计算程序运行时间的方法。分享给大家供大家参考。具体实现方法如下:import timedef start_slee
- 示例函数为了开发类型检查器,我们需要一个简单的函数对其进行实验。欧几里得算法就是一个完美的例子: def gcd(a, b):
- 本篇文章是作者关于在学习了《Python学习手册》以后,分享的学习心得,在此之前,我们先给大家分享一下这本书:下载地址:Python学习手册
- renderer是Go语言的一个简单的、轻量的、快速响应的呈现包,它可以支持JSON、JSONP、XML、HYAML、HTML、File等类
- 在各类的前端开发工具里,在功能上虽然Editplus显得有些“单薄”,但是仍然是很多我辈做开发的人们离不开的工具,因为他小巧,语言高亮,支持
- 选择自 xinyuxin912 的 Blog将一个图片以二进制值的形式存入Xml文件中try { &nbs
- 类的私有属性和方法Python是个开放的语言,默认情况下所有的属性和方法都是公开的 或者叫公有方法,不像C++和 Java中有明确的publ
- 项目是基于vue2 的移动端项目,供大家参考,具体内容如下1、实际效果地址 * 联动 mint-ui picker.png2、首先你需要去下载
- pycharm三个有引号不能自动生成函数注释函数注释自动生成函数注释,包括参数和返回值。使用方法,函数定义时,直接输入三个双引号后回车,例如
- 功能说明: 滑动展开/收缩广告效果,可指定:广告完全展开时的停留时间,最大高度。兼容浏览器:IE5.0+、FF1.06+、Opera8.0+
- 本文实例讲述了sql server实现在多个数据库间快速查询某个表信息的方法。分享给大家供大家参考,具体如下:最近出来实习,所在公司的服务器
- 这篇文章我们学习 Python 变量与数据类型变量变量来源于数学,是计算机语言中能储存计算结果或能表示值抽象概念,变量可以通过变量名访问。在