如何获取给定 IP 地址的以太网端口?
我正在尝试编写一个 bash 脚本来获取我知道其 IP 地址的接口的以太网端口。我需要从 ifconfig 获取这个,但似乎无法弄清楚如何去做。有什么想法吗?
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
将 127.0.0.1 替换为您想要获取其接口信息的 IP 地址
如果您还想识别计算机上的物理端口,请运行
与该接口关联的以太网卡上的指示灯将闪烁
Replace 127.0.0.1 with the ip address you want to get the interface info for
If you also want to identify the physical port on the machine, run
It will blink the light on the ethernet card associated with that interface
有点乱,但应该可以:
或者,您可以使用 ip 命令,在使用时使用
-o|-oneline
选项,解析起来要容易得多。例如A little messy but should work:
Optionally, you could use the ip command which, when used with the
-o|-oneline
option, is a lot easier to parse. For example我可能会使用 grep:
其中“127.0.0.1”是您要查找的地址。
-B1 设置要返回的匹配项之前的行数。
-o 将第二个 grep 设置为仅返回匹配的段,而不是整行。
'^[a-zA-Z0-9]*' 匹配从行开头开始的任何字母数字。
由于 ifconfig 缩进除接口名称行之外的所有行,因此它只会匹配接口名称。
它又快又脏,但应该可以工作。
Off the top of my head I might use grep:
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.