1

I am currently writing a bash script (for Nagios), and I would like to be able to detect if specific network cards are up or not.

My best guess is to do something like this:

ifconfig eth0 | grep UP | wc -l

or:

 ethtool eth0 | grep "Link detected: yes" | wc -l

Are either/both of those reliable ways of testing if the network card is up, or is there a better option? Perhaps there is a flag on ethtool which will do precisely what I want?

4 Answers 4

1

I think this is perhaps the best way to do it. You may want to do some more specific processing on the card, such as the grep you suggested with "Link detected: yes". make sure you escape special characters such as the colon, to make sure it is properly found. Also You can grep on its IP address segment, such as "192.168.25." for a class-C internal IP address. This would be based on your internal networking, whatever it is. But I think this is definitely the best way to do this.

There may also be some ways to actually detect a change, and trigger some event.

2
  • 2
    Networks no longer use classes and colons don't need to be escaped Sep 17, 2010 at 12:33
  • where you wrote "for a class C internal ip address" As they don't use classes anymore, that should read for a /24 internal ip address.
    – barlop
    May 25, 2014 at 1:34
3

Check if interface is up:

ip link show eth0 | grep -qs "[<,]UP[,>]"

Check if it has any IPv4 addresses assigned:

ip -4 addr show eth0 | grep -Eqs "^\s"

In general, grep | wc -l should be replaced with grep -c if you want the match count.

Or grep -qs if you only want "match/no match" based on exit code: if stuff | grep -qs stuff; then ... fi

1

The show command from iproute-3.14.0-2 has this option:

up - only display running interfaces.

So if you run ip link show eth0 up and the interface is down, the output will be empty.

To check it, see question "test if a command returns a string or nothing in bash" from Stack Overflow. Basically something like this should do the trick:

test -n "`ip link show eth0 up`"

It exits with a status of 0 if the eth0 is up.

0

I think link detected… is not enough. You should also grep for the inet addr because even if a link could detect from the switch, the NIC may not has a valid IP address.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .