Searching...

Script to automatically restart server when connectivity is lost

If you need restart your server whenever you lost connectivity, you can use simple script.
The script checks the connection every 10 minutes

For next steps you will need:


  • Operation system linux (Ubuntu, Debian, Arch linux)
  • Text editor (nano, vim)
  • Sudo user

rc.local variant

With sudo user and text editor open a file /etc/rc.local

sudo nano /etc/rc.local
Into file add a text

#!/bin/sh
# /etc/rc.local: Local multi-user startup script
while [ 1 ]; do
if [ -z "$(ping -c 1 www.google.com)" ]
then
shutdown -r now
fi
sleep 600
done

exit 0

Save a file and close editor.
Now restart your server for load that script we made, after that your server will be automatically restarted when connection is lost.

systemd variant

With sudo user and text editor open a file /etc/rc.local

sudo nano /etc/rc.local
Into file add a text

#!/bin/sh
# /etc/rc.local: Local multi-user startup script
while [ 1 ]; do
if [ -z "$(ping -c 1 www.google.com)" ]
then
shutdown -r now
fi
sleep 600
done

exit 0

Save changes and close editor.
Create new file /usr/lib/systemd/system/rc-local.service

sudo nano /usr/lib/systemd/system/rc-local.service
Into file add a text

[Unit]
Description=/etc/rc.local compatibility

[Service]
Type=oneshot
ExecStart=/etc/rc.local
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target

Save a file and close editor. Set a file for execute.

chmod +x /usr/lib/systemd/system/rc-local.service
Enable and start a script.

sudo systemctl enable rc-local.service
sudo systemctl start rc-local.service

Now whenever your connection is lost, it will be automatically restarted.

Comments

To submit comment you have to be logged-in