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的几种开发工具介绍
Mar 07 Python
基于python的汉字转GBK码实现代码
Feb 19 Python
python实现的希尔排序算法实例
Jul 01 Python
python感知机实现代码
Jan 18 Python
python实现栅栏加解密 支持密钥加密
Mar 20 Python
pytorch 在sequential中使用view来reshape的例子
Aug 20 Python
python实现while循环打印星星的四种形状
Nov 23 Python
Python和Sublime整合过程图示
Dec 25 Python
Python 从attribute到property详解
Mar 05 Python
Python 程序员必须掌握的日志记录
Aug 17 Python
python中的测试框架
Nov 13 Python
python IP地址转整数
Nov 20 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中使用foreach和引用导致程序BUG的问题介绍
2012/09/05 PHP
Thinkphp模板中截取字符串函数简介
2014/06/17 PHP
PHP依赖倒置(Dependency Injection)代码实例
2014/10/11 PHP
PHP扩展开发教程(总结)
2015/11/04 PHP
php实现网页端验证码功能
2017/07/11 PHP
javascript 对象的定义方法
2007/01/10 Javascript
javascript获取作用在元素上面的样式属性代码
2012/09/20 Javascript
Jquery实现自定义tooltip示例代码
2014/02/12 Javascript
JavaScript数组去重的两种方法推荐
2016/04/05 Javascript
原生 JS Ajax,GET和POST 请求实例代码
2016/06/08 Javascript
jQuery css() 方法动态修改CSS属性
2016/09/25 Javascript
jQuery实现的模拟弹出窗口功能示例
2016/11/24 Javascript
从零开始学习Node.js系列教程五:服务器监听方法示例
2017/04/13 Javascript
js 开发之autocomplete=&quot;off&quot;在chrom中失效的解决办法
2017/09/28 Javascript
JS中使用textPath实现线条上的文字
2017/12/25 Javascript
实战node静态文件服务器的示例代码
2018/03/08 Javascript
Vue解析带html标签的字符串为dom的实例
2019/11/13 Javascript
Tornado Web服务器多进程启动的2个方法
2014/08/04 Python
python分析nignx访问日志脚本分享
2015/02/26 Python
python清除指定目录内所有文件中script的方法
2015/06/30 Python
Django查询数据库的性能优化示例代码
2017/09/24 Python
Python实现的FTP通信客户端与服务器端功能示例
2018/03/28 Python
Python实现接受任意个数参数的函数方法
2018/04/21 Python
对Python3.6 IDLE常用快捷键介绍
2018/07/16 Python
Python实现的批量修改文件后缀名操作示例
2018/12/07 Python
Django中的FBV和CBV用法详解
2019/09/15 Python
python实现WebSocket服务端过程解析
2019/10/18 Python
python打印文件的前几行或最后几行教程
2020/02/13 Python
Python检测端口IP字符串是否合法
2020/06/05 Python
Smashbox英国官网:美国知名彩妆品牌
2017/11/13 全球购物
英国在线电子和小工具商店:TecoBuy
2018/10/06 全球购物
我的中国梦演讲稿高中篇
2014/08/19 职场文书
安全生产月标语
2014/10/07 职场文书
2015年公务员工作总结
2015/04/24 职场文书
趣味运动会口号
2015/12/24 职场文书
macos系统如何实现微信双开? mac登录两个微信以上微信的技巧
2022/07/23 数码科技