使用 Bash 解析 ifconfig 以仅获取我的 IP 地址

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23934425/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 00:51:38  来源:igfitidea点击:

Parse ifconfig to get only my IP address using Bash

macosbashawkifconfig

提问by Fernando Retimo

I want to edit the bashrc file to have a simple function called "myip" to run. As you might guess, the function myip prints only my internal IP address of my machine.

我想编辑 bashrc 文件以运行一个名为“myip”的简单函数。正如您可能猜到的,函数 myip 只打印我机器的内部 IP 地址。

The far as I got working, this is the script:

就我开始工作而言,这是脚本:

ifconfig en1 | awk '{ print }' | sort

Which got my this output:

这得到了我的输出:

10.0.0.12
options=1<PERFORMNUD>
flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST>
fe80::daa2:5eff:fe96:ba2f%en1
d8:a2:5e:96:ba:2f
autoselect
active

I'm working on Mac OS X.

我在 Mac OS X 上工作。

How can I get this done?

我怎样才能做到这一点?

采纳答案by Fernando Retimo

Well, after hours of struggling I finally got it right:

好吧,经过几个小时的挣扎,我终于做对了:

ifconfig en1 | awk '{ print }' | grep -E -o "([0-9]{1,3}[\.]){3}[0-9]{1,3}"

That last part I had missing is just grep a pattern of IP addresses from my list.

我遗漏的最后一部分只是从我的列表中 grep 一个 IP 地址模式。

回答by Etan Reisner

Both the following work here (CentOS 5).

以下两个都在这里工作(CentOS 5)。

ip addr show eth0 | awk ' == "inet" {gsub(/\/.*$/, "", ); print }'

ifconfig eth0 | awk '/inet addr/ {gsub("addr:", "", ); print }'

For OS X (v10.11(El Capitan) at least):

对于 OS X(至少v10.11(El Capitan)):

ifconfig en0 | awk ' == "inet" {print }'

回答by Mariano Ruiz

This is the more "agnostic" way to get the IP address, regardless of you *nix system (Mac OS, Linux), interface name, and even your locale configuration:

这是获取 IP 地址的更“不可知”的方式,无论您使用 *nix 系统(Mac OS、Linux)、接口名称,甚至您的语言环境配置:

ifconfig | grep -E "([0-9]{1,3}\.){3}[0-9]{1,3}" | grep -v 127.0.0.1 | awk '{ print  }' | cut -f2 -d:

If you have more than one active IP, will listed each one in a separated line. If you want just the first IP, add | head -n1to the expression:

如果您有多个活动 IP,将在单独的一行中列出每个 IP。如果您只想要第一个 IP,请添加| head -n1到表达式中:

ifconfig | grep -E "([0-9]{1,3}\.){3}[0-9]{1,3}" \
     | grep -v 127.0.0.1 | awk '{ print  }' | cut -f2 -d: | head -n1

And if you want the IP address of a specific interface, replace the first expression ifconfigby ifconfig INTERFACENAME, for example ifconfig eth0 | grep -E ....

如果你想要一个特定的接口的IP地址,更换一次表达ifconfigifconfig INTERFACENAME,例如ifconfig eth0 | grep -E ...

These are some examples mentioned in this page that fails in some circumstances and why:

这些是本页中提到的一些在某些情况下失败的示例以及原因:

  • ip route ...: the ipcommand isn't installed in OSX machines.
  • hostname -I: the -Ioption is invalid in OSX.
  • ifconfig en0 ...: the interfaces names (eth0, en0) are different in Linux and OSX, and in Linux the name depends also of the interface type (ethXfor ethernet connection, wlanXfor wireless, etc.).
  • python -c 'import socket; print(socket.gethostbyname(socket.gethostname()))': this got me 127.0.1.1(a loopback IP) in Ubuntu Linux 14.04, so doesn't work.
  • ifconfig | grep 'inet addr:' | grep -v 127.0.0.1 | head -n1 | cut -f2 -d: | cut -f1 -d ' ': the Geograph's post is the more close, but doesn't work in some Linux distributions without LANG=enconfigured, because the text inet addr:that greplooks for is output with a different text in other locales, and in Mac OS that label is also different.
  • ip route ...:该ip命令未安装在 OSX 机器上。
  • hostname -I: 该-I选项在 OSX 中无效。
  • ifconfig en0 ...:接口名称 ( eth0, en0) 在 Linux 和 OSX 中不同,在 Linux 中,名称还取决于接口类型(ethX用于以太网连接,wlanX用于无线等)。
  • python -c 'import socket; print(socket.gethostbyname(socket.gethostname()))':这在 Ubuntu Linux 14.04 中得到了我127.0.1.1(一个环回 IP),所以不起作用。
  • ifconfig | grep 'inet addr:' | grep -v 127.0.0.1 | head -n1 | cut -f2 -d: | cut -f1 -d ' ':在Geograph的职位是比较接近,但在一些Linux发行版,而不不起作用LANG=en配置,因为文字inet addr:grep验看是与其他区域设置不同的文本输出,并在Mac OS中该标签也不同。

