Python 查找第一个网络跃点
我需要找到第一个网络跃点位于 Linux 上的 python 程序中。我不能仅仅依赖默认网关作为第一跳,因为盒子上的一些网络软件可能(或可能不)插入捕获所有路由:
0.0.0.0/1
128.0.0.0/1
我考虑过打开 tracepath -m 1
并解析输出,但我不喜欢依赖于另一个程序的输出。我认为从 /proc 读取路由表并向其应用路由逻辑有点超出了我的脚本编写能力,尽管我可能会在某个时候尝试它。有没有更简单的方法(其他人已经在我不知道的模块中发明了这个轮子)?
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
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)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
“catch all”路线有什么作用?如果它们只是网关路由,则进行路由查找仍然有效。您可以执行以下操作:
这将打印离线路由的网关地址:
...或在线路由的接口名称:
顺便说一下(正如我的回答所暗示的那样)我同意这样的评论:在这种情况下,不依赖外部程序的原则就显得过于谨慎了。 =) 我怀疑
ip
的输出会改变。就我个人而言,我会使用路由查找,因为
tracepath
或traceroute
将依赖于第一跳主机实际向您发送TTL 过期
ICMP 消息(它可能会放弃它)。我不知道你的用例是什么。如果你需要一个Python库来做到这一点,我会研究libdnet。
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:
This would print the gateway address for an off-link route:
... or the interface name for an on-link route:
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.Personally I'd use the route lookup since
tracepath
ortraceroute
would rely on the 1st hop host actually sending you theTTL expired
ICMP message (it might drop it). I don't know what your use case is though.If you need a python library to do this, I'd look into libdnet.