Python Linux 路由表查找

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4954738/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 02:47:11  来源:igfitidea点击:

Python Linux route table lookup

pythonlinuxnetworkingroutes

提问by tMC

I posted Python find first network hopabout trying to find the first hop and the more I thought about it, the easier it seemed like it would be a process the routing table in python. I'm not a programmer, I don't know what I'm doing. :p

我发布了关于尝试找到第一跳的 Python find first network hop并且我想得越多,它看起来就越容易在 python 中处理路由表。我不是程序员,我不知道我在做什么。:p

This is what I came up with, the first issue I noticed is the loopback interface doesn't show up in the /proc/net/route file- so evaluating 127.0.0.0/8 will give you the default route... for my application, that doesn't matter.

这就是我想出的,我注意到的第一个问题是环回接口没有出现在 /proc/net/route 文件中 - 所以评估 127.0.0.0/8 会给你默认路由......对于我的申请,无所谓。

Anything else major I'm overlooking? Is parsing ip route get <ip>still a better idea?

还有什么我忽略的主要内容吗?解析ip route get <ip>仍然是一个更好的主意吗?

import re
import struct
import socket

'''
   Read all the routes into a list. Most specific first.
   # eth0  000219AC        04001EAC        0003    0       0       0       00FFFFFF ...
'''
def _RtTable():
    _rt = []
    rt_m = re.compile('^[a-z0-9]*\W([0-9A-F]{8})\W([0-9A-F]{8})[\W0-9]*([0-9A-F]{8})')
    rt = open('/proc/net/route', 'r')
    for line in rt.read().split('\n'):
        if rt_m.match(line):
            _rt.append(rt_m.findall(line)[0])

    rt.close()
    return _rt

'''
   Create a temp ip (tip) that is the entered ip with the host 
   section striped off.  Matching to routers in order, 
   the first match should be the most specific.

   If we get 0.0.0.0 as the next hop, the network is likely(?) 
   directly attached- the entered IP is the next (only) hop
'''
def FindGw(ip):
    int_ip = struct.unpack("I", socket.inet_aton(ip))[0]
    for entry in _RtTable():
        tip = int_ip & int(entry[2], 16)
        if tip == int(entry[0], 16):
            gw_s = socket.inet_ntoa(struct.pack("I", int(entry[1], 16)))
            if gw_s == '0.0.0.0':
                return ip
            else:
                return gw_s

if __name__ == '__main__':
    import sys
    print FindGw(sys.argv[1])

采纳答案by Senthil Kumaran

In the man page of proc file system it is given that.

在 proc 文件系统的手册页中给出了这一点。

   /proc/net
          various net pseudo-files, all of which give the status of some part of
          the networking layer.  These files contain ASCII structures and  are,
          there‐fore, readable with cat(1).
          However, the standard netstat(8) suite provides much 
          cleaner access to these files.

Just rely on the tools designed for those purposes. Use netstat, traceroute or any other standard tool. Wrap those commands cleanlyusing subprocess module and get the information for what you are looking for.

只需依赖为这些目的而设计的工具。使用 netstat、traceroute 或任何其他标准工具。使用 subprocess 模块干净地包装这些命令并获取您正在寻找的信息。

回答by svinota

With pyroute2.IPRoute, get the next hop on the way to some distant host, here — 8.8.8.8:

使用pyroute2.IPRoute,在去往某个遥远主机的途中获得下一跳,这里——8.8.8.8:

from pyroute2 import IPRoute

with IPRoute() as ipr:
    print(ipr.route('get', dst='8.8.8.8'))