Problématique
- Extraire l'IP d'une machine Linux
- Problème : la sortie d'
ifconfig
n'est pas la même en fonction des versions des distributions Linux.
Décorticons le problème
- En CentOS/RHEL 5 et 6, mais aussi en Debian 7, le format est :
Sortie de ifconfig (extrait)
eth0 Link encap:Ethernet HWaddr xx:xx:xx:xx:xx:xx inet adr:10.10.10.4 Bcast:10.10.10.255 Masque:255.255.255.0 UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:157294240 errors:0 dropped:0 overruns:0 frame:0 TX packets:267640203 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 lg file transmission:1000 RX bytes:42876676315 (39.9 GiB) TX bytes:41894146069 (39.0 GiB) Interruption:44
- En CentOS/RHEL 7 et Debian 8 :
Sortie de ifconfig (extrait)
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet 10.10.10.3 netmask 255.255.255.0 broadcast 10.10.10.255 inet6 fe80::xxxx:xxxx:xxxx:xxxx prefixlen 64 scopeid 0x20<link> ether xx:xx:xx:xx:xx:xx txqueuelen 1000 (Ethernet) RX packets 85334856 bytes 33546825750 (31.2 GiB) RX errors 0 dropped 0 overruns 0 frame 0 TX packets 40354844 bytes 376314967151 (350.4 GiB) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
Solution
Une commande qui marche pour CentOS 5,6,7, ArchLinux, Debian 7,8
ifconfig | grep --color=no inet | grep -v '127.0.0.1\|inet6' | awk '{print $2}' | grep --color=no -o '[1-9][^[:space:]]*'