欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python獲取網段內ping通IP的方法

 更新時間:2019年01月31日 10:11:31   作者:前進吧-程序員  
今天小編就為大家分享一篇Python獲取網段內ping通IP的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

問題描述

在某些問題背景下,需要確認是否多臺終端在線,也就是會使用我們牛逼的ping這個命令,做一些的ping操作,如果需要確認的設備比較少,也還能承受。倘若,在手中維護的設備很多。那么這無疑會變成一個惱人的問題。腳本的作用就凸顯了。另外,我們需要使用多線程的一種措施,否則單線程很難在很短的時間內拿到統(tǒng)計結果。

應用背景

有多臺設備需要維護,周期短,重復度高;

單臺設備配備多個IP,需要經常確認網絡是否通常;

等等其他需要確認網絡是否暢通的地方

問題解決

使用python自帶threading模塊,實現多線程的并發(fā)操作。如果本機沒有相關的python模塊,請使用pip install package name安裝之。

threading并發(fā)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中qutip用法示例詳解

    Python中qutip用法示例詳解

    這篇文章主要給大家介紹了關于Python中qutip用法示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-10-10
  • 如何使用scrapy中的ItemLoader提取數據

    如何使用scrapy中的ItemLoader提取數據

    這篇文章主要介紹了如何使用scrapy中的ItemLoader提取數據,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-09-09
  • 使用Python操作ArangoDB的方法步驟

    使用Python操作ArangoDB的方法步驟

    這篇文章主要介紹了使用Python操作ArangoDB的方法步驟,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-02-02
  • linux下安裝python3和對應的pip環(huán)境教程詳解

    linux下安裝python3和對應的pip環(huán)境教程詳解

    這篇文章主要介紹了linux下安裝python3和對應的pip環(huán)境,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下
    2019-07-07
  • Python中處理表格數據的Tablib庫詳解

    Python中處理表格數據的Tablib庫詳解

    這篇文章主要介紹了Python中處理表格數據的Tablib庫詳解,Tablib 是一個 MIT 許可的格式不可知的表格數據集庫,用 Python 編寫,它允許您導入、導出和操作表格數據集,需要的朋友可以參考下
    2023-08-08
  • Pytorch使用visdom可視化問題

    Pytorch使用visdom可視化問題

    這篇文章主要介紹了Pytorch使用visdom可視化問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-06-06
  • python 統(tǒng)計文件中的字符串數目示例

    python 統(tǒng)計文件中的字符串數目示例

    今天小編就為大家分享一篇python 統(tǒng)計文件中的字符串數目示例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-12-12
  • Vs Code中8個好用的python 擴展插件

    Vs Code中8個好用的python 擴展插件

    這篇文章主要介紹了Vs Code中8個好用的python 擴展插件,幫助大家更好的利用vs code進行python開發(fā),感興趣的朋友可以了解下
    2020-10-10
  • python使用JSON模塊進行數據處理(編碼解碼)

    python使用JSON模塊進行數據處理(編碼解碼)

    這篇文章主要為大家介紹了python使用JSON模塊進行數據處理編碼解碼的使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-06-06
  • python對比兩個字典dict的差異詳解

    python對比兩個字典dict的差異詳解

    這篇文章主要為大家詳細介紹了python?如何對比兩個字典dict的不同差異,文中的示例代碼簡潔易懂,具有一定的學習價值,感興趣的可以了解一下
    2023-05-05

最新評論