On 2023-03-22 10:06, Jeremy Ardley wrote:
On 22/3/23 09:12, f...@dnsbed.com wrote:
Hello,
In my shell script, how to get the localhost's IPs (eth0 and eth1)
correctly?
I know I can run 'ifconfig' and grep etc, but it's maybe not that
graceful.
On Debian the preferred command is
root@debian12:~# ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN
group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: enp0s3: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel
state UP group default qlen 1000
link/ether 08:00:27:18:b6:ac brd ff:ff:ff:ff:ff:ff
inet 10.31.40.166/24 brd 10.31.40.255 scope global dynamic enp0s3
valid_lft 81816sec preferred_lft 81816sec
inet6 2403:5800:c101:b700:a00:27ff:fe18:b6ac/64 scope global
dynamic mngtmpaddr
valid_lft 6667sec preferred_lft 3066sec
inet6 fe80::a00:27ff:fe18:b6ac/64 scope link
valid_lft forever preferred_lft forever
You can also output in .json format
root@debian12:~# ip -j a
[{"ifindex":1,"ifname":"lo","flags":["LOOPBACK","UP","LOWER_UP"],"mtu":65536,"qdisc":"noqueue","operstate":"UNKNOWN","group":"default","txqlen":1000,"link_type":"loopback","address":"00:00:00:00:00:00","broadcast":"00:00:00:00:00:00","addr_info":[{"family":"inet","local":"127.0.0.1","prefixlen":8,"scope":"host","label":"lo","valid_life_time":4294967295,"preferred_life_time":4294967295},{"family":"inet6","local":"::1","prefixlen":128,"scope":"host","valid_life_time":4294967295,"preferred_life_time":4294967295}]},{"ifindex":2,"ifname":"enp0s3","flags":["BROADCAST","MULTICAST","UP","LOWER_UP"],"mtu":1500,"qdisc":"fq_codel","operstate":"UP","group":"default","txqlen":1000,"link_type":"ether","address":"08:00:27:18:b6:ac","broadcast":"ff:ff:ff:ff:ff:ff","addr_info":[{"family":"inet","local":"10.31.40.166","prefixlen":24,"broadcast":"10.31.40.255","scope":"global","dynamic":true,"label":"enp0s3","valid_life_time":81787,"preferred_life_time":81787},{"family":"inet6","local":"2403:5800:c101:
b700:a00:27ff:fe18:b6ac","prefixlen":64,"scope":"global","dynamic":true,"mngtmpaddr":true,"valid_life_time":6638,"preferred_life_time":3037},{"family":"inet6","local":"fe80::a00:27ff:fe18:b6ac","prefixlen":64,"scope":"link","valid_life_time":4294967295,"preferred_life_time":4294967295}]}]
and if you write a script like this (and make it write protected and
executable)
cat ipv4_addresses.py
#!/usr/bin/env python3
import json
import sys
data = sys.stdin.read()
interfaces = json.loads(data)
for interface in interfaces:
ifname = interface['ifname']
for addr_info in interface['addr_info']:
if addr_info['family'] == 'inet':
ipv4 = addr_info['local']
print(f"{ifname}: {ipv4}")
you can do
ip -j a | ./ipv4_addresses.py
lo: 127.0.0.1
enp7s0: 10.31.40.68
or on a fancier setup
Thanks a lot. Now I prefer this way:
$ ip -j a|python3 -mjson.tool
regards.