如何在给定目的地的 Linux 中获取默认网关?

发布于 2024-07-30 02:44:46 字数 595 浏览 12 评论 0原文

我正在尝试使用目标 0.0.0.0 获取默认网关。

我使用了命令netstat -rn | grep 0.0.0.0 并返回此列表:

Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface
10.9.9.17       0.0.0.0         255.255.255.255 UH        0 0          0 tun0
133.88.0.0      0.0.0.0         255.255.0.0     U         0 0          0 eth0
0.0.0.0         133.88.31.70    0.0.0.0         UG        0 0          0 eth0

我的目标是使用目标 0.0.0.0(即 133.88.31.70) ping 默认网关,但由于使用了grep,这个返回一个列表。

如何仅获取默认网关? 我的 Bash 脚本需要它来确定网络连接是否已启动。

I'm trying to get the default gateway, using the destination 0.0.0.0.

I used the command netstat -rn | grep 0.0.0.0 and it returned this list:

Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface
10.9.9.17       0.0.0.0         255.255.255.255 UH        0 0          0 tun0
133.88.0.0      0.0.0.0         255.255.0.0     U         0 0          0 eth0
0.0.0.0         133.88.31.70    0.0.0.0         UG        0 0          0 eth0

My goal here is to ping the default gateway using the destination 0.0.0.0, which is 133.88.31.70, but this one returns a list because of using grep.

How do I get the default gateway only? I need it for my Bash script to determine whether the network connection is up or not.

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

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

发布评论

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

