本文主要是介绍通过 traceroute 和 networkx 构建网络拓扑图,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
文章目录
- 一、通过 traceroute 获取网络中的节点
- 二、使用 networkx 进行绘图
- 三、traceroute 部分结果及网络拓扑图
一、通过 traceroute 获取网络中的节点
import osdef 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 = 1for website in website_list:command = "traceroute -n -m 9 -q 1 -w 1 " + website # -n 不显示域名 -m 跳数 -q 探测包的个数 -w 响应等待时间file.writelines("[" + str(index) + "] " + command + "\n") # 将命令写入文件index = index + 1ret = os.popen(command).readlines() # 调用系统命令并写到内存中for i in ret:file.writelines(i) # 把命令输出写到文件中file.close()if __name__ == "__main__":exec_command()
二、使用 networkx 进行绘图
import reimport matplotlib.pyplot as plt
import networkx as nxdef get_node_and_edge():"""基于 traceroute 结果提取边和节点"""nodes_set = {"127.0.0.1", "192.168.0.1"} # 节点集合 通过集合自动去重edges_list = [] # 边列表previous_node = "127.0.0.1" # 用于记录每次 traceroute 过程中上一次访问的节点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) # 提取 ip 地址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.01 192.168.0.1 2.451 ms2 192.168.1.1 3.220 ms3 10.40.16.1 6.572 ms4 218.11.136.57 8.558 ms5 61.182.183.185 11.666 ms6 61.182.184.169 11.787 ms7 112.97.0.202 45.623 ms8 157.148.0.166 64.426 ms9 211.95.149.242 48.744 ms
[2] traceroute -n -m 9 -q 1 -w 1 www.baidu.com1 192.168.0.1 2.847 ms2 192.168.1.1 3.399 ms3 10.40.16.1 7.472 ms4 218.11.136.57 8.126 ms5 61.182.184.13 13.335 ms6 61.182.184.9 19.884 ms7 110.242.66.190 17.743 ms8 221.194.45.134 19.138 ms9 *
...
...
...
[30] traceroute -n -m 9 -q 1 -w 1 www.jd.com1 192.168.0.1 2.769 ms2 192.168.1.1 2.875 ms3 10.40.16.1 6.300 ms4 218.11.171.57 8.563 ms5 61.182.184.5 18.292 ms6 61.182.184.1 19.421 ms7 60.9.12.6 31.128 ms8 *9 *
这篇关于通过 traceroute 和 networkx 构建网络拓扑图的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!