【问题标题】:Find gateway of an interface查找接口的网关
【发布时间】:2013-09-28 16:44:27
【问题描述】:

对于 bash 集成,我需要从接口检索默认网关。

这是命令 route -n 的输出

Table de routage IP du noyau
Destination     Passerelle      Genmask         Indic Metric Ref    Use Iface
0.0.0.0         p.p.p.p         128.0.0.0       UG    0      0        0 tun0
0.0.0.0         x.x.x.x         0.0.0.0         UG    100    0        0 eth0
10.43.0.1       10.43.0.5       255.255.255.255 UGH   0      0        0 tun0
10.43.0.5       0.0.0.0         255.255.255.255 UH    0      0        0 tun0
y.y.y.y         x.x.x.x         255.255.255.255 UGH   0      0        0 eth0
x.x.x.0         0.0.0.0         255.255.255.0   U     0      0        0 eth0
128.0.0.0       10.43.0.5       128.0.0.0       UG    0      0        0 tun0

我尝试为 Iface tun0 捕获网关(法语中的 Passerelle)。

这个正则表达式正在使用 Rubular:

^[0\.]+\s+([\w\.]+)\s+.*UG.*tun0$

但是这个shell命令不起作用(没有输出):

route -n |egrep -oh '^[0\.]+\s+([\w\.]+)\s+.*UG.*tun0$'

请告诉我为什么?

【问题讨论】:

  • 没有“接口的默认路由”之类的东西。默认路由是在内核路由表中的任何其他路由无法用于告知数据包目的地的情况下采用的路由。也就是说,所有接口只能有一个default route or gateway

标签: regex linux ubuntu grep


【解决方案1】:

为什么不直接使用awk,而不是怪诞的正则表达式?比如:

route -n | grep -e 'UG.*tun0' | awk '{print $2}'

免责声明:我没有测试过这个,所以可能有错别字......

【讨论】:

  • Thx,我找到了解决方案,我不知道 awk 命令的存在:)
【解决方案2】:

尝试这样做(只有一个管道):

route -n | 
    awk -viface=eth0 '{if ($1 == "0.0.0.0" && $8 == iface) {print $2;exit}}'

甚至更好:

ip route |
    awk -viface=eth0 '{
        if ($1 == "default" && $2 == "via" && $5 == iface) {print $3; exit}
    }'

【讨论】:

  • 根据我的配置,你更好的解决方案不起作用,因为 tun0 接口是 OpenVPN 创建的虚拟接口,它没有“默认通过”路由。但在我看来,在不指定任何接口的情况下检索默认网关是一个更好的解决方案。
  • 你现在可以选择了 ;)
【解决方案3】:

另一个选项,没有 regex 和 awk:

route -n | grep -E "ppp0$" | tr -s ' ' | cut -f 2 -d ' '

【讨论】:

  • @sputnick:没有正则表达式来拆分我的意思。 grep ppp0 也在那里工作
猜你喜欢
  • 2012-01-16
  • 1970-01-01
  • 2012-09-10
  • 1970-01-01
  • 2011-08-21
  • 2017-01-25
  • 2018-08-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多