评论(15

萌梦深 2024-08-06 02:44:47

另一个 Perl 的事情:

$return = (split(" ", `ip route | grep default`))[2];<br>

注意:在 ip 之前和 default 之后使用这些反引号

Another perl thing:

$return = (split(" ", `ip route | grep default`))[2];<br>

Note: use these backticks before ip and after default

凉风有信 2024-08-06 02:44:47

netstat -rn | 网络统计 0.0.0.0 | grep 0.0.0.0 | awk '{print $2}' | grep -v "0.0.0.0"

netstat -rn | grep 0.0.0.0 | awk '{print $2}' | grep -v "0.0.0.0"

落日海湾 2024-08-06 02:44:47
#!/bin/bash

##################################################################3
# Alex Lucard
# June 13 2013
#
# Get the gateway IP address from the router and store it in the variable $gatewayIP
# Get the Router mac address and store it in the variable gatewayRouter
# Store your routers mac address in the variable homeRouterMacAddress
#

# If you need the gateway IP uncomment the next line to get the gateway address and store it in the variable gateWayIP
# gatewayIP=`sudo route -n | awk '/^0.0.0.0/ {print $2}'` 

homeRouterMacAddress="20:aa:4b:8d:cb:7e" # Store my home routers mac address in homeRouterMac.
gatewayRouter=`/usr/sbin/arp -a`

# This if statement will search your gateway router for the mac address you have in the variable homeRouterMacAddress
if `echo ${gatewayRouter} | grep "${homeRouterMacAddress}" 1>/dev/null 2>&1`
then
  echo "You are home"
else
  echo "You are away"
fi
#!/bin/bash

##################################################################3
# Alex Lucard
# June 13 2013
#
# Get the gateway IP address from the router and store it in the variable $gatewayIP
# Get the Router mac address and store it in the variable gatewayRouter
# Store your routers mac address in the variable homeRouterMacAddress
#

# If you need the gateway IP uncomment the next line to get the gateway address and store it in the variable gateWayIP
# gatewayIP=`sudo route -n | awk '/^0.0.0.0/ {print $2}'` 

homeRouterMacAddress="20:aa:4b:8d:cb:7e" # Store my home routers mac address in homeRouterMac.
gatewayRouter=`/usr/sbin/arp -a`

# This if statement will search your gateway router for the mac address you have in the variable homeRouterMacAddress
if `echo ${gatewayRouter} | grep "${homeRouterMacAddress}" 1>/dev/null 2>&1`
then
  echo "You are home"
else
  echo "You are away"
fi
夜还是长夜 2024-08-06 02:44:47

如果您知道 0.0.0.0 是您的预期输出,并且位于行的开头,则可以在脚本中使用以下内容:

IP=`netstat -rn | grep -e '^0\.0\.0\.0' | cut -d' ' -f2`

然后引用变量 ${IP}< /代码>。

最好使用 awk 而不是在这里剪切......即:

IP=`netstat -rn | grep -e '^0\.0\.0\.0' | awk '{print $2}'`

If you know that 0.0.0.0 is your expected output, and will be at the beginning of the line, you could use the following in your script:

IP=`netstat -rn | grep -e '^0\.0\.0\.0' | cut -d' ' -f2`

then reference the variable ${IP}.

It would be better to use awk instead of cut here... i.e.:

IP=`netstat -rn | grep -e '^0\.0\.0\.0' | awk '{print $2}'`
寂寞笑我太脆弱 2024-08-06 02:44:47

使用下面的命令:

route -n | grep '^0\.0\.\0\.0[ \t]\+[1-9][0-9]*\.[1-9][0-9]*\.[1-9][0-9]*\.[1-9][0-9]*[ \t]\+0\.0\.0\.0[ \t]\+[^ \t]*G[^ \t]*[ \t]' | awk '{print $2}'

use command below:

route -n | grep '^0\.0\.\0\.0[ \t]\+[1-9][0-9]*\.[1-9][0-9]*\.[1-9][0-9]*\.[1-9][0-9]*[ \t]\+0\.0\.0\.0[ \t]\+[^ \t]*G[^ \t]*[ \t]' | awk '{print $2}'
半寸时光 2024-08-06 02:44:47

/sbin/route |egrep "^default" |cut -d' ' -f2-12 #and 'cut' 来品尝...

/sbin/route |egrep "^default" |cut -d' ' -f2-12 #and 'cut' to taste...

风启觞 2024-08-06 02:44:47

要获取默认网关的 NIC 名称,请使用以下命令:

netstat -rn | grep UG | awk '{print $8}'

To get the NIC name that it's the default gateway use this command:

netstat -rn | grep UG | awk '{print $8}'
尬尬 2024-08-06 02:44:46

ip 路由 iproute2 包中的命令可以选择路由,而无需使用 awk /grep 等进行选择。

选择默认路由(可能从多个):

$ ip -4 route show default  # use -6 instead of -4 for ipv6 selection.
default via 172.28.206.254 dev wlp0s20f3 proto dhcp metric 600

选择特定接口的下一跃点:

$ ip -4 route list type unicast dev eth0 exact 0/0  # Exact specificity
default via 172.29.19.1 dev eth0

如果有多个默认网关,您可以选择选择哪一个作为到特定目标地址的下一跃点:

$ ip route get $(dig +short google.com | tail -1)
173.194.34.134 via 172.28.206.254 dev wlan0  src 172.28.206.66 
    cache

然后,您可以提取使用 sed/awk/grep 等读取值。这是一个使用 bashread 的示例内置:

$ read _ _ gateway _ < <(ip route list match 0/0); echo "$gateway"
172.28.206.254

The ip route command from the iproute2 package can select routes without needing to use awk/grep, etc to do the selection.

To select the default route (from possibly many):

$ ip -4 route show default  # use -6 instead of -4 for ipv6 selection.
default via 172.28.206.254 dev wlp0s20f3 proto dhcp metric 600

To select the next hop for a particular interface:

$ ip -4 route list type unicast dev eth0 exact 0/0  # Exact specificity
default via 172.29.19.1 dev eth0

In case of multiple default gateways, you can select which one gets chosen as the next hop to a particular destination address:

$ ip route get $(dig +short google.com | tail -1)
173.194.34.134 via 172.28.206.254 dev wlan0  src 172.28.206.66 
    cache

You can then extract the value using sed/awk/grep, etc. Here is one example using bash's read builtin:

$ read _ _ gateway _ < <(ip route list match 0/0); echo "$gateway"
172.28.206.254
病毒体 2024-08-06 02:44:46

您可以使用 ip 命令获取默认网关,如下所示:

IP=$(/sbin/ip route | awk '/default/ { print $3 }')
echo $IP

You can get the default gateway using ip command like this:

IP=$(/sbin/ip route | awk '/default/ { print $3 }')
echo $IP
末が日狂欢 2024-08-06 02:44:46

适用于任何 Linux:

route -n|grep "UG"|grep -v "UGH"|cut -f 10 -d " "

works on any linux:

route -n|grep "UG"|grep -v "UGH"|cut -f 10 -d " "
鹤舞 2024-08-06 02:44:46

这个简单的 perl 脚本将为您完成。

#!/usr/bin/perl

$ns = `netstat -nr`;

$ns =~ m/0.0.0.0\s+([0-9]+.[0-9]+.[0-9]+.[0-9]+)/g;

print $1

基本上,我们运行 netstat,将其保存到 $ns。 然后找到以 0.0.0.0 开头的行。 然后正则表达式中的括号将其中的所有内容保存到 $1 中。 之后,只需打印出来即可。

如果它被称为 null-gw.pl,只需在以下命令上运行它:

perl null-gw.pl

或者如果您需要在 bash 表达式中使用它:

echo $(perl null-gw.pl)

祝你好运。

This simple perl script will do it for you.

#!/usr/bin/perl

$ns = `netstat -nr`;

$ns =~ m/0.0.0.0\s+([0-9]+.[0-9]+.[0-9]+.[0-9]+)/g;

print $1

Basically, we run netstat, save it to $ns. Then find the line that starts off with 0.0.0.0. Then the parentheses in the regex saves everything inside it into $1. After that, simply print it out.

If it was called null-gw.pl, just run it on the command like:

perl null-gw.pl

or if you need it inside a bash expression:

echo $(perl null-gw.pl)

Good luck.

不知在何时 2024-08-06 02:44:46

我就是这样做的:

#!/bin/sh
GATEWAY_DEFAULT=$(ip route list | sed -n -e "s/^default.*[[:space:]]\([[:digit:]]\+\.[[:digit:]]\+\.[[:digit:]]\+\.[[:digit:]]\+\).*/\1/p")
echo ${GATEWAY_DEFAULT}

This is how I do it:

#!/bin/sh
GATEWAY_DEFAULT=$(ip route list | sed -n -e "s/^default.*[[:space:]]\([[:digit:]]\+\.[[:digit:]]\+\.[[:digit:]]\+\.[[:digit:]]\+\).*/\1/p")
echo ${GATEWAY_DEFAULT}
や莫失莫忘 2024-08-06 02:44:46

有关所有默认网关的列表,请使用mezgani的答案,此处重复(并稍作简化) :

/sbin/ip route | awk '/^default/ { print $3 }'

如果您同时配置了多个网络接口,这将打印多个网关。 如果您想按名称选择单个已知网络接口(例如 eth1),除了过滤 ^default 之外,只需搜索该接口即可。行:

/sbin/ip route |grep '^default' | awk '/eth1/ {print $3}'

您可以制作一个脚本,将单个网络接口名称作为参数并打印关联的网关:

#!/bin/bash
if [[ $# -ne 1 ]]; then
    echo "ERROR: must specify network interface name!" >&2
    exit 1
fi
# The third argument of the 'default' line associated with the specified
# network interface is the Gateway.
# By default, awk does not set the exit-code to a nonzero status if a
# specified search string is not found, so we must do so manually.
/sbin/ip route | grep '^default' | awk "/$1/ {print \$3; found=1} END{exit !found}"

如注释中所述,这具有设置合理的退出代码的优点,这在更广泛的编程中可能很有用语境。

For a list of all default gateways, use mezgani's answer, duplicated (and slightly simplified) here:

/sbin/ip route | awk '/^default/ { print $3 }'

If you have multiple network interfaces configured simultaneously, this will print multiple gateways. If you want to select a single known network interface by name (e.g. eth1), simply search for that in addition to filtering for the ^default lines:

/sbin/ip route |grep '^default' | awk '/eth1/ {print $3}'

You can make a script that takes a single network-interface name as an argument and prints the associated gateway:

#!/bin/bash
if [[ $# -ne 1 ]]; then
    echo "ERROR: must specify network interface name!" >&2
    exit 1
fi
# The third argument of the 'default' line associated with the specified
# network interface is the Gateway.
# By default, awk does not set the exit-code to a nonzero status if a
# specified search string is not found, so we must do so manually.
/sbin/ip route | grep '^default' | awk "/$1/ {print \$3; found=1} END{exit !found}"

As noted in the comments, this has the advantage of setting a sensible exit-code, which may be useful in a broader programmatic context.

甲如呢乙后呢 2024-08-06 02:44:46

以下命令仅使用 bash 和 awk 返回 Linux 主机上的默认路由网关 IP:

printf "%d.%d.%d.%d" $(awk '$2 == 00000000 && $7 == 00000000 { for (i = 8; i >= 2; i=i-2) { print "0x" substr($3, i-1, 2) } }' /proc/net/route)

如果您有多个默认网关,只要它们的指标不同(而且它们应该是......),这甚至应该可以工作。

The following command returns the default route gateway IP on a Linux host using only bash and awk:

printf "%d.%d.%d.%d" $(awk '$2 == 00000000 && $7 == 00000000 { for (i = 8; i >= 2; i=i-2) { print "0x" substr($3, i-1, 2) } }' /proc/net/route)

This should even work if you have more than one default gateway as long as their metrics are different (and they should be..).

中二柚 2024-08-06 02:44:46

这里已经有很多答案了。 其中一些是非常特定于发行版的。 对于那些发现这篇文章寻找找到网关的方法,但不需要在代码/批量利用中使用它的人(就像我所做的那样)...尝试:

traceroute www.google.com

第一跳是您的默认网关。

There are a lot of answers here already. Some of these are pretty distro specific. For those who found this post looking for a way to find the gateway, but not needing to use it in code/batch utilization (as I did)... try:

traceroute www.google.com

the first hop is your default gateway.

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