In a Linux environment, I need to detect the physical connected or disconnected state of an RJ45 connector to its socket. Preferably using BASH scripting only.
The
I do all this as normal user (not root)
Grab infos from dmesg
Using dmesg
is one of the 1st things to do for inquiring current state of system:
dmesg | sed '/eth.*Link is/h;${x;p};d'
could answer something like:
[936536.904154] e1000e: eth0 NIC Link is Down
or
[936555.596870] e1000e: eth0 NIC Link is Up 100 Mbps Full Duplex, Flow Control: Rx/Tx
depending on state, message could vary depending on hardware and drivers used.
Nota: this could by written dmesg|grep eth.*Link.is|tail -n1
but I prefer using sed
.
dmesg | sed '/eth.*Link is/h;${x;s/^.*Link is //;p};d'
Up 100 Mbps Full Duplex, Flow Control: Rx/Tx
dmesg | sed '/eth.*Link is/h;${x;s/^.*Link is //;p};d'
Down
Test around /sys
pseudo filesystem
Reading or writting under /sys
could break your system, especially if run as root! You've been warned ;-)
This is a pooling method, not a real event tracking.
cd /tmp
grep -H . /sys/class/net/eth0/* 2>/dev/null >ethstate
while ! read -t 1;do
grep -H . /sys/class/net/eth0/* 2>/dev/null |
diff -u ethstate - |
tee >(patch -p0) |
grep ^+
done
Could render something like (once you've unplugged and plugged back, depending ):
+++ - 2016-11-18 14:18:29.577094838 +0100
+/sys/class/net/eth0/carrier:0
+/sys/class/net/eth0/carrier_changes:9
+/sys/class/net/eth0/duplex:unknown
+/sys/class/net/eth0/operstate:down
+/sys/class/net/eth0/speed:-1
+++ - 2016-11-18 14:18:48.771581903 +0100
+/sys/class/net/eth0/carrier:1
+/sys/class/net/eth0/carrier_changes:10
+/sys/class/net/eth0/duplex:full
+/sys/class/net/eth0/operstate:up
+/sys/class/net/eth0/speed:100
(Hit Enter to exit loop)
Nota: This require patch
to be installed.
In fine, there must already be something about this...
Depending on Linux Installation, you could add if-up
and if-down
scripts to be able to react to this kind of events.
On Debian based (like Ubuntu), you could store your scripts into
/etc/network/if-down.d
/etc/network/if-post-down.d
/etc/network/if-pre-up.d
/etc/network/if-up.d
see man interfaces
for more infos.
There exists two daemons that detect these events:
ifplugd and netplugd
You can use ifconfig.
# ifconfig eth0 up
# ifconfig eth0
If the entry shows RUNNING, the interface is physically connected. This will be shown regardless if the interface is configured.
This is just another way to get the information in /sys/class/net/eth0/operstate
.