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根据距离和时长计算配速示例
Feb 16 Python
python pandas dataframe 行列选择,切片操作方法
Apr 10 Python
numpy.linspace 生成等差数组的方法
Jul 02 Python
TensorFlow 合并/连接数组的方法
Jul 27 Python
Python3实现爬取简书首页文章标题和文章链接的方法【测试可用】
Dec 11 Python
如何用Python破解wifi密码过程详解
Jul 12 Python
基于Django统计博客文章阅读量
Oct 29 Python
Django 创建后台,配置sqlite3教程
Nov 18 Python
python 实现简单的FTP程序
Dec 27 Python
Python random模块制作简易的四位数验证码
Feb 01 Python
python实现简单的tcp 文件下载
Sep 16 Python
在 Python 中利用 Pool 进行多线程
Apr 24 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
浅析PHP的ASCII码转换类
2013/07/05 PHP
什么是PEAR?什么是PECL?PHP中两个容易混淆的概念解释
2015/07/01 PHP
THINKPHP截取中文字符串函数实例代码
2017/03/20 PHP
六款帮助你实现惊艳视差滚动效果的jQuery插件
2012/09/14 Javascript
javascript游戏开发之《三国志曹操传》零部件开发(四)用地图块拼成大地图
2013/01/23 Javascript
jQuery 实现侧边浮动导航菜单效果
2014/12/26 Javascript
JS实现超过长度限制后自动跳转下一款文本框的方法
2015/02/23 Javascript
javascript:void(0)点击登录没反应怎么解决
2015/11/13 Javascript
基于Bootstrap3表格插件和分页插件实例详解
2016/05/17 Javascript
基于js中document.cookie全面解析
2017/09/14 Javascript
bootstrap模态框嵌套、tabindex属性、去除阴影的示例代码
2017/10/17 Javascript
微信小程序返回多级页面的实现方法
2017/10/27 Javascript
微信小程序动态生成二维码的实现代码
2018/07/25 Javascript
关于ckeditor在bootstrap中modal中弹框无法输入的解决方法
2019/09/11 Javascript
浅谈Vue中render中的h箭头函数
2019/11/07 Javascript
vue elementui 实现搜索栏公共组件封装的实例代码
2020/01/20 Javascript
基于js实现数组相邻元素上移下移
2020/05/19 Javascript
Python获取任意xml节点值的方法
2015/05/05 Python
python实现的DES加密算法和3DES加密算法实例
2015/06/03 Python
Python logging设置和logger解析
2019/08/28 Python
Python3将jpg转为pdf文件的方法示例
2019/12/13 Python
Python 中如何使用 virtualenv 管理虚拟环境
2021/01/21 Python
纯CSS实现颜色渐变效果(包含环形渐变、线性渐变、彩虹效果等)
2014/05/07 HTML / CSS
移动端适配 使px自动转换rem
2019/08/26 HTML / CSS
英国领先的汽车轮胎和快速健康中心:Kwik Fit
2017/10/29 全球购物
Java TransactionAPI (JTA) 主要包含几部分
2012/12/07 面试题
大学生职业生涯设计书
2014/01/02 职场文书
物业管理专业自荐信
2014/07/01 职场文书
家庭教育的心得体会
2014/09/01 职场文书
反对四风问题自我剖析材料
2014/09/29 职场文书
2015应届毕业生求职信范文
2015/03/20 职场文书
杨善洲观后感
2015/06/04 职场文书
2016大学生就业指导课心得体会
2016/01/15 职场文书
假期读书倡议书3篇
2019/08/19 职场文书
美甲店的创业计划书模板
2019/08/23 职场文书
python实现简易名片管理系统
2021/04/11 Python