Advertisement
MartineauPASTEBIN

SyslogEventMonitor.sh

Oct 9th, 2018
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 8.42 KB | None | 0 0
  1. #!/bin/sh
  2. VER="v1.03"
  3. #======================================================================================================= © 2016-2020 Martineau, v1.03
  4. #
  5. # Simple Syslog event monitor. Normally runs in background as a permanent task and allows for Event DOWN recovery action.
  6. #
  7. #     SyslogEventMonitor   { & } [ status ] [ stop ]
  8. #
  9. #     SyslogEventMonitor   &
  10. #                          Run in the background and creates '/tmp/SyslogMonitor-running' semaphore file
  11. #                          This file will contain messages for events that have been triggered etc.
  12. #                          Emails will be sent for matching triggers.
  13. #
  14. #     SyslogEventMonitor   stop
  15. #                          The '/tmp/SyslogMonitor-running' semaphore is renamed to '/tmp/SyslogMonitor-yyyy-hhmmss
  16. #                          which causes the background task to terminate the Syslog Event monitoring.
  17.  
  18. #
  19.  
  20. Say(){
  21.    echo -e $$ $@ | logger -st "($(basename $0))"
  22. }
  23. SayT(){
  24.    echo -e $$ $@ | logger -t "($(basename $0))"
  25. }
  26. # Print between line beginning with'#==' to first blank line inclusive
  27. ShowHelp() {
  28.     awk '/^#==/{f=1} f{print; if (!NF) exit}' $0
  29. }
  30. # shellcheck disable=SC2034
  31. ANSIColours() {
  32.  
  33.     cRESET="\e[0m";cBLA="\e[30m";cRED="\e[31m";cGRE="\e[32m";cYEL="\e[33m";cBLU="\e[34m";cMAG="\e[35m";cCYA="\e[36m";cGRA="\e[37m"
  34.     cBGRA="\e[90m";cBRED="\e[91m";cBGRE="\e[92m";cBYEL="\e[93m";cBBLU="\e[94m";cBMAG="\e[95m";cBCYA="\e[96m";cBWHT="\e[97m"
  35.     aBOLD="\e[1m";aDIM="\e[2m";aUNDER="\e[4m";aBLINK="\e[5m";aREVERSE="\e[7m"
  36.     cRED_="\e[41m";cGRE_="\e[42m"
  37.  
  38. }
  39. SendMail() {
  40.  
  41.     local MYROUTER=$(nvram get computer_name)
  42.  
  43.     local TEMPFILE="/tmp/mail.txt"
  44.  
  45.     local SMTP="mysmtp.server.com:nnn"                          # e.g. smtp.gmail.com:465
  46.     local FROM="Me@gmail.com"
  47.     local TO="Me@gmail.com"
  48.     local USERNAME="account_ID"
  49.     local PASSWORD="password"
  50.     local FROMNAME="This "$MYROUTER
  51.  
  52.     BODY=$(echo -e "Start Email body...\n\n\tFirst line.\n\tSecond line.\n\nEnd of email Body")
  53.  
  54.     echo -e "Subject: Example email"         >$TEMPFILE
  55.     echo -e "From: \"$FROMNAME\"<$FROM>"    >>$TEMPFILE
  56.     echo -e "Date: `date -R`"               >>$TEMPFILE
  57.     echo -e ""                              >>$TEMPFILE
  58.     echo -e "$BODY"                         >>$TEMPFILE
  59.     echo -e ""                              >>$TEMPFILE
  60.     echo -e $(date)                         >>$TEMPFILE
  61.  
  62.     curl    -s --url smtps://$SMTP                  \
  63.             --mail-from "$FROM" --mail-rcpt "$TO"   \
  64.             --upload-file $TEMPFILE                 \
  65.             --ssl-reqd                              \
  66.             --user "$USERNAME:$PASSWORD" --insecure
  67.  
  68.     Say "e-mail sent using curl smtps:// SSL/TLS (non-Certificate)" $SMTP
  69.  
  70.     return 0
  71. }
  72. SyslogEmail() {
  73.  
  74.     # Uses Global variables!!!! - Tacky!!!
  75.  
  76.     local MSG=$TAG" "$REASON
  77.  
  78.     if [ $(echo "$@" | grep -cw "noaction") -eq 0 ];then
  79.         local MSG=$MSG"; Action='"$ACTION"'"
  80.     fi
  81.     if [ $(echo "$@" | grep -cw "error") -eq 1 ];then
  82.         local MSG="***ERROR*** "$MSG            # 'Add '***ERROR***' prefix
  83.     fi
  84.     SayT "$MSG"
  85.     echo -e $(date)" "$MSG >> $LOCKFILE
  86.  
  87.     if [ $(echo "$@" | grep -cw "nomail") -eq 0 ];then
  88.         SendMail "$MSG"
  89.     fi
  90.  
  91.     return 0
  92.  
  93. }
  94. Process_ACTION() {
  95.  
  96.     # Execute a script for this trigger message
  97.     if [ ! -z "$ACTION" ];then
  98.         if [ -f "$ACTION" ];then
  99.             Say $(date)" "$TAG" action requested '"$ACTION"'"   # v1.03
  100.             sh $ACTION &
  101.             ACTION=
  102.         else
  103.             Say $TAG"'"$ACTION"' ***ERROR action NOT FOUND?"    # v1.03
  104.         fi
  105.     fi
  106.  
  107.  
  108. }
  109.  
  110.  
  111. #===============================================Main==============================================================================
  112. Main() { true; }            # Syntax that is Atom Shellchecker compatible!
  113.  
  114. ANSIColours
  115.  
  116. # v384.13+ NVRAM variable 'lan_hostname' supersedes 'computer_name'
  117. [ -n "$(nvram get computer_name)" ] && MYROUTER=$(nvram get computer_name) || MYROUTER=$(nvram get lan_hostname)
  118.  
  119. trap '' SIGHUP                  # Since 'nohup' doesn't work; Allow starting this script as a background task from command line!
  120.  
  121. #if [ -d "/tmp/mnt/"$MYROUTER ];then
  122.     #MOUNT="/tmp/mnt/"$MYROUTER
  123. #else
  124.     MOUNT="/tmp"
  125. #fi
  126.  
  127. # Single instance semaphore
  128. LOCKFILE=${MOUNT}"/"$(basename $0)"-running"
  129.  
  130. if [ "$1" == "status" ];then
  131.     if [ ! -z "$(ps | grep $(basename $0) | grep -v "VPN_" | grep -v "grep $(basename $0)" | grep -v "status")" ];then
  132.         echo -e $cBGRE
  133.         Say "Syslog Event monitor ACTIVE" $(grep -oE "PID=[0-9]*" $LOCKFILE)
  134.         echo -e $cRESET
  135.         exit
  136.     else
  137.         echo -e $cBMAG
  138.         Say "Syslog Event monitor not running"
  139.         echo -e $cRESET
  140.         exit
  141.     fi
  142. fi
  143.  
  144. if [ "$1" == "stop" ] && [ -f $LOCKFILE ];then
  145.     echo -e $cGRE
  146.     Say "Syslog Event monitor Termination requested" $(grep -oE "PID=[0-9]*" $LOCKFILE)
  147.     mv $LOCKFILE ${MOUNT}"/"$(basename $0)-$(date +"%Y%m%d-%H%M%S")
  148.     echo -e $cRESET
  149.     exit 0
  150. fi
  151.  
  152. echo -en $cBWHT
  153. Say $VER "Syslog Event Monitor started....."
  154. echo -en $cRESET
  155.  
  156. FD=120
  157. eval exec "$FD>$LOCKFILE"
  158. flock -n $FD || { Say "Syslog Event monitor ALREADY running...ABORTing"; exit; }
  159.  
  160. sleep 1
  161. echo -e $(date)" Syslog Event Monitor started.....PID="$$ >> $LOCKFILE
  162.  
  163. # Define Trigger messages
  164. #
  165. #       DOWN message count (to allow for controlling the trigger/action etc.)
  166. #       DOWN trigger message
  167. #       DOWN trigger ACTION script
  168. #       UP trigger message
  169. #       UP trigger ACTION script
  170.  
  171. #------------------------------------Start of customisation----------------------------------------------------------------
  172.  
  173. MSG0001T="WiFi subsystem"                       # Title for Syslog messages/SendMail
  174. MSG0001C=1                                      # DOWN message count trigger
  175. MSG0001D="notify_rc restart_wireless"           # DOWN Trigger message
  176. MSG0001U="eth1: Broadcom"                       # UP message: Reset monitoring/recovery action message or perhaps any of these???
  177.                                                 #   'wl_module_init: igs set to 0x0'
  178.                                                 #   'wl_module_init: txworkq set to 0x1'
  179.                                                 #   'eth1: Broadcom BCM4360 802.11 Wireless Controller 6.37.14.126 (r561982)'
  180.                                                 #   'eth2: Broadcom BCM4360 802.11 Wireless Controller 6.37.14.126 (r561982)'
  181.                                                 #   'device eth1 entered promiscuous mode'
  182.                                                 #   v384.xx message -> 'roamast: eth1: add client'
  183. MSG0001XD="/jffs/scripts/DOWNfixit.sh"          # DOWN action script
  184. MSG0001XU="/jffs/scripts/UPCheckit.sh"          # UP   action script
  185.  
  186.  
  187. #------------------------------------End of customisation----------------------------------------------------------------
  188.  
  189.  
  190. # Explicitly identify Syslog i.e. if syslog-ng is running, although /tmp/syslog.log is usually symlinked anyway?
  191. # NB. It might be safer to simply hard-code '/tmp/syslog.log' to ensure continued event monitoring if syslog-ng is unexpectedly stopped?
  192. #[ -z "$(ps -w | grep -v grep | grep -F "{syslog-ng}")" ] && FN="/tmp/syslog.log" || FN="/opt/var/log/messages"
  193. FN="/tmp/syslog.log"                        # v1.03
  194.  
  195. tail -F $FN | \
  196.     while read SYSLOG
  197.         do
  198.             case "$SYSLOG" in
  199.                 *$MSG0001D*|*$MSG0001U*)                                # DOWN/UP pair
  200.                     TAG="$MSG0001T"
  201.                     REASON="Trigger"
  202.                     [ -z "MSG0001CT" ] && MSG0001CT=0                   # v1.02
  203.                     case "$SYSLOG" in
  204.                         *$MSG0001D*)                                    # DOWN event
  205.                             MSG0001CT=$((1+MSG0001CT))
  206.                             ACTION=$MSG0001XD                           # DOWN ACTION script
  207.                             if [ $MSG0001CT -eq $MSG0001C ];then        # v1.02 Apply trigger threshold logic
  208.                                 REASON="unexpected restart detected"
  209.                                 SyslogEmail                             # Email etc.
  210.                                 Process_ACTION                          # Execute a script for this DOWN trigger message
  211.                             fi
  212.                             ;;
  213.                         *$MSG0001U*)                                    # UP event
  214.                             #MSG0001CU=$((1+MSG0001CU))
  215.                             ACTION=$MSG0001XU                           # UP ACTION script
  216.                             REASON="re-initialised"
  217.                             SyslogEmail                                 # Email or not using "nomail" arg
  218.                             Process_ACTION                              # Execute a script for this UP trigger message
  219.                             MSG0001CT=0                                 # v 1.02 Reset DOWN trigger threshold counter
  220.                             ;;
  221.                     esac
  222.                     ;;
  223.                 #
  224.                 #*$MSG9999U*|*$MSG9999D*)                               # Repeat for additional triggers
  225.                 #   TAG=
  226.                 #   REASON=
  227.                 #   etc.
  228.  
  229.                 *)
  230.                     # No trigger message match
  231.                     ;;
  232.             esac
  233.  
  234.             # Check for external kill switch; NOTE: Termination can be delayed on a quiet system!
  235.             if [ ! -f "$LOCKFILE" ];then                        # Tacky! should really check for a separate 'KILL' file?
  236.                 echo -en $cBYEL
  237.                 Say "Syslog Event Monitor external termination trigger.....terminating"
  238.                 echo -e $cRESET
  239.                 flock -u $FD
  240.                 exit
  241.             fi
  242.         done
  243.  
  244. # Runs forever???
  245.  
  246.  
  247. exit 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement