Ubuntu: wait for network link up and execute a bas

2019-02-20 02:24发布

In Ubuntu (the latest distro is fine), I want to reboot a router and inside a bash script I'd like to have a command that waits for the network link to be up again and, when it detects that, it has to start a bash command.

I could implement this with some kind of polling loop, but the ideal solution would be to have a bash command that, when executed, waits for the link to be up and automatically executes a bash command that I gave to it.

I read something about dbus (and dbus seems the way to go) but it also seems that it takes too much time to fully understand how to use it properly. I was suggested to check if a tool like ethtool was able to do that kind of "wait and execute" but in the man pages I didn't find anything about it.

Note: I forgot to say that I'd like the command to check if the PHYSICAL layer of the link is up. So solutions working at upper layers are not accepted. Moreover, solutions involving putting scripts inside directories (such as/etc/network/if-up.d) are not accepted too.


Any ideas?

Thank you

3条回答
冷血范
2楼-- · 2019-02-20 02:57

The event listener I suggested:

inotifywait -e modify /sys/class/net/eth0/carrier; echo 'Change detected'

When you plug or unplug network cable, it will trigger echo 'Change detected', of course it could trigger just about anything.

And this will run as one off, but I take you know how to make a daemon out of it, if not it will be a good exercise to learn :)

查看更多
再贱就再见
3楼-- · 2019-02-20 02:57

You can check link is up/down by /sys/class/net/eth0/carrier file

cat /sys/class/net/eth0/carrier

if output is 1 then ethernet cable is plugged in and link is up.

if output is 0 then ethernet cable is removed and link is down.

Note:if you have interface other then eth0 then replace interface like eth2/eth3 in place of eth0

查看更多
做个烂人
4楼-- · 2019-02-20 03:02

If you want a command to check if the link is up or down use ip :

ip addr show eth0 | grep -Po "(?<=state ).*?(?=\s)"
DOWN

ip addr show wlan0 | grep -Po "(?<=state ).*?(?=\s)"
UP
查看更多
登录 后发表回答