Python Linux 路由表查找

发布于 2024-10-16 18:14:29 字数 1614 浏览 2 评论 0原文

我发布了 Python 查找第一个网络跃点 关于尝试查找第一个跃点,并且我越了解想了想,好像用python处理路由表就更容易了。我不是程序员,我不知道自己在做什么。 :p

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

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

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])

I posted Python find first network hop about 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

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.

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

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])

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

深府石板幽径 2024-10-23 18:14:29

使用 pyroute2.IPRoute,获取到某个远程主机的下一跳,这里 - 8.8.8.8:

from pyroute2 import IPRoute

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

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

from pyroute2 import IPRoute

with IPRoute() as ipr:
    print(ipr.route('get', dst='8.8.8.8'))
欢烬 2024-10-23 18:14:29

在 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 或任何其他标准工具。使用子流程模块干净包装这些命令并获取您正在寻找的信息。

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

   /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 cleanly using subprocess module and get the information for what you are looking for.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文