查看当前linux服务器的路由表,Python Linux路由表查找

我张贴Pythonfind第一跳的networking首先想find第一跳,我想到的越多,越容易,它似乎是一个进程的Python路由表。 我不是程序员,我不知道我在做什么。 :p

这就是我想到的,我注意到的第一个问题是loopback接口没有显示在/ proc / net / route文件中 – 所以评估127.0.0.0/8会给你默认路由…对于我的应用程序,这并不重要。

还有什么重要的,我俯瞰? parsingip 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])

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

使用pyroute2 .IPRoute,获取下一跳到远程主机的路径,在这里 – 8.8.8.8:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值