简体   繁体   English

使用IP地址和AWK Bash检索网络接口的名称

[英]Retrieve the name of a Network Interface using an IP Address and AWK Bash

I am trying to use Bash on CentOS 6.4 to retrieve the network interface name attached to an IP address using AWK. 我试图在CentOS 6.4上使用Bash来检索使用AWK附加到IP地址的网络接口名称。 I have a bit of command from a Solaris box, but I'm not sure how to convert it to Linux output. 我从Solaris盒子里得到了一些命令,但我不确定如何将它转换为Linux输出。

The command looks like this: 该命令如下所示:

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

    '

Its part of a script, so it takes commandline argument like monitor.sh xxxx yyyy and it uses the first xxxx to get the interface name, then makes $1 == $2 so then it can ping yyyy later. 它是脚本的一部分,所以它需要像monitor.sh xxxx yyyy这样的命令行参数,它使用第一个xxxx获取接口名称,然后使$ 1 == $ 2,这样它就可以在以后ping yyyy。 I'm guessing that in Solaris the ifconfig -a output is different than CentOS. 我猜测在Solaris中, ifconfig -a输出与CentOS不同。 I can get the interface name if the IP and interface are on the same line, but in linux, they're on two different lines. 如果IP和接口在同一行,我可以得到接口名称,但在linux中,它们在两个不同的行上。 Any ideas. 有任何想法吗。

I don't have CentOS, but in RHEL, IP address is listed as inet address. 我没有CentOS,但在RHEL中,IP地址被列为inet地址。 I believe they should be same. 我相信他们应该是一样的。

The following command should give you the interface name which has a IP address. 以下命令应该为您提供具有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

And this one should show the IP including localhost : 这个应该显示IP包括localhost:

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

geting ifname for 127.0.0.1 (or any other IP) 为127.0.0.1(或任何其他IP)创建ifname

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

getting ip: 得到ip:

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

Post the output of ifconfig, and I can help you fine tune for your OS 发布ifconfig的输出,我可以帮助您微调您的操作系统

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM