0

I've had frustrating issues with a computer whose network drops at apparently random times and as a work-around I made a simple cron job to restart it every hour. But this seems silly if the network is already up -- why restart it, right?

So is there a simple script I could create that will first check (ping? ifconfig?) to see if the network is working and then only restart if that returns false? Or a flag on network-manager that will check itself?

My cron is just this:

15 * * * * /sbin/service network-manager restart

Thanks in advance to anyone with ideas on how best to "network-manage" this! (pun intended!) :-)

user1149499
  • 573
  • 4
  • 12
  • 30

1 Answers1

1

Call a more complicated script from your crontab:

15 * * * * mySafeRestart


#!/bin/bash  
# mySafeRestart : restart only if uncommunicative
if ! ping -c 1 remote.host.com ; then 
    /sbin/service network-manager restart
fi

As for a test for network up, see How to test an Internet connection with bash?

Using the netcat test suggested below would be:

if ! nc -w 2 google.com 80 ; then
  ...
Dave X
  • 4,831
  • 4
  • 31
  • 42
  • I've seen network connections where a ping works but TCP and UDP packets just cannot make it. I would suggest using `nc` or some such tool to check the network. – Alexis Wilke Mar 15 '17 at 17:06
  • Hi @AlexisWilke, thanks for the comment. Can you offer a similar solution using nc? I had something like the above in mind but if there are serious problems with ping then maybe that's less than ideal. I am not a programmer so any help with that side would be great. – user1149499 Mar 16 '17 at 02:48
  • @user1149499, see here http://stackoverflow.com/questions/4922943/test-from-shell-script-if-remote-tcp-port-is-open#9463554 – Alexis Wilke Mar 16 '17 at 03:17
  • Can I replace the "if ! ping..." line with "if nc -w 2 -v google.com 80 ; then..."? Or is there other syntax for this I need to consider? And would it always be port 80? – user1149499 Mar 16 '17 at 13:23
  • nc versus ping versus ifconfig is more of a question of how you determine if your network is up. There's lots of ways to handle it. If I was using the `nc` in the cron job, I'd drop the `-v`. Testing `if nc -w 2 google.com 80 ; then echo "up" ; fi` looks like the syntax would be fine. – Dave X Mar 16 '17 at 15:52