Monday, March 28, 2011

Linux, check interface status

In some cases you might want to check the status of your network interfaces from a script. In a "normal" situation you can just run a ifconfig command and look if your interface is up or down however when you want to do this automated from within a script you do not want the complete output of ifconfig. You might just want a simple "up" or a simple "down" string returned. If you for example want to use this within a custom check in Nagios or Oracle Enterprise Manager.

You have some options, in the example below I will provide a "up" or a "down" string based upon the status of the interface. However you might also go for a even more simplistic way by returning a zero or one value. the script is based upon the fact that you will provide a parameter with the interface name, for example eth0 or en0. in case you provide a interface name that is none existing get a error message something like "ifconfig: interface eth0 does not exist". You can use the standard option to suppress this error message by using the default way to suppers stderr message by adding a "2> /dev/null" at the end of your script.


#!/bin/bash

IFCONFIG="/sbin/ifconfig $1"

ISIT=`$IFCONFIG | grep "UP" | wc -l`;

if test $ISIT -gt 0;
then
echo "up";
else
echo "down";
fi


No comments: