Python网络检测案例如何实现:从基础到实战的完整指南
目录导读
为什么用Python做网络检测?
网络运维中,频繁需要检测主机是否在线、端口是否开放、网络延迟是否正常,传统手工操作效率低下,而Python凭借其丰富的第三方库(如socket、ping3、requests)和简洁语法,成为网络检测自动化方案的理想选择,通过编写脚本,你可以轻松实现定时检测、结果记录、报警通知等功能。
必备工具与库
- socket:Python标准库,用于创建网络连接、扫描端口
- ping3:纯Python实现的ICMP Ping库,无需系统命令
- requests:HTTP请求库,适合检测Web服务状态
- concurrent.futures:多线程库,加速并发检测
- time & datetime:处理时间与定时任务
安装命令:
pip install ping3 requests
基础案例:Ping检测脚本
代码示例
import ping3
import time
def ping_host(host):
try:
rtt = ping3.ping(host, timeout=2)
if rtt is not None:
print(f"[OK] {host} 延迟: {rtt*1000:.2f}ms")
return True
else:
print(f"[FAIL] {host} 超时")
return False
except Exception as e:
print(f"[ERROR] {host}: {e}")
return False
# 批量检测
hosts = ["8.8.8.8", "192.168.1.1", "google.com"]
for host in hosts:
ping_host(host)
time.sleep(1)
运行效果:
[OK] 8.8.8.8 延迟: 12.34ms
[FAIL] 192.168.1.1 超时
[OK] google.com 延迟: 45.67ms
进阶案例:多端口扫描与状态监控
端口开放检测
import socket
from concurrent.futures import ThreadPoolExecutor
def check_port(host, port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(1.5)
result = sock.connect_ex((host, port))
sock.close()
if result == 0:
return f"[OPEN] {host}:{port}"
else:
return f"[CLOSED] {host}:{port}"
# 多线程扫描80、443、8080端口
host = "your-server-domain-example"
ports = [80, 443, 8080]
with ThreadPoolExecutor(max_workers=5) as executor:
futures = [executor.submit(check_port, host, p) for p in ports]
for future in futures:
print(future.result())
说明:使用socket.connect_ex返回0表示端口开放,适合快速检测,结合线程池可秒级扫描数百个端口。
实战案例:网络连通性与延迟检测系统
完整模块化设计
配置组件
import json
from datetime import datetime
def load_config(path="config.json"):
with open(path, "r") as f:
return json.load(f)
# config.json示例
# {
# "targets": [{"host": "api.example.com", "type": "ping"},
# {"host": "web.example.com", "port": 443, "type": "port"}],
# "interval": 60,
# "alarm": {"email": "admin@example.com"}
# }
核心检测引擎
def unified_check(target):
host = target["host"]
if target["type"] == "ping":
rtt = ping3.ping(host, timeout=3)
status = "ok" if rtt else "fail"
return status, host, f"{rtt*1000:.1f}ms" if rtt else "N/A"
elif target["type"] == "port":
port = target["port"]
sock = socket.socket()
sock.settimeout(2)
result = sock.connect_ex((host, port))
sock.close()
status = "ok" if result == 0 else "fail"
return status, host+":"+str(port), "open" if result==0 else "closed"
else:
return "error", host, "unknown type"
# 循环检测
config = load_config()
interval = config["interval"]
while True:
for t in config["targets"]:
status, target, info = unified_check(t)
print(f"[{datetime.now()}] {status.upper()} {target} -> {info}")
time.sleep(interval)
告警集成(简易邮件通知)
import smtplib
def send_alarm(subject, body):
from_addr = "monitor@example.com"
to_addr = config["alarm"]["email"]
msg = f"Subject: {subject}\n\n{body}"
with smtplib.SMTP("smtp.example.com", 587) as server:
server.login(from_addr, "password")
server.sendmail(from_addr, to_addr, msg)
# 在检测到失败时调用
if status == "fail":
send_alarm(f"Network Alert: {target} down", f"Time: {datetime.now()}\nInfo: {info}")
常见问题与优化建议
问题1:Ping超时但主机在线?
- 原因:部分服务器禁用ICMP协议
- 解决:改用TCP端口检测(如80、443)
问题2:多端口扫描太慢?
- 优化:使用
concurrent.futures.ThreadPoolExecutor,线程数控制在50内避免操作系统负载过高
问题3:长时间运行内存泄漏?
- 解决:避免在循环中创建太多对象,使用
gc.collect()或资源上下文管理器
安全与效率提示
- 检测频率不要过高,遵循服务协议(如网站robots.txt)
- 对敏感目标需获得授权
- 建议将结果写入日志文件(如
logging模块)而非仅打印
FAQ问答
Q1:如何检测一个网站是否正常运行(不仅看端口)?
A:用requests.get(url, timeout=5),检查返回状态码200及页面内容关键词。
import requests
try:
r = requests.get("https://example.com", timeout=5)
if r.status_code == 200 and "正常" in r.text:
print("网站服务正常")
else:
print("网站异常")
except requests.exceptions.RequestException:
print("网络不可达")
Q2:能否检测内网设备的MAC地址?
A:Python通过ARP协议检测MAC较复杂,可结合系统命令:subprocess.run(["arp", "-a"], capture_output=True)解析输出。
Q3:如何定时自动运行检测脚本?
A:推荐使用schedule库或系统定时任务(Linux crontab / Windows 任务计划程序),示例:
import schedule
schedule.every(10).minutes.do(job)
while True:
schedule.run_pending()
time.sleep(1)
Q4:检测结果如何存储以便历史分析?
A:使用SQLite或CSV存储,示例(CSV):
import csv
with open("network_log.csv", "a", newline="") as f:
writer = csv.writer(f)
writer.writerow([datetime.now(), target, status, info])
Q5:为什么ping3在某些系统上返回None?
A:可能是权限问题(Linux需root权限发送ICMP包),或是目标设备防火墙阻止了ICMP请求,可尝试sudo运行或改用TCP检测。
通过以上案例,你可以构建从简单Ping到企业级网络检测系统的完整方案,关键在于理解协议原理、善用Python的并发和异常处理机制,并根据实际环境选择检测方式,网络安全检测需遵守法规,仅用于授权网络环境。
标签: Python案例