Linux detects if the server is connected to the network

  • 2020-06-03 09:05:47
  • OfStack

Linux detects if the server is connected to the network

Abstract: Every 5 minutes to detect whether the server is connected to the network, if the three detection no network ? Then automatic shutdown! Main usage scenarios: because you have a server on the remote hometown, there are likely to encounter power lead to broken network problems, and there are limits to UPS use time after the blackout, so the script is designed to solve various problems caused by the server when the power suddenly loses power, when power network impassability, also need to automatically shut down the server at this time. Of course, need to manually restart the server after calls!!!!!!


 #!/bin/bash

#  Checks if the server is connected to the network , If the network doesn't work   the  3 After the time   To turn it off 
# crontab -e
# */5 * * * * ./check.sh

echo "Starting test network was clear..."

if test -e ./checkInfo
 then
 echo "CheckInfo File Exist..."
else
 cat /dev/null > ./checkInfo
fi

last_res=`head -1 ./checkInfo`

checkInternet(){
 ping_res=1

 for url in "8.8.8.8" "61.139.2.69" "114.114.114.114" "168.95.1.1" "223.5.5.5" "180.76.76.76"
 do
 echo "PING ${url}"

 ping=`ping -c 3 ${url}|awk 'NR==7 {print $4}'`

 if [ ${ping} -eq 0 ]
  then
  ping_res=1
  else
  ping_res=2
 fi

 if [ ${ping_res} -eq 2 ]
  then
  break
 fi
 done

 return ${ping_res}
}

checkInternet

result="$?"

if [ ${result} -eq 1 ]
 then
 if [ "${last_res}" = "1" ]
  then
  echo "2" > ./checkInfo
 elif [ "${last_res}" = "2" ]
  then
  cat /dev/null > ./checkInfo
  init 0
  else
  echo "1" > ./checkInfo
 fi
 else
 cat /dev/null > ./checkInfo
fi

Thank you for reading, I hope to help you, thank you for your support to this site!


Related articles: