Python NetworkX 可视化 Tracert 路由追踪
首先,需要安装 networkx 库和 matplotlib 库。可以使用以下命令进行安装:
pip install networkx
pip install matplotlib
接着,可以使用以下代码实现 tracert 路由追踪可视化:
import subprocess
import re
import networkx as nx
import matplotlib.pyplot as plt
# 获取IP地址和RTT信息
def get_ip_rtt(line):
p = re.compile('\d+\.\d+\.\d+\.\d+')
ip = re.findall(p, line)
p = re.compile('\d+\.?\d*')
rtt = re.findall(p, line)
if len(ip) > 0 and len(rtt) > 0:
return ip[0], float(rtt[-1])
else:
return None, None
# 获取跃点数
def get_hop(line):
p = re.compile('\d+')
hop = re.findall(p, line)
if len(hop) > 0:
return int(hop[0])
else:
return None
# 获取路由追踪结果
def tracert(target):
cmd = ['tracert', '-d', '-w', '100', '-h', '30', target]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
return out.decode('gbk')
# 绘制路由追踪结果
def draw_trace(trace):
G = nx.Graph()
last_hop = 0
last_ip = None
for line in trace.split('\n'):
if 'ms' in line:
hop = get_hop(line)
ip, rtt = get_ip_rtt(line)
if ip is not None and hop is not None:
if hop > last_hop:
G.add_edge(last_ip, ip, weight=rtt)
last_hop = hop
last_ip = ip
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels=True, font_weight='bold')
labels = nx.get_edge_attributes(G, 'weight')
nx.draw_networkx_edge_labels(G, pos, edge_labels=labels)
plt.show()
if __name__ == '__main__':
target = input('请输入目标IP地址:')
trace = tracert(target)
draw_trace(trace)
运行程序后,输入目标IP地址,即可绘制出路由追踪结果的网络拓扑图。每个节点代表一个路由器,每条边代表两个路由器之间的连接,边上的数字代表两个路由器之间的RTT时间。
原文地址: https://www.cveoy.top/t/topic/n31W 著作权归作者所有。请勿转载和采集!