Search This Blog

Wednesday, August 28, 2013

Elaborate Linux Script for determining IP

Sometimes the ordering of your Ethernet adapters are not the same on a specific machine vs the others in your cluster.  So simply grepping the IP based on adapter name can be a little tricky.  So I just made this script to do it for you.

#! /usr/bin/env bash
for network in $(cat /proc/net/dev | grep ':' | cut -d: -f1 | awk '{ print $1 }'); do
if [ "$network" != "lo" ]
then
echo $(/sbin/ifconfig $network | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}')
fi
done


Clearly you could modify the if condition to fit your needs.

4 comments:

  1. another way:
    ip -o -4 a | awk '{if ($2 ~ /[^lo]/) print $4}' | cut -d/ -f1

    ReplyDelete
  2. Nice. I wasn't aware awk also supported if conditions. The important thing to remember with both solutions is that you may have more than one adapter, so the if condition will need to be modified to fit the specific interface you're interested in. e.g.

    $ ifconfig -a
    docker0 Link encap:Ethernet HWaddr 56:84:7a:fe:97:99
    inet addr:172.17.42.1 Bcast:0.0.0.0 Mask:255.255.0.0
    UP BROADCAST 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:0
    RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)

    eth0 Link encap:Ethernet HWaddr fa:16:3e:e4:ca:cb
    inet addr:172.16.0.18 Bcast:172.16.255.255 Mask:255.255.0.0
    inet6 addr: fe80::f816:3eff:fee4:cacb/64 Scope:Link
    UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
    RX packets:649673 errors:0 dropped:0 overruns:0 frame:0
    TX packets:398361 errors:0 dropped:0 overruns:0 carrier:0
    collisions:0 txqueuelen:1000
    RX bytes:765872494 (765.8 MB) TX bytes:53054549 (53.0 MB)

    lo Link encap:Local Loopback
    inet addr:127.0.0.1 Mask:255.0.0.0
    inet6 addr: ::1/128 Scope:Host
    UP LOOPBACK RUNNING MTU:65536 Metric:1
    RX packets:59066 errors:0 dropped:0 overruns:0 frame:0
    TX packets:59066 errors:0 dropped:0 overruns:0 carrier:0
    collisions:0 txqueuelen:0
    RX bytes:45734865 (45.7 MB) TX bytes:45734865 (45.7 MB)

    ~$ ip -o -4 a | awk '{if ($2 ~ /[^lo]/) print $4}' | cut -d/ -f1
    172.16.0.18
    172.17.42.1

    Which one is actually eth0? Likely need another conditional check.

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. root@hop:~# ip -o -4 a | awk '{if ($2 ~ /[^lo]/) print $2" "$4}' | cut -d/ -f1
    eth0 172.18.196.236
    virbr0 192.168.122.1
    tun0 10.10.10.5
    vboxnet0 10.20.0.1
    vboxnet1 10.0.2.1
    vboxnet2 10.0.2.1

    ReplyDelete