找到第一个网络跃点

找到第一个网络跃点

本文介绍了Python找到第一个网络跃点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要找到第一个网络跃点是在Linux上的python程序中。我不能仅仅依靠默认网关作为第一跳,因为包装盒上的某些网络软件可能会(也可能不会)插入来捕获所有路由:

I need to find the first network hop is in a python program on Linux. I can't just depend on the default gateway being the first hop, because some of the network software on the box may (or may not) insert catch all routes:

0.0.0.0/1

128.0.0.0/1

我曾考虑过将 tracepath -m 1< some ip> 弹出并解析输出,但是我不喜欢另一个程序的输出格式。从/ proc读取路由表并对其应用路由逻辑,我认为这超出了我的脚本编写能力,尽管我可能会在某个时候尝试一下。有没有更简单的方法(有人已经在我不知道的模块中发明了这个轮子)?

I've thought about popen'ing a tracepath -m 1 <some ip> and parsing the output, but I dislike depending on the format of the output of another program. Reading the routing table from /proc and applying routing logic to it I think is a little beyond my scripting abilities, though I will likely try it at some point. Is there a an easier way (has someone else already invented-this-wheel in a module I'm not aware of)?

推荐答案

全部捕获路线有什么作用?如果它们只是网关路由,则仍然可以进行路由查找。您可以执行以下操作:

What do the "catch all" routes do? If they are simply gateway routes, doing a route lookup would still work. You can do something like:

$ ip route get <ip> | head -1 | awk '{ print $3 }'

这将打印脱机路由的网关地址:

This would print the gateway address for an off-link route:

$ ip route get 8.8.8.8 | head -1 | awk '{ print $3 }'
192.168.0.1

...或接口名称链接路径:

... or the interface name for an on-link route:

$ ip route get 192.168.0.2 | head -1 | awk '{ print $3 }'
eth0

然后顺便说一句(正如我的回答所暗示的)我同意这样的评论,即在这种情况下, not 依赖于外部程序的原则过于谨慎。 =)我怀疑 ip 的输出是否会更改。

And by the way (as my answer implies) I agree with the comment that the principle of not relying on an external program is overcautious in this case. =) I doubt that the output of ip will change.

我个人会使用 tracepath 或 traceroute 依赖于第一跳主机实际向您发送 TTL过期 ICMP消息(可能会删除它)。我不知道您的用例是什么。

Personally I'd use the route lookup since tracepath or traceroute would rely on the 1st hop host actually sending you the TTL expired ICMP message (it might drop it). I don't know what your use case is though.

如果您需要python库来执行此操作,则可以查看。

If you need a python library to do this, I'd look into libdnet.

这篇关于Python找到第一个网络跃点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 06:41