【问题标题】:Retrieve the name of a Network Interface using an IP Address and AWK Bash使用 IP 地址和 AWK Bash 检索网络接口的名称
【发布时间】:2013-08-20 16:57:09
【问题描述】:

我正在尝试在 CentOS 6.4 上使用 Bash 来使用 AWK 检索附加到 IP 地址的网络接口名称。我有一些来自 Solaris 机器的命令,但我不确定如何将其转换为 Linux 输出。

命令如下所示:

ifconfig -a | awk '
    $1 ~ /:/    {split($1,nic,":"); 
                     lastif=sprintf("%s:%s",nic[1],nic[2]);}
    $2 == "'$1'"    { print lastif ; exit; }

    '

它是脚本的一部分,所以它需要像monitor.sh x.x.x.x y.y.y.y 这样的命令行参数,它使用第一个 x.x.x.x 来获取接口名称,然后使 $1 == $2 之后它可以 ping y.y.y.y。我猜想在 Solaris 中ifconfig -a 的输出与 CentOS 不同。如果 IP 和接口在同一行,我可以获得接口名称,但在 linux 中,它们在两条不同的行上。有任何想法吗。

【问题讨论】:

标签: linux bash awk


【解决方案1】:

我没有 CentOS,但在 RHEL 中,IP 地址被列为 inet 地址。我相信它们应该是一样的。

以下命令应该为您提供具有 IP 地址的接口名称。

export iface=$(ifconfig | grep -B1 "inet addr:x.x.x.x" | awk '$1!="inet" && $1!="--" {print $1}')

echo "$iface" # To get the interface name for x.x.x.x ip

这个应该显示IP,包括本地主机:

ifconfig | grep "inet addr:" | sed -e 's/addr:/addr: /g' | awk '{print $3}'

【讨论】:

    【解决方案2】:

    获取 127.0.0.1(或任何其他 IP)的 ifname

    ifconfig | awk '/127.0.0.1/ {print $1}' RS="\n\n"
    lo
    

    获取ip:

    ifconfig | awk -F"[ :]+" '/inet addr:/ {print $4}'
    

    发布 ifconfig 的输出,我可以帮你微调你的操作系统

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-21
      • 2021-01-03
      • 2020-01-14
      • 2019-02-03
      • 2013-03-03
      相关资源
      最近更新 更多