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
Into file add a text
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.
Into file add a text
Save changes and close editor.
Create new file /usr/lib/systemd/system/rc-local.service
Into file add a text
Save a file and close editor. Set a file for execute.
Enable and start a script.
Now whenever your connection is lost, it will be automatically restarted.
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.localsudo nano /etc/rc.localInto file add a text
#!/bin/sh
# /etc/rc.local: Local multi-user startup scriptwhile [ 1 ]; do
if [ -z "$(ping -c 1 www.google.com)" ]
then
shutdown -r now
fi
sleep 600
done
exit 0Save 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.localsudo nano /etc/rc.localInto file add a text
#!/bin/sh
# /etc/rc.local: Local multi-user startup scriptwhile [ 1 ]; do
if [ -z "$(ping -c 1 www.google.com)" ]
then
shutdown -r now
fi
sleep 600
done
exit 0Save changes and close editor.
Create new file /usr/lib/systemd/system/rc-local.service
sudo nano /usr/lib/systemd/system/rc-local.serviceInto file add a text
[Unit]
Description=/etc/rc.local compatibility
[Service]
Type=oneshot
ExecStart=/etc/rc.local
RemainAfterExit=yes
[Install]
WantedBy=multi-user.targetSave a file and close editor. Set a file for execute.
chmod +x /usr/lib/systemd/system/rc-local.serviceEnable and start a script.
sudo systemctl enable rc-local.service
sudo systemctl start rc-local.serviceNow whenever your connection is lost, it will be automatically restarted.