093. 编写一个函数,实现简单的网络分析工具
以下是一个简单的 Python 网络分析工具的实现示例。这个工具可以完成以下功能:
- 检测网络连通性:检查当前设备是否能够连接到指定的服务器或 IP 地址。
- 测量网络延迟:通过发送 ICMP 请求(ping)来测量到目标服务器的延迟。
- 端口扫描:检测指定主机上的特定端口是否开放。
- 获取网络接口信息:列出当前设备的网络接口及其 IP 地址。
示例代码
import os
import socket
import subprocess
import netifaces as ni
def ping_host(host, count=4):
"""
检测网络连通性,通过发送 ICMP 请求(ping)
:param host: 目标主机的 IP 地址或域名
:param count: 发送的 ICMP 请求次数,默认为 4
:return: 是否成功
"""
try:
# 根据操作系统选择 ping 命令
if os.name == "nt": # Windows
output = subprocess.run(
["ping", "-n", str(count), host], capture_output=True, text=True
)
else: # Linux/MacOS
output = subprocess.run(
["ping", "-c", str(count), host], capture_output=True, text=True
)
print(output.stdout)
return output.returncode == 0
except Exception as e:
print(f"Error during ping: {e}")
return False
def scan_port(host, port):
"""
检测指定主机的端口是否开放
:param host: 目标主机的 IP 地址或域名
:param port: 要检测的端口号
:return: 端口是否开放
"""
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(2) # 设置超时时间
result = sock.connect_ex((host, port))
if result == 0:
print(f"Port {port} on {host} is open.")
return True
else:
print(f"Port {port} on {host} is closed.")
return False
except Exception as e:
print(f"Error during port scan: {e}")
return False
finally:
sock.close()
def get_network_interfaces():
"""
获取当前设备的网络接口信息
:return: 网络接口及其 IP 地址的字典
"""
interfaces = ni.interfaces()
interface_info = {}
for interface in interfaces:
try:
ip = ni.ifaddresses(interface)[ni.AF_INET][0]["addr"]
interface_info[interface] = ip
except (KeyError, IndexError):
pass # 忽略没有 IPv4 地址的接口
return interface_info
def analyze_network():
"""
简单的网络分析工具
"""
print("Network Analysis Tool")
print("---------------------")
# 检测网络连通性
host = input("Enter the host to ping (IP or domain): ")
if ping_host(host):
print("Host is reachable.")
else:
print("Host is not reachable.")
# 端口扫描
port = int(input("Enter the port to scan: "))
if scan_port(host, port):
print("Port is open.")
else:
print("Port is closed.")
# 获取网络接口信息
print("\nNetwork Interfaces:")
interfaces = get_network_interfaces()
for interface, ip in interfaces.items():
print(f" {interface}: {ip}")
# 示例用法
analyze_network()
功能说明
网络连通性检测:
-
使用
subprocess.run
调用系统的ping
命令来检测目标主机是否可达。 -
根据操作系统的不同,选择不同的
ping
命令参数。
端口扫描:
-
使用
socket
模块尝试连接目标主机的指定端口。 -
如果连接成功,则端口开放;否则,端口关闭。
获取网络接口信息:
-
使用
netifaces
库获取当前设备的网络接口及其 IPv4 地址。 -
netifaces
是一个第三方库,需要通过pip install netifaces
安装。
使用方法
- 将上述代码保存为一个
.py
文件。 - 确保安装了
netifaces
库(通过运行pip install netifaces
)。 - 运行脚本后,根据提示输入目标主机的 IP 地址或域名以及要扫描的端口号。
注意事项
-
端口扫描可能需要管理员权限,尤其是在某些操作系统上。
-
网络分析工具可能会受到网络防火墙和安全策略的限制,某些功能可能无法正常工作。
-
如果需要更高级的网络分析功能,可以考虑使用专门的网络分析工具(如
nmap
)或 Python 的scapy
库。
视频讲解
BiliBili: 视睿网络-哔哩哔哩视频 (bilibili.com)