Python获取网段内ping通IP的方法


Posted in Python onJanuary 31, 2019

问题描述

在某些问题背景下,需要确认是否多台终端在线,也就是会使用我们牛逼的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 相关文章推荐
python备份文件以及mysql数据库的脚本代码
Jun 10 Python
Python Queue模块详细介绍及实例
Dec 27 Python
利用python将xml文件解析成html文件的实现方法
Dec 22 Python
python3.x上post发送json数据
Mar 04 Python
Python简单计算给定某一年的某一天是星期几示例
Jun 27 Python
python爱心表白 每天都是浪漫七夕!
Aug 18 Python
python实现简单flappy bird
Dec 24 Python
Python实现最常见加密方式详解
Jul 13 Python
python3 自动打印出最新版本执行的mysql2redis实例
Apr 09 Python
Keras 使用 Lambda层详解
Jun 10 Python
python实现将中文日期转换为数字日期
Jul 14 Python
Django利用AJAX技术实现博文实时搜索
May 06 Python
Python实现删除排序数组中重复项的两种方法示例
Jan 31 #Python
python重试装饰器的简单实现方法
Jan 31 #Python
Python实现合并两个有序链表的方法示例
Jan 31 #Python
Django 日志配置按日期滚动的方法
Jan 31 #Python
Python类的继承用法示例
Jan 31 #Python
判断python对象是否可调用的三种方式及其区别详解
Jan 31 #Python
python3使用QQ邮箱发送邮件
May 20 #Python
You might like
封装一个PDO数据库操作类代码
2009/09/09 PHP
深入理解PHP原理之Session Gc的一个小概率Notice
2011/04/12 PHP
在IIS下安装PHP扩展的方法(超简单)
2017/04/10 PHP
javascript setTimeout()传递函数参数(包括传递对象参数)
2010/04/07 Javascript
Array, Array Constructor, for in loop, typeof, instanceOf
2011/09/13 Javascript
file控件选择上传文件确定后触发的js事件是哪个
2014/03/17 Javascript
详解AngularJS中的表达式使用
2015/06/16 Javascript
实例详解AngularJS实现无限级联动菜单
2016/01/15 Javascript
[原创]JQuery 在表单提交之前修改 提交的值
2016/04/14 Javascript
easyui combobox开启搜索自动完成功能的实例代码
2016/11/08 Javascript
js+css3实现旋转效果
2017/01/20 Javascript
BootStrap 获得轮播中的索引和当前活动的焦点对象
2017/05/11 Javascript
Angular中ng-repeat与ul li的多层嵌套重复问题
2017/07/24 Javascript
详解Node全局变量global模块
2017/09/28 Javascript
Laravel整合Bootstrap 4的完整方案(推荐)
2018/01/25 Javascript
[34:10]Secret vs VG 2019国际邀请赛淘汰赛 败者组 BO3 第二场 8.24
2019/09/10 DOTA
python 多线程应用介绍
2012/12/19 Python
python中threading超线程用法实例分析
2015/05/16 Python
详解Python中的Cookie模块使用
2015/07/06 Python
tensorflow入门之训练简单的神经网络方法
2018/02/26 Python
对python .txt文件读取及数据处理方法总结
2018/04/23 Python
Python实现截取PDF文件中的几页代码实例
2019/03/11 Python
如何运行.ipynb文件的图文讲解
2019/06/27 Python
Python pip 常用命令汇总
2020/10/19 Python
python中的yield from语法快速学习
2020/11/06 Python
全世界最美丽的四星和五星级酒店预订:Prestigia.com
2017/11/15 全球购物
C#如何判断当前用户是否输入某个域
2015/12/07 面试题
市场部管理制度
2014/02/02 职场文书
教学评估实施方案
2014/03/16 职场文书
班级活动总结格式
2014/08/30 职场文书
2014年教师节红领巾广播稿
2014/09/10 职场文书
2014教师专业技术工作总结
2014/12/03 职场文书
辩论会主持词
2015/07/03 职场文书
二年级作文之动物作文
2019/11/13 职场文书
深度学习详解之初试机器学习
2021/04/14 Python
win10此电脑打不开怎么办 win10双击此电脑无响应的解决办法
2022/07/23 数码科技