How can I fetch the ethernet port given the ip address?

谁都会走 提交于 2019-12-22 06:10:34

问题


I am trying to write a bash script to fetch the ethernet port of an interface whose IP address I know. I need to grab this from ifconfig but can't seem to be able to figure out how to go about it. Any ideas?

Thanks.


回答1:


A little messy but should work:

/sbin/ifconfig | grep -B1 1.2.3.4 | awk '{print $1; exit}'

Optionally, you could use the ip command which, when used with the -o|-oneline option, is a lot easier to parse. For example

ip -o addr | awk '/1.2.3.4/{print $2}'



回答2:


Replace 127.0.0.1 with the ip address you want to get the interface info for

ifconfig  | grep 127.0.0.1 -B1 | grep Link | cut -f 1 '-d '

If you also want to identify the physical port on the machine, run

ethtool -p $OUTPUT_OF_FIRST_COMMAND

It will blink the light on the ethernet card associated with that interface




回答3:


Off the top of my head I might use grep:

ifconfig |grep -B1 '127.0.0.1' |grep -o '^[a-zA-Z0-9]*'  

Where '127.0.0.1' is the address you're looking for.

-B1 sets the number of lines preceding the match to return.

-o sets the second grep to only return the matching segment, instead of the whole line.

'^[a-zA-Z0-9]*' matches any alphanumerics that start at the beginning of the line.

Since ifconfig indents all lines except the interface name line, it will only match the interface name.

It's quick and dirty, but should work.




回答4:


ifconfig | awk 'BEGIN{RS=""}/127.0.0.1/{print $1}'

ifconfig | ruby -00 -ane 'puts $F[0] if /127.0.0.1/'


来源:https://stackoverflow.com/questions/4986169/how-can-i-fetch-the-ethernet-port-given-the-ip-address

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!