【问题标题】:Python Linux route table lookupPython Linux 路由表查找
【发布时间】:2011-06-24 16:39:32
【问题描述】:

我在Python find first network hop 上发布了关于试图找到第一个跃点的信息,我越想越容易,这似乎是 python 中的路由表的一个过程。我不是程序员,我不知道我在做什么。 :p

这就是我想出的,我注意到的第一个问题是环回接口没有显示在 /proc/net/route 文件中 - 因此评估 127.0.0.0/8 将为您提供默认路由.. . 对于我的应用程序来说,这并不重要。

还有什么我忽略的主要内容吗?解析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])

【问题讨论】:

  • 看起来很有趣(当然我也有偏见),但我仍然建议改用ip route get。好处:有人已经为你完成了所有的调试。 =) 例如,他们知道如何处理路线类型之间的差异,包括您已经发现的本地路线的极端情况。 (考虑其他类型:单播、本地、广播、黑洞等)此外,当您开始支持 IPv6 时,ip 将继续为您工作!

标签: python linux networking routes


【解决方案1】:

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

from pyroute2 import IPRoute

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

【讨论】:

    【解决方案2】:

    在 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.
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-29
      • 1970-01-01
      • 2011-09-05
      • 1970-01-01
      • 2012-01-21
      相关资源
      最近更新 更多