Python實(shí)現(xiàn)批量檢測(cè)ip地址連通性
實(shí)現(xiàn)代碼
#########################################################################
# File Name: check_ip_test.py
# Author: eight
# Mail: 18847097110@163.com
# Created Time: Thu 11 Apr 2024 08:52:45 AM CST
#########################################################################
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import ipaddress
import subprocess
import re
import json
# 處理單個(gè)IP 的ping請(qǐng)求
def ping_ip(ip):
try:
output = subprocess.check_output(['ping', '-c', '1', ip], stderr=subprocess.STDOUT, universal_newlines=True, timeout=2)
return output
except (subprocess.CalledProcessError, subprocess.TimeoutExpired):
return False
# 處理網(wǎng)段的請(qǐng)求
def scan_network(ip_network):
result_list = []
for ip in ipaddress.IPv4Network(ip_network, strict=False):
ip_str = str(ip)
result = ping_ip(ip_str)
print(f"Begin Ping {ip_str}...")
time_value = ping_test_match(ip_str)
if result:
#print(f"{ip_str} Network communication is normal.")
if time_value:
result_list.append({'ip': ip_str, 'connection': True, 'time': f"{time_value} ms"})
else:
result_list.append({'ip': ip_str, 'connection': True, 'time': '0ms'})
else:
#print(f"{ip_str} Network communication is not normal.")
result_list.append({'ip': ip_str, 'connection': False})
return result_list
# 測(cè)試的請(qǐng)求及正則匹配time時(shí)間
def ping_test_match(ip):
try:
ipaddress.IPv4Address(ip)
#print("The entered address is valid. The connectivity check starts")
ping_output = ping_ip(ip)
if ping_output:
#return "yes"
time_match = re.search(r"time=([\d.]+) ms", ping_output)
if time_match:
time_value = float(time_match.group(1))
return time_value
else:
return None
else:
return None
except ipaddress.AddressValueError:
#print("The entered address is invalid")
return None
# 如果是單個(gè)IP,執(zhí)行第一條,因?yàn)槔么朔椒z測(cè)ip是否是合法的,輸入網(wǎng)段則視為不合法,所以輸入網(wǎng)段會(huì)用except
if __name__ == "__main__":
ip = sys.argv[1]
try:
ipaddress.IPv4Address(ip)
print(ping_test_match(ip))
except ipaddress.AddressValueError:
result_list = scan_network(ip)
#print(json.dumps(result_list))
for item in result_list:
if "time" not in item:
item["time"] = "0ms"
print(json.dumps(result_list)) 代碼詳解
模塊解釋:
- sys: 模塊,用于訪問命令行參數(shù)等系統(tǒng)功能。
- ipaddress: 模塊,用于處理 IP 地址和網(wǎng)絡(luò)。
- subprocess: 模塊,用于執(zhí)行外部命令。
- re:模塊,用于正則表達(dá)式匹配。
- json: 模塊,用于 JSON 數(shù)據(jù)展示
代碼解釋:
ping_ip函數(shù)
1.接收一個(gè) IP 地址作為參數(shù),執(zhí)行 ping 測(cè)試,使用 subprocess.check_output 函數(shù)來運(yùn)行 ping 命令,然后返回命令的輸出。
2.如果 ping 命令執(zhí)行失?。ɡ?,由于超時(shí)或返回非零退出代碼),則會(huì)捕獲 subprocess.CalledProcessError 或 subprocess.TimeoutExpired 異常,并返回 False
scan_network函數(shù)
1.scan_network 函數(shù)接收一個(gè) IP 網(wǎng)段作為參數(shù),然后遍歷該網(wǎng)段中的所有 IP 地址。
2.對(duì)于每個(gè) IP 地址,調(diào)用 ping_ip 函數(shù)執(zhí)行 ping 測(cè)試,調(diào)用ping_test_match函數(shù)獲取time時(shí)間。
3.將結(jié)果存儲(chǔ)在 result 中。
4.最后,根據(jù) ping 測(cè)試的結(jié)果和 ping 時(shí)間,它向 result_list 中添加一個(gè)字典,該字典包含 IP 地址、連接狀態(tài)和 ping 時(shí)間
ping_test_match函數(shù)
1.調(diào)用 ping_ip 函數(shù)的結(jié)果
2.利用正則匹配 time字段
if __name__ == "__main__":
1.獲取傳參
2.如果是單個(gè) IPv4 地址,則執(zhí)行單個(gè) IP 地址的 ping 測(cè)試,并打印結(jié)果。
3.如果無法轉(zhuǎn)換為 IPv4 地址,則將輸入視為 IP 網(wǎng)段,并執(zhí)行ping測(cè)試,將結(jié)果以 JSON 格式打印
效果
執(zhí)行命令必須傳參,否則會(huì)報(bào)錯(cuò)

執(zhí)行某個(gè)網(wǎng)段的測(cè)試

到此這篇關(guān)于Python實(shí)現(xiàn)批量檢測(cè)ip地址連通性的文章就介紹到這了,更多相關(guān)Python檢測(cè)ip連通性內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python中用memcached來減少數(shù)據(jù)庫查詢次數(shù)的教程
這篇文章主要介紹了Python中用memcached來減少數(shù)據(jù)庫查詢次數(shù)的教程,memcached是一種分布式的內(nèi)存緩存工具,使用后可以減少對(duì)硬盤的I/O次數(shù),需要的朋友可以參考下2015-04-04
學(xué)會(huì)這29個(gè)常用函數(shù),你就是Pandas專家
Pandas?無疑是?Python?處理表格數(shù)據(jù)最好的庫之一,但是很多新手無從下手,這里總結(jié)出最常用的?29?個(gè)函數(shù),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2022-11-11
Python利用memory_profiler查看內(nèi)存占用情況
memory_profiler是第三方模塊,用于監(jiān)視進(jìn)程的內(nèi)存消耗以及python程序內(nèi)存消耗的逐行分析。本文將利用memory_profiler查看代碼運(yùn)行占用內(nèi)存情況,感興趣的可以了解一下2022-06-06
python內(nèi)存動(dòng)態(tài)分配過程詳解
這篇文章主要介紹了python內(nèi)存動(dòng)態(tài)分配過程詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-07-07
Python中的np.setdiff1d()函數(shù)詳解
Python中的np.setdiff1d()函數(shù)可用于找出兩個(gè)序列集合中元素的差異,下面通過示例代碼給大家詳細(xì)講解,感興趣的朋友跟隨小編一起看看吧2024-06-06
Python使用OpenCV實(shí)現(xiàn)全景拼接功能
全景拼接是將多張圖像拼接成一張全景圖的技術(shù),本文將詳細(xì)介紹如何使用 Python 和 OpenCV 庫進(jìn)行全景拼接,感興趣的小伙伴可以了解一下2024-11-11

