Reputation: 3781
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?
Upvotes: 0
Views: 5792
Reputation: 25687
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 straightforward.
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.
Upvotes: 4
Reputation: 2459
You might be interested in the ip
command. The following example focuses on globally valid IPv4 addresses outputting them in CIDR notation.
# list interfaces that are up
ip -family inet -oneline addr show scope global | awk '{ printf "%s %s up\n", $2, $4 }'
# list interfaces that are down
ip -family inet -oneline link show scope global | grep ' DOWN ' | sed 's/\://g' | awk '{ printf "%s none down\n", $2}'
(Note that the desired netmask representation is omitted in the example.)
As ip
is quite powerful, you might be able to find an even cleaner solution using other parameters.
Upvotes: 0
Reputation: 881467
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).
Upvotes: 3