watchcat.sh (1843B)
1 #!/bin/sh 2 # 3 # Copyright (C) 2010 segal.di.ubi.pt 4 # 5 # This is free software, licensed under the GNU General Public License v2. 6 # 7 8 mode="$1" 9 10 # Fix potential typo in mode (backward compatibility). 11 [ "$mode" = "allways" ] && mode="always" 12 13 shutdown_now() { 14 local forcedelay="$1" 15 16 reboot & 17 18 [ "$forcedelay" -ge 1 ] && { 19 sleep "$forcedelay" 20 21 echo b > /proc/sysrq-trigger # Will immediately reboot the system without syncing or unmounting your disks. 22 } 23 } 24 25 watchcat_always() { 26 local period="$1"; local forcedelay="$2" 27 28 sleep "$period" && shutdown_now "$forcedelay" 29 } 30 31 watchcat_ping() { 32 local period="$1"; local forcedelay="$2"; local pinghosts="$3"; local pingperiod="$4" 33 34 time_now="$(cat /proc/uptime)" 35 time_now="${time_now%%.*}" 36 time_lastcheck="$time_now" 37 time_lastcheck_withinternet="$time_now" 38 39 while true 40 do 41 # account for the time ping took to return. With a ping time of 5s, ping might take more than that, so it is important to avoid even more delay. 42 time_now="$(cat /proc/uptime)" 43 time_now="${time_now%%.*}" 44 time_diff="$((time_now-time_lastcheck))" 45 46 [ "$time_diff" -lt "$pingperiod" ] && { 47 sleep_time="$((pingperiod-time_diff))" 48 sleep "$sleep_time" 49 } 50 51 time_now="$(cat /proc/uptime)" 52 time_now="${time_now%%.*}" 53 time_lastcheck="$time_now" 54 55 for host in "$pinghosts" 56 do 57 if ping -c 1 "$host" &> /dev/null 58 then 59 time_lastcheck_withinternet="$time_now" 60 else 61 time_diff="$((time_now-time_lastcheck_withinternet))" 62 logger -p daemon.info -t "watchcat[$$]" "no internet connectivity for $time_diff seconds. Reseting when reaching $period" 63 fi 64 done 65 66 time_diff="$((time_now-time_lastcheck_withinternet))" 67 [ "$time_diff" -ge "$period" ] && shutdown_now "$forcedelay" 68 69 done 70 } 71 72 if [ "$mode" = "always" ] 73 then 74 watchcat_always "$2" "$3" 75 else 76 watchcat_ping "$2" "$3" "$4" "$5" 77 fi