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如何生成随机密码
Apr 20 Python
Python 稀疏矩阵-sparse 存储和转换
May 27 Python
python with提前退出遇到的坑与解决方案
Jan 05 Python
python批量替换页眉页脚实例代码
Jan 22 Python
python TCP Socket的粘包和分包的处理详解
Feb 09 Python
python 除法保留两位小数点的方法
Jul 16 Python
python实现梯度下降算法
Mar 24 Python
深入了解Python iter() 方法的用法
Jul 11 Python
Python利用WMI实现ping命令的例子
Aug 14 Python
python pandas dataframe 去重函数的具体使用
Jul 20 Python
解决tensorflow模型压缩的问题_踩坑无数,总算搞定
Mar 02 Python
关于Python OS模块常用文件/目录函数详解
Jul 01 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
E路文章系统PHP
2006/12/11 PHP
TP5框架实现自定义分页样式的方法示例
2020/04/05 PHP
nicejforms——美化表单不用愁
2007/02/20 Javascript
Extjs根据条件设置表格某行背景色示例
2014/07/23 Javascript
js自动生成的元素与页面原有元素发生堆叠的解决方法
2014/09/04 Javascript
推荐10个2014年最佳的jQuery视频插件
2014/11/12 Javascript
JavaScript插件化开发教程 (二)
2015/01/27 Javascript
jquery中map函数遍历数组用法实例
2015/05/18 Javascript
微信小程序 wxapp内容组件 progress详细介绍
2016/10/31 Javascript
网站发布后Bootstrap框架引用woff字体无法正常显示的解决方法
2016/11/24 Javascript
Vue2.0 vue-source jsonp 跨域请求
2017/08/04 Javascript
详解使用Vue Router导航钩子与Vuex来实现后退状态保存
2017/09/11 Javascript
React Native之prop-types进行属性确认详解
2017/12/19 Javascript
利用es6 new.target来对模拟抽象类的方法
2019/05/10 Javascript
最简单的vue消息提示全局组件的方法
2019/06/16 Javascript
vue 实现Web端的定位功能 获取经纬度
2019/08/08 Javascript
微信小程序实现轨迹回放的示例代码
2019/12/13 Javascript
[33:19]完美世界DOTA2联赛PWL S2 PXG vs InkIce 第一场 11.26
2020/11/30 DOTA
python基于xml parse实现解析cdatasection数据
2014/09/30 Python
Python实现自动登录百度空间的方法
2017/06/10 Python
Python 比较两个数组的元素的异同方法
2017/08/17 Python
Python简直是万能的,这5大主要用途你一定要知道!(推荐)
2019/04/03 Python
Python程序包的构建和发布过程示例详解
2019/06/09 Python
python 整数越界问题详解
2019/06/27 Python
英国时尚高尔夫服装购物网站:Trendy Golf
2020/01/10 全球购物
Wiggle新西兰:自行车、跑步、游泳
2020/05/06 全球购物
初婚未育证明
2014/01/15 职场文书
刘胡兰的英雄事迹材料
2014/02/11 职场文书
校庆筹备方案
2014/03/30 职场文书
亲子阅读的活动方案
2014/08/15 职场文书
九一八事变纪念日演讲稿
2014/09/14 职场文书
2016高校自主招生自荐信范文
2016/01/28 职场文书
《抽屉原理》教学反思
2016/02/20 职场文书
详解Python中的进程和线程
2021/06/23 Python
python中__slots__节约内存的具体做法
2021/07/04 Python
Python与C++中梯度方向直方图的实现
2022/03/17 Python