After encountering several times that the network on a remote host completely dropped during network configuration, making it difficult to restore access, this script was devised. During the debugging period, I set it to run in cron every 5 minutes, and then the script pings Google; if it fails, it applies known working settings.
#!/bin/bash
# Script for restoring network settings in case the server loses internet due to incorrect network configuration
# Requires ifupdown2, install via apt-get install ifupdown2
host=${1:-'8.8.8.8'} # Host to be pinged, defaults to Google or first argument
source='/etc/network/interfaces_work' # Known working network config
destination='/etc/network/interfaces' # System network config
fail_conf='/etc/network/interfaces_fail' # Here failed configs will be stored
DATE=`date +"%H:%M %d/%m/%Y"` # Date and time
log=/home/network_restore.log # Log file
result=$(ping -c 1 $host | grep % | cut -d ' ' -f6) # Ping and save result
if [[ "$result" = '0%' ]];then # If everything is ok
echo $DATE ok >> $log # Log it
else # If no ping
echo $DATE fail >> $log # Log it
echo $DATE >> $fail_conf # Log it
echo >> $fail_conf # Just for convenience
echo >> $fail_conf
echo >> $fail_conf
echo '###################################################' >> $fail_conf
cat $destination >> $fail_conf # Save the failed config
cat $source > $destination # Overwrite
ifdown -a # Bring down the network
ifup -a # Bring up the network with new settings
# sleep 30
# result=$(ping -c 1 $host | grep % | cut -d ' ' -f6) # Ping and save result
#
# if [[ "$result" = '0%' ]];then # If everything is ok
# echo ok #
# else #
# reboot # If it didn't help, try rebooting the system
# fi
fi