Simple script for detecting if internet connection is working and if no then reboot

hal_sk

New Member
Credits
148
Hi,
What is the most efficient way to detect (using terminal) if my internet connection is working. Returned result should be yes or no so I can use it in shell script conditioning and in case the answer is no (no internet connection) then I will command reboot.
Use case: My R-Pi is connected to internet via USB 3G modem. And roughly once in a week the modem from unknown reason disconnects. The solution is to reboot R-Pi because USB modem automatically connect to internet again.
 


f33dm3bits

Gold Member
Gold Supporter
Credits
24,380
Ping your gateway and if it returns and exit code greater than zero have it do an action.
Bash:
#!/bin/bash

ping -c3 192.168.122.1 &> /dev/null
if [ $? -gt 0 ]
then
     sudo reboot
fi
Replacing 192.168.122.1 with the gateway used and assuming the pi user has full sudo rights.
1. Create file with that content in the bin directory of the pi user.
2. Make it executable: chmod +x $HOME/bin/checkgw.sh
3. Add it to in the crontab of the pi user.
Code:
*/5 * * * *  /home/pi/bin/checkgw.sh
 
Last edited:

hal_sk

New Member
Credits
148
Ping your gateway and if it returns and exit code greater than zero have it do an action.
Bash:
#!/bin/bash

ping -c3 192.168.122.1 &> /dev/null
if [ $? -gt 0 ]
then
     sudo reboot
fi
Replacing 192.168.122.1 with the gateway used and assuming the pi user has full sudo rights.
1. Create file with that content in the bin directory of the pi user.
2. Make it executable: chmod +x $HOME/bin/checkgw.sh
3. Add it to in the crontab of the pi user.
Code:
*/5 * * * *  /home/pi/bin/checkgw.sh
Thank you! Will try that later. My R-Pi is in garage checking garage door closed/open status. If I encounter any issue I might show up here again later.
 
$100 Digital Ocean Credit
Get a free VM to test out Linux!


Latest posts

Top