linux – 如何从ifconfig命令捕获第一个IP地址?

如何捕获来自ifconfig命令的第一个IP地址?

ifconfig -a
enw178032: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 100.14.22.12  netmask 255.255.0.0  broadcast 100.14.255.255
        inet6 fe80::250:56ff:fe9c:158a  prefixlen 64  scopeid 0x20<link>
        ether 00:10:56:9c:65:8a  txqueuelen 1000  (Ethernet)
        RX packets 26846250  bytes 12068811576 (11.2 GiB)
        RX errors 0  dropped 58671  overruns 0  frame 0
        TX packets 3368855  bytes 1139160934 (1.0 GiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

预期结果:

IP=100.14.22.12

解决方法:

最好避免使用ifconfig在脚本中获取IP地址,但在某些发行版中不推荐使用它(例如CentOS和其他版本,不再默认安装它).

在其他系统中,ifconfig的输出根据分发的发布而变化(例如,ifconfig的输出/间隔/字段与Debian 8不同,例如Debian 9).

要使用ip获取IP地址,请以类似的方式询问:

ip addr | awk ' !/127.0.0.1/ && /inet/ { gsub(/\/.*/, "", $2); print "IP="$2 } '

或者更好的是:

$ip -o -4  address show  | awk ' NR==2 { gsub(/\/.*/, "", $4); print $4 } '
192.168.1.249

或者,当你问“IP =”时

#!/bin/bash
echo -n "IP="
ip -o -4  address show  | awk ' NR==2 { gsub(/\/.*/, "", $4); print $4 } '

从@Roman无耻地改编这个想法

$ip -o -4  address show  | awk ' NR==2 { gsub(/\/.*/, "", $4); print "IP="$4 } ' 
IP=192.168.1.249

正常输出:

 $ip -o -4  address show 
1: lo    inet 127.0.0.1/8 scope host lo\       valid_lft forever preferred_lft forever
2: eth0    inet 192.168.1.249/24 brd 192.168.1.255 scope global eth0\       valid_lft forever preferred_lft forever

来自man ip:

-o, -oneline
output each record on a single line, replacing line feeds with
the ‘\’ character. This is convenient when you want to count
records with wc(1) or to grep(1) the output.

请参阅一个示例,说明为什么不建议使用ifconfig:BBB: `bbb-conf –check` showing IP addresses as `inet` – ifconfig woes

要了解ifconfig即将发布的原因,请参阅Difference between ‘ifconfig’ and ‘ip’ commands

ifconfig is from net-tools, which hasn’t been able to fully keep up
with the Linux network stack for a long time. It also still uses ioctl
for network configuration, which is an ugly and less powerful way of
interacting with the kernel.

Around 2005 a new mechanism for controlling the network stack was
introduced – netlink sockets.

To configure the network interface iproute2 makes use of that
full-duplex netlink socket mechanism, while ifconfig relies on an
ioctl system call.

上一篇:linux-解决添加的网卡无法识别的问题(转载)


下一篇:CentOS获取公网IP