How can I detect if a NIC is UP in UNIX?

1

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?

Rich

Posted 2010-09-17T12:11:11.330

Reputation: 1 647

Answers

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.

jfmessier

Posted 2010-09-17T12:11:11.330

Reputation: 2 530

2Networks no longer use classes and colons don't need to be escaped – Paused until further notice. – 2010-09-17T12:33:20.377

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 – 2014-05-25T01:34:24.593

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

user1686

Posted 2010-09-17T12:11:11.330

Reputation: 283 655

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.

Cristian Ciupitu

Posted 2010-09-17T12:11:11.330

Reputation: 4 515

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.

dejo

Posted 2010-09-17T12:11:11.330

Reputation: 1