tags:

views:

269

answers:

2

I know there is ifconfig command that we can list network interface info. but i want to get information in the following pattern

Interface_Name IP_Address Net_Mask Status(up/down)

for example

eth0 192.168.1.1 255.255.255.0 down

I tried ifconfig and grep command but can't get right pattern. There is another command or some trick to do this?

+1  A: 

ifconfig has two output modes -- the default one in which it gives a LOT more output, and the short -s one in which it gives less (or, rather, picks different bits of info from what you'd like). So what about taking ifconfig in the default mode and cherry-picking the specific info you want in a script (python, perl, ruby, awk, bash+sed+..., whatever floats your boat;-). E.g., w/Python:

import re
import subprocess

ifc = subprocess.Popen('ifconfig', stdout=subprocess.PIPE)
res = []
for x in ifc.stdout:
  if not x.strip():
    print ' '.join(res)
    del res[:]
  elif not res:
    res.append(re.match(r'\w+', x).group())
  else:
    mo = re.match(r'\s+inet addr:(\S+).*Mask:(\S+)', x)
    if mo:
      res.extend(mo.groups())
    elif re.match(r'\sUP\s', x):
      res.append('up')
    elif re.match(r'\sDOWN\s', x):
      res.append('down')

if res: print ' '.join(res)

and the output should be as you desire it (easy to translate in any of the other languages I mentioned, I hope).

Alex Martelli
+1  A: 

Python is good :D but let see in bash:

Interfaces=`ifconfig -a \
    | grep -o -e "[a-z][a-z]*[0-9]*[ ]*Link" \
    | perl -pe "s|^([a-z]*[0-9]*)[ ]*Link|\1|"`

for Interface in $Interfaces; do
    INET=`ifconfig $Interface | grep -o -e "inet addr:[^ ]*" | grep -o -e "[^:]*$"`
    MASK=`ifconfig $Interface | grep -o -e "Mask:[^ ]*"      | grep -o -e "[^:]*$"`
    STATUS="up"
    if [ "$INET" == "" ]; then
        INET="-"
        MASK="-"
        STATUS="down";
    fi
    printf "%-10s %-15s %-16s %-4s\n" "$Interface" "$INET" "$MASK" "$STATUS"
done

It is quite stread forward.

This is done on an assumption that 'ifconfig interface does not show an internet address' to means that the interface is down.

I hope this helps.

NawaMan