回答by JSR

In case of eth0, the following works for me. Try to tweak it with the same logic.

在 eth0 的情况下,以下对我有用。尝试用相同的逻辑调整它。

ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print }'  

回答by slm

You can use awkto do both the selecting of the inetline and the parsing of the IP address like so:

您可以使用awk来进行inet行的选择和 IP 地址的解析,如下所示:

$ ip addr ls docker0 | awk '/inet / {print }' | cut -d"/" -f1
172.17.42.1

In the example above, substitute the device handle eth0in for docker0. Also, if you want a pure AWKimplementation, you can do the "cutting" within like so:

在上面的示例中,将设备句柄替换eth0docker0。另外,如果你想要一个纯粹的AWK实现,你可以像这样进行“切割”:

$ ip addr ls docker0 | awk '/inet / {split(, ary, /\//); print ary[1]}'
172.17.42.1

回答by Mike Q

IPv4 Examples using BASH4+

使用 BASH4+ 的 IPv4 示例

Example 1, using hostname:

示例 1,使用主机名:

  hostname -I|cut -d" " -f 1

Example 2,the device is known (and it never changes) :

示例 2,设备是已知的(并且永远不会改变):

  ifconfig ens5 | grep "inet" | awk '{print }' |  sed 's/[^0-9.]*//g'

Example 3, don't now the device (e.g. eth0, eth1, enp0s23, or wpxxx) :

示例 3,不要现在的设备(例如 eth0、eth1、enp0s23 或 wpxxx):

 ip a | awk 'BEGIN{ "hostname -I|cut -d\" \" -f 1" | getline ip}  ~ ip {print "Device: "$NF "  IP: "}'

Example 4, want the network IP address:

例4,想要网络IP地址:

 wget -q -O /dev/stdout http://checkip.dyndns.org/ | cut -d":" -f2 | cut -d \< -f1

enjoy.

请享用。

回答by Baskar

There is another easy way to get the IP address apart from parsing ifconfig.

除了解析 ifconfig 之外,还有另一种简单的方法来获取 IP 地址。

hostname -I -I, --all-ip-addresses all addresses for the host -i, --ip-address addresses for the hostname

hostname -I -I, --all-ip-addresses all addresses for the host -i, --ip-address addresses for the hostname

Ref: http://linux.die.net/man/1/hostname

参考:http: //linux.die.net/man/1/hostname

Example:

例子:

[ec2-user@terraform ~]$ hostname -I
10.10.10.10

[ec2-user@terraform ~]$ 主机名 -I
10.10.10.10

回答by John Zwinck

No need to do unportable ifconfig parsing in Bash. It's a trivial one-liner in Python:

无需在 Bash 中进行不可移植的 ifconfig 解析。这是 Python 中的一个简单的单行代码:

python -c 'import socket; print(socket.gethostbyname(socket.gethostname()))'

回答by Jonathan Le

If you're looking for just "inet" and not "inet6", this works for me:

如果您只是在寻找“inet”而不是“inet6”,这对我有用:

/usr/bin/ifconfig eth0 | grep --word-regexp inet | awk '{print }'

"--word-regexp" will make grep look for the whole word "inet" and not match partials of words, i.e. "inet" won't match "inet6" - "inet" will only match lines with "inet" in them.

“--word-regexp”将使grep查找整个单词“inet”而不匹配单词的部分,即“inet”不会匹配“inet6” - “inet”只会匹配其中包含“inet”的行.

回答by Charlotte Russell

You can also try this

你也可以试试这个

user@linux:~$ cat script.sh
ifconfig | grep ad.*Bc | cut -d: -f2 | awk '{ print }'
user@linux:~$ 

Output

输出

user@linux:~$ ./script.sh
192.168.1.1
10.0.1.1
user@linux:~$

Please take note that ifconfig output might be different depending on your linux version. Hence, you might want to change the script accordingly.

请注意,ifconfig 输出可能会因您的 linux 版本而异。因此,您可能希望相应地更改脚本。

Btw, this is my ifconfig output

顺便说一句,这是我的 ifconfig 输出

user@linux:~$ ifconfig 
eth0      Link encap:Ethernet  HWaddr 00:00:00:00:00:10  
          inet addr:192.168.1.1  Bcast:192.168.56.255  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:112 errors:0 dropped:0 overruns:0 frame:0
          TX packets:93 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:14616 (14.2 KiB)  TX bytes:17776 (17.3 KiB)

eth1      Link encap:Ethernet  HWaddr 00:00:00:00:00:11
          inet addr:10.0.1.1  Bcast:10.0.1.255  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

user@linux:~$