文章目录
- 一、通过 traceroute 获取网络中的节点
- 二、使用 networkx 进行绘图
- 三、traceroute 部分结果及网络拓扑图
一、通过 traceroute 获取网络中的节点
import os
def exec_command():
website_list = ["120.78.188.0", "www.baidu.com", "www.csdn.net", "www.bilibili.com", "www.nowcoder.com",
"www.leetcode.cn", "www.markji.com", "www.gitee.com", "www.github.com", "www.runoob.com",
"www.zhipin.com", "www.gushiwen.cn", "www.youtube.com", "www.twitter.com", "www.stackoverflow.com",
"www.paypal.com", "www.cacti.net", "www.wargaming.com", "www.sina.com", "www.caida.org",
"www.sohu.com", "www.qq.com", "www.iqiyi.com", "www.zhihu.com", "www.ximalaya.com",
"www.taobao.com", "www.qidian.com", "www.tudou.com", "www.youku.com", "www.jd.com"]
file = open('traceroute.txt', 'w')
index = 1
for website in website_list:
command = "traceroute -n -m 9 -q 1 -w 1 " + website
file.writelines("[" + str(index) + "] " + command + "\n")
index = index + 1
ret = os.popen(command).readlines()
for i in ret:
file.writelines(i)
file.close()
if __name__ == "__main__":
exec_command()
二、使用 networkx 进行绘图
import re
import matplotlib.pyplot as plt
import networkx as nx
def get_node_and_edge():
"""
基于 traceroute 结果提取边和节点
"""
nodes_set = {"127.0.0.1", "192.168.0.1"}
edges_list = []
previous_node = "127.0.0.1"
with open("traceroute.txt", "r") as traceroute:
for i in range(1, 31):
print(traceroute.readline(), end="")
for j in range(1, 10):
line = traceroute.readline()
ip = re.findall(r"\s\s(.*)\s\s", line)
if len(ip):
nodes_set.add(ip[0])
if j == 1:
if "127.0.0.1" != ip[0]:
node_tuple = ("127.0.0.1", ip[0])
else:
if previous_node != ip[0]:
node_tuple = (previous_node, ip[0])
previous_node = ip[0]
edges_list.append(node_tuple)
return edges_list, list(nodes_set)
def draw_network():
"""
绘制网络拓扑图
"""
edges_list, nodes_list = get_node_and_edge()
G = nx.Graph()
for node in nodes_list:
G.add_node(node)
G.add_edges_from(edges_list)
nx.draw(G, with_labels=True, node_size=25, font_size=5)
plt.show()
if __name__ == "__main__":
draw_network()
三、traceroute 部分结果及网络拓扑图
[1] traceroute -n -m 9 -q 1 -w 1 120.78.188.0
1 192.168.0.1 2.451 ms
2 192.168.1.1 3.220 ms
3 10.40.16.1 6.572 ms
4 218.11.136.57 8.558 ms
5 61.182.183.185 11.666 ms
6 61.182.184.169 11.787 ms
7 112.97.0.202 45.623 ms
8 157.148.0.166 64.426 ms
9 211.95.149.242 48.744 ms
[2] traceroute -n -m 9 -q 1 -w 1 www.baidu.com
1 192.168.0.1 2.847 ms
2 192.168.1.1 3.399 ms
3 10.40.16.1 7.472 ms
4 218.11.136.57 8.126 ms
5 61.182.184.13 13.335 ms
6 61.182.184.9 19.884 ms
7 110.242.66.190 17.743 ms
8 221.194.45.134 19.138 ms
9 *
...
...
...
[30] traceroute -n -m 9 -q 1 -w 1 www.jd.com
1 192.168.0.1 2.769 ms
2 192.168.1.1 2.875 ms
3 10.40.16.1 6.300 ms
4 218.11.171.57 8.563 ms
5 61.182.184.5 18.292 ms
6 61.182.184.1 19.421 ms
7 60.9.12.6 31.128 ms
8 *
9 *
![通过 traceroute 和 networkx 构建网络拓扑图_第1张图片](http://img.e-com-net.com/image/info8/d151fc59e4c84d67906d0c44c693a92b.jpg)