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使用PyFetion来发送短信的例子
Apr 22 Python
修改Python的pyxmpp2中的主循环使其提高性能
Apr 24 Python
分享Python字符串关键点
Dec 13 Python
Python socket网络编程TCP/IP服务器与客户端通信
Jan 05 Python
Python numpy实现二维数组和一维数组拼接的方法
Jun 05 Python
python的一些加密方法及python 加密模块
Jul 11 Python
使用PYTHON解析Wireshark的PCAP文件方法
Jul 23 Python
python Django 创建应用过程图示详解
Jul 29 Python
python脚本之一键移动自定格式文件方法实例
Sep 02 Python
python用WxPython库实现无边框窗体和透明窗体实现方法详解
Feb 21 Python
django迁移文件migrations的实现
Mar 31 Python
keras绘制acc和loss曲线图实例
Jun 15 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经典的给图片加水印程序
2006/12/06 PHP
php实现快速排序法函数代码
2012/08/27 PHP
PHP 面向对象程序设计(oop)学习笔记 (二) - 静态变量的属性和方法及延迟绑定
2014/06/12 PHP
php生成txt文件实例代码介绍
2016/04/28 PHP
PHP中strpos、strstr和stripos、stristr函数分析
2016/06/11 PHP
Symfony查询方法实例小结
2017/06/28 PHP
asp.net网站开发中用jquery实现滚动浏览器滚动条加载数据(类似于腾讯微博)
2012/03/14 Javascript
node.js中的buffer.length方法使用说明
2014/12/14 Javascript
解决jQuery使用JSONP时产生的错误
2015/12/02 Javascript
BootStrap中按钮点击后被禁用按钮的最佳实现方法
2016/09/23 Javascript
详解本地Node.js服务器作为api服务器的解决办法
2017/02/28 Javascript
node.js 中间件express-session使用详解
2017/05/20 Javascript
requirejs按需加载angularjs文件实例
2017/06/08 Javascript
ajax jquery实现页面某一个div的刷新效果
2021/03/04 jQuery
Python合并多个装饰器小技巧
2015/04/28 Python
Python使用chardet判断字符编码
2015/05/09 Python
详细介绍Python的鸭子类型
2016/09/12 Python
python 产生token及token验证的方法
2018/12/26 Python
python二进制读写及特殊码同步实现详解
2019/10/11 Python
python 操作hive pyhs2方式
2019/12/21 Python
Pytorch提取模型特征向量保存至csv的例子
2020/01/03 Python
PyTorch笔记之scatter()函数的使用
2020/02/12 Python
Tensorflow之MNIST CNN实现并保存、加载模型
2020/06/17 Python
达拉斯牛仔官方商店:Dallas Cowboys Pro Shop
2018/02/10 全球购物
屈臣氏官方旗舰店:亚洲享负盛名的保健及美妆零售商
2019/03/15 全球购物
泰国第一在线超市:Tops
2021/02/13 全球购物
简述Linux文件系统通过i节点把文件的逻辑结构和物理结构转换的工作过程
2016/01/06 面试题
无工作经验者个人求职信范文
2013/12/22 职场文书
我的网上商城创业计划书
2013/12/26 职场文书
小学后勤管理制度
2014/01/14 职场文书
大学生秋游活动方案
2014/02/17 职场文书
2015年挂职锻炼工作总结
2014/12/12 职场文书
师范生见习总结范文
2015/06/23 职场文书
婚礼长辈答谢词
2015/09/29 职场文书
创业计划书之废品回收
2019/09/26 职场文书
超详细教你怎么升级Mysql的版本
2021/05/19 MySQL