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 08 Python
Python中断言Assertion的一些改进方案
Oct 27 Python
python并发2之使用asyncio处理并发
Dec 21 Python
78行Python代码实现现微信撤回消息功能
Jul 26 Python
python实现扫描ip地址的小程序
Apr 16 Python
NumPy 基本切片和索引的具体使用方法
Apr 24 Python
python中利用matplotlib读取灰度图的例子
Dec 07 Python
python集合删除多种方法详解
Feb 10 Python
Python如何在main中调用函数内的函数方式
Jun 01 Python
Python调用.net动态库实现过程解析
Jun 05 Python
Python logging模块原理解析及应用
Aug 13 Python
scrapy redis配置文件setting参数详解
Nov 18 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
附件名前加网站名
2008/03/23 PHP
基于wordpress主题制作的具体实现步骤
2013/05/10 PHP
CURL的学习和应用(附多线程实现)
2013/06/03 PHP
PHP中的按位与和按位或操作示例
2014/01/27 PHP
php中current、next与reset函数用法实例
2014/11/17 PHP
Windows7下的php环境配置教程
2015/02/28 PHP
Laravel 5框架学习之环境与配置
2015/04/08 PHP
thinkphp实现分页显示功能
2016/12/03 PHP
实现PHP中session存储及删除变量
2018/10/15 PHP
php使用scandir()函数扫描指定目录下所有文件示例
2019/06/08 PHP
PHP 构造函数和析构函数原理与用法分析
2020/04/21 PHP
jQuery 入门讲解1
2009/04/15 Javascript
jquery 3D球状导航的文章分类
2010/07/06 Javascript
jQuery 自定义函数写法分享
2012/03/30 Javascript
jQuery防止click双击多次提交及传递动态函数或多参数
2014/04/02 Javascript
ECMAScript5中的对象存取器属性:getter和setter介绍
2014/12/08 Javascript
详谈javascript中的cookie
2015/06/03 Javascript
JavaScript模拟鼠标右键菜单效果
2020/12/08 Javascript
vue.js+Element实现表格里的增删改查
2017/01/18 Javascript
js正则表达式验证密码强度【推荐】
2017/03/03 Javascript
NodeJs安装npm包一直失败的解决方法
2017/04/28 NodeJs
[01:38]2018DOTA2亚洲邀请赛主赛事第二日现场采访 神秘商人痛陈生计不易
2018/04/05 DOTA
python 查找文件夹下所有文件 实现代码
2009/07/01 Python
python中numpy的矩阵、多维数组的用法
2018/02/05 Python
Python使用win32 COM实现Excel的写入与保存功能示例
2018/05/03 Python
flask-restful使用总结
2018/12/04 Python
Python中filter与lambda的结合使用详解
2019/12/24 Python
python如何从键盘获取输入实例
2020/06/18 Python
Python+unittest+requests 接口自动化测试框架搭建教程
2020/10/09 Python
英国时尚优质的女装:Hope Fashion
2018/08/14 全球购物
物理教师自荐信范文
2013/12/28 职场文书
大学专科求职信
2014/07/02 职场文书
2014年就业工作总结
2014/11/26 职场文书
学校捐款活动总结
2015/05/09 职场文书
居委会工作总结2015
2015/05/18 职场文书
如何利用pygame实现打飞机小游戏
2021/05/30 Python