Python获取网段内ping通IP的方法

 更新时间:2019年01月31日 10:11:31   作者:前进吧-程序员  
今天小编就为大家分享一篇Python获取网段内ping通IP的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

问题描述

在某些问题背景下,需要确认是否多台终端在线,也就是会使用我们牛逼的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的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • OpenCV哈里斯(Harris)角点检测的实现

    OpenCV哈里斯(Harris)角点检测的实现

    这篇文章主要介绍了OpenCV哈里斯 (Harris)角点检测,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-01-01
  • JupyterNotebook设置Python环境的方法步骤

    JupyterNotebook设置Python环境的方法步骤

    这篇文章主要介绍了JupyterNotebook设置Python环境的方法步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-12-12
  • Linux系统下升级pip的完整步骤

    Linux系统下升级pip的完整步骤

    这篇文章主要给大家介绍了关于Linux系统下升级pip的完整步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-01-01
  • python插入排序算法的实现代码

    python插入排序算法的实现代码

    这篇文章主要介绍了python插入排序算法的实现代码,大家参考使用吧
    2013-11-11
  • python基于socket实现网络广播的方法

    python基于socket实现网络广播的方法

    这篇文章主要介绍了python基于socket实现网络广播的方法,涉及Python操作socket的相关技巧,非常具有实用价值,需要的朋友可以参考下
    2015-04-04
  • Python Pandas基础操作详解

    Python Pandas基础操作详解

    这篇文章主要介绍了Python使用Pandas库常见操作,结合实例形式详细分析了Python Pandas模块的功能、原理、数据对象创建、查看、选择等相关操作技巧与注意事项,需要的朋友可以参考下
    2021-10-10
  • python制作企业邮箱的爆破脚本

    python制作企业邮箱的爆破脚本

    这篇文章主要介绍了python制作企业邮箱的爆破脚本的相关资料,需要的朋友可以参考下
    2016-10-10
  • Python实现查找二叉搜索树第k大的节点功能示例

    Python实现查找二叉搜索树第k大的节点功能示例

    这篇文章主要介绍了Python实现查找二叉搜索树第k大的节点功能,结合实例形式分析了Python二叉搜索树的定义、查找、遍历等相关操作技巧,需要的朋友可以参考下
    2019-01-01
  • springboot整合单机缓存ehcache的实现

    springboot整合单机缓存ehcache的实现

    本文主要介绍了springboot整合单机缓存ehcache的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-02-02
  • python中把元组转换为namedtuple方法

    python中把元组转换为namedtuple方法

    在本篇文章里小编给大家整理的是一篇关于python中把元组转换为namedtuple方法,有兴趣的朋友们可以参考下。
    2020-12-12

最新评论