Guest User

Untitled

a guest
Nov 24th, 2017
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 29.11 KB | None | 0 0
  1. #!/bin/bash
  2.     # Filename    : autoshutdown.sh
  3.  
  4.     ######## VARIABLE DEFINITION ########
  5.     RESULT=0            # declare reusable RESULT variable to check function return values
  6.     ACTIVEIPS=""        # declare empty list of active IPs
  7.  
  8.     ######## CONSTANT DEFINITION ########
  9.     SCANRG="true"       # control the rescanning of the defined IP range
  10.                         # (default="true" is needed for preparation scan on boot up)
  11.     OPTSTRING="C:R:bdf:hl:t:r:s:v"      # option string for function 'getopt'
  12.  
  13.     ######## DEFAULT CONFIGURATION DEFINITION ########
  14.     CLASS=192.168.0          # Set the default IP base CLASS.
  15.     DEBUG="false"            # default status of debug log outputs (default="false")
  16.  
  17.     PORT="445"   # Set the Ports to watch for connection, separated with space
  18.                  # default "22 80 445" # SSH, Webinterface and SMB/CIFS-Transfer
  19.                  # SSH = 22
  20.                  # HTTP = 80 (Webinterface)
  21.                  # SMB/CIFS = 445
  22.                  # If any local IP in $CLASS is connected, FreeNAS is not shut down
  23.  
  24.     FREENASIP=192.168.0.191    # Set the IP of Freenas, used for checking connection in with netstat
  25.  
  26.     ####  Auto-Unrar Check ####
  27.     # If you don't know what this is, leave it by default
  28.     AUTOUNRARCHECK=false     # Check, if auto-unrar is extracting something
  29.                              # If an extraction-Process is running, the NAS is not shut down
  30.                              # default="false"
  31.     UNRARLOGDIR="/mnt/Data_on_CF/logs"  # Set the log-Dir of status.info
  32.     UNRARLOG="status.info"              # Set the filename of "status.info"
  33.  
  34.  
  35.  
  36.     FLAG=5              # Set the number of total failures before shutdown. (default=10)
  37.     RESCAN=1            # Number of cycles with full scan activity, before changing to background IP scan (default=10)
  38.     BGSCAN=1            # Number of cycles after which one background IP scan is triggered (default=15, ~30 min)
  39.     SLEEP=30           # Numbers of seconds between each check/loop. (default=120, 2 min)
  40.  
  41.     BOOTUP="false"      # activate a boot up phase: no shutdown will be triggered
  42.                         # until at least one active IP has been found before (default="false)
  43.                         # WARNING: This may lead to a NAS that will stay on, if no other host
  44.                         # will show active in the network !
  45.  
  46.     RANGE="0"           # define a range of IPs which should be scanned, (default="2..254")
  47.                         # via XXX.XXX.XXX.xxx last triple of IP address in a list
  48.                         # The following scheme is mandatory
  49.                         # "v..v+m,w,x..x+m,y+o..y,z"
  50.                         # define an ip range :    <start>..<end> -> the two dots are mandatory
  51.                         # define a single ip :   <ip>
  52.                         # all list entries seperated by comma ','
  53.                         # Please make sure to leave 1 and 255 out of the list !
  54.  
  55.     LOADPROCNAMES="proftpd,smbd,nfsd,transmission-daemon,mt-daapd"
  56.                         # command names of processes with load dependent children
  57.                         # (default="proftpd smbd nfsd transmission-daemon mt-daapd")
  58.     TEMPPROCNAMES="in.tftpd"
  59.                         # command names of processes only started when active
  60.                         # (default="in.tftpd")
  61.  
  62.     LPREPEAT=50         # number of test cycles for finding and active L-Process (default=50)
  63.     TPREPEAT=10         # number of test cycles for finding and active T-Process (default=10)
  64.  
  65.     CTOPPARAM="-d 1"            # define common parameters for the top command line (default="-d 1")
  66.     STOPPARAM="-I $CTOPPARAM"   # add specific parameters for the top command line  (default="-I $CTOPPARAM")
  67.  
  68.     SYSLOG="true"               # activate write to syslog (default="true")
  69.     VERBOSE="true"              # use the verbose mode, with additional info on the command line (default="true")
  70.     LOGGER="/usr/bin/logger"    # path and name of logger (default="/usr/bin/logger")
  71.     FACILITY="local6"           # facility to log to -> see syslog.conf  and add the line (default="local6")
  72.                                 # "local6.* %/var/log/autoshutdown.log"
  73.    
  74.     # loop to disable the script running from daytime
  75.     ENABLESCHED="true"   # enable or disable the scheduling function - comment to disable or set as false (default="true")
  76.     STARTTIME=20         # when to start running the loop (disabling shutdown) in 24h form. accepts hours only. (for example 02,03,..,22,23,00)
  77.     ENDTIME=21           # when to stop running the loop (disabling shutdown) in 24h form. accepts hours only. (see above)
  78.     SCHEDSLEEP=120       # run script every n seconds. (default=900)
  79.     ######## FUNCTION DECLARATION ########
  80.  
  81.  
  82.     ################################################################
  83.     #
  84.     #   name      : _script_help
  85.     #   parameter   : none
  86.     #   return      : none
  87.     #
  88.     _script_help()
  89.     {
  90.     echo "Command: $(basename $0) [-bdhv] [-C nnn.nnn.nnn] [-e mmm,mmm,mmm] [-S sss] [-E eee] [-c UP|DOWN] [-l lproc1,lproc2,lproc3,...] [-t tproc1,tproc2,tproc3,...] [-f nfc] [-r nrc] [-s sleeptime(sec)]
  91.    -----------------------------------------------
  92.    Command line option details:
  93.  
  94.       -b :            activate boot up phase (no shutdown until at least one host [IP] has been found active before)
  95.                   NOTE:   If it is a normal state of your network, to have no active hosts [IPs], but the NAS started
  96.                      this will keep your NAS awake. In this case deactive '-b', as script scans
  97.                      'nfc' times for active hosts in any case (see option '-r')
  98.                   [default: deactivated]
  99.  
  100.       -d :            activate additional debugging output in log file
  101.                   [default: deactivated]
  102.  
  103.       -h :            display this information
  104.  
  105.       -v :            activate verbose logging, all log informations are also visible
  106.                   in the terminal
  107.  
  108.       -C nnn.nnn.nnn :      define CLASS of network (first three triples of IPV4 address) for scanning
  109.                   with ping, e.g. 192.168.1
  110.                   [default: 192.168.1]
  111.  
  112.       -R s1..s1+n,i1,s2+m..s2,i2,s3..s3+o :   define a list of last triples of IPV4 addresses to scan for active hosts; single IPs
  113.                      or IP ranges can be defined, seperated by commas:
  114.  
  115.                         IP range : <s[ss]>..<e[ee]>
  116.                         -> numbers with 1..3 digits are allowed; two dots as range indicator are mandatory
  117.  
  118.                         single IP: <i[ii]>
  119.                         -> numbers with 1..3 digits are allowed
  120.  
  121.                      valid parameter lists:
  122.  
  123.                       e.g.   -R 1..2,3,4..10,11,254..12
  124.                       e.g.   -R 1..254
  125.                       e.g.   -R 10..20,50..100,150..200
  126.  
  127.                      in valid parameter lists:
  128.  
  129.                       e.g.   -R 1...2,3, 4.1011 254..12 (missing commas will lead to wrong ip ranges)
  130.  
  131.                      IP ranges are usually scanned from <s[ss]> UP to <e[ee]>, starting at <s[ss]>.
  132.                      <s[ss]> can be chosen bigger than <e[ee]>, this will lead to a DOWN search, starting at <s[ss]>
  133.                      [default: 2..254]
  134.  
  135.       -l lproc1,lproc2,... :      define one or multiple commands of processes to be supervised on activity
  136.                   all of these commands spawn active 'clones' in 'top' on activity, e.g. smbd
  137.                   [default: proftpd,smbd,nfsd,transmission-daemon,mt-daapd]
  138.  
  139.       -t tproc1,tproc2,... :      define one or multiple commands of processes to be supervised on activity
  140.                   all of these commands are only shown in 'top' on activity, e.g. sshd
  141.                   [default: sshd,in.tftpd]
  142.  
  143.       -f nfc :         define number of execution cycles without activity, before shutdown is issued
  144.                   [default: 10]
  145.  
  146.       -r nrc :         define number of IP scan cycles without any active host [IP] found, before entering
  147.                   background scan mode without an active host [IP] present, the script scans
  148.                   'nfc' times the bus ('burst scan'). Then scanning on every execution cycle is deactivated.
  149.                   NOTE: Background IP scanning every x execution cycles is always active.
  150.                   [default: 10]
  151.  
  152.       -s slt (sec) :         define how long the script will sleep [seconds], before checking again
  153.                   [default: 120]
  154.       " 1>&2
  155.     exit 0;
  156.     }
  157.  
  158.     ################################################################
  159.     #
  160.     #   name      : _log
  161.     #   parameter   : $LOGMESSAGE : logmessage in format "PRIORITY: MESSAGE"
  162.     #   return      : none
  163.     #
  164.     _log()
  165.        {(
  166.            [[ "$*" =~ ^([A-Za-z]*):(.*) ]] &&
  167.              {
  168.                 PRIORITY=${BASH_REMATCH[1]}
  169.                 LOGMESSAGE=${BASH_REMATCH[2]}
  170.                 [[ "$(basename "$0")" =~ ^(.*)\. ]] && LOGMESSAGE="${BASH_REMATCH[1]}[$$]: $PRIORITY: $LOGMESSAGE";
  171.              }
  172.  
  173.           if $VERBOSE ; then
  174.              # next line only with implementation where logger does not support option '-s'
  175.              # echo "$(date '+%b %e %H:%M:%S'):$LOGMESSAGE"
  176.  
  177.              [ $SYSLOG ] && $LOGGER -s -t "$(date '+%b %e %H:%M:%S'): $USER" -p $FACILITY.$PRIORITY $LOGMESSAGE
  178.  
  179.           else
  180.              [ $SYSLOG ] && $LOGGER -p $FACILITY.$PRIORITY $LOGMESSAGE
  181.  
  182.           fi   # > if [ "$VERBOSE" = "NO" ]; then
  183.  
  184.        )}
  185.  
  186.     ################################################################
  187.     #
  188.     #   name      : _ping_range
  189.     #   parameter   : none
  190.     #   global return   : ACTIVEIPS : list of all active hosts in given IP range, separated by blank
  191.     #       global return   : SCANRG    : 0 = at least one active IP found
  192.     #   return value   : CNT       : number of active IP hosts within given IP range
  193.  
  194.     _ping_range()
  195.     {
  196.        CNT=0
  197.        ACTIVEIPS=""
  198.        IPING=
  199.  
  200.        # separate the IP end number from the loop counter, to give the user a chance to configure the search "algorithm"
  201.        # COUNTUP = 1 means starting at the lowest IP address; COUNTUP=0 will start at the upper end of the given range
  202.        if $DEBUG ; then _log "DEBUG: _ping_range(): RANGE: '$RANGE'" ; fi
  203.  
  204.           for RG in ${RANGE//,/ } ; do
  205.  
  206.              if [[ ! "$RG" =~ \.{2} ]]; then
  207.  
  208.                 FINIT="J=$RG"
  209.                 FORCHECK="J<=$RG"
  210.                 STEP="J++"
  211.  
  212.                 if $DEBUG ; then _log "DEBUG: _ping_range(): Single Number, RG: '$RG', FINIT: '$FINIT', FORCHECK: '$FORCHECK', STEP: '$STEP'" ; fi
  213.  
  214.              elif [[ "$RG" =~ ^([0-9]{1,3})\.{2}([0-9]{1,3}$) ]]; then
  215.  
  216.                 if $DEBUG ; then _log "DEBUG: _ping_range(): IP Range, RG: '$RG', BASH_REMATCH: '$BASH_REMATCH', BASH_REMATCH[1]: '${BASH_REMATCH[1]}', BASH_REMATCH[2]: '${BASH_REMATCH[2]}'" ; fi
  217.  
  218.                 if [ ${BASH_REMATCH[2]} -gt ${BASH_REMATCH[1]} ]; then
  219.                    FINIT="J=${BASH_REMATCH[1]}"
  220.                    FORCHECK="J<=${BASH_REMATCH[2]}"
  221.                    STEP="J++"
  222.  
  223.                    if $DEBUG ; then _log "DEBUG: _ping_range(): START < END, RG: '$RG', FINIT: '$FINIT', FORCHECK: '$FORCHECK', STEP: '$STEP'" ; fi
  224.  
  225.                 else
  226.                    FINIT="J=${BASH_REMATCH[1]}"
  227.                    FORCHECK="J>=${BASH_REMATCH[2]}"
  228.                    STEP="J--";
  229.  
  230.                    if $DEBUG ; then _log "DEBUG: _ping_range(): END > START, RG: '$RG', FINIT: '$FINIT', FORCHECK: '$FORCHECK', STEP: '$STEP'" ; fi
  231.  
  232.                 fi   # > if [ ${BASH_REMATCH[2]} -gt ${BASH_REMATCH[1]} ]; then
  233.  
  234.              fi   # > iif [[ "$RG" =~ [0-9]{1,3} ]]; then
  235.  
  236.           for (( $FINIT;$FORCHECK;$STEP )); do
  237.  
  238.              # Ping each IP address in turn. if we find one -> CNT ++
  239.              # added the redirect to /dev/null, as we are only interested in the return value (no output on console)
  240.  
  241.            # Log the IP-adresses to ping only in DEBUG-Mode
  242.                 if $DEBUG  ; then _log "DEBUG: Scan IP $CLASS.$J for active host."; fi
  243.  
  244.                 ping -c 1 -s 8 -t 1 $CLASS.$J > /dev/null &&
  245.                    {
  246.                       # Found one!!
  247.                       _log "INFO: Found IP $CLASS.$J as active host."
  248.                       ACTIVEIPS="$ACTIVEIPS$CLASS.$J "
  249.                       SCANRG="false"
  250.                       let CNT++;
  251.                    }
  252.  
  253.              done   # > for (( J=$iSTART;$FORCHECK;$STEP )); do
  254.  
  255.           done   # > for RG in ${RANGE//,/ } ; do
  256.  
  257.           if $DEBUG ; then _log "DEBUG: _ping_range(): ACTIVEIPS: '$ACTIVEIPS', SCANRG: '$SCANRG', CNT: '$CNT'" ; fi
  258.  
  259.  
  260.        return ${CNT};
  261.     }
  262.  
  263.     ################################################################
  264.     #
  265.     #   name      : _ping_active_list
  266.     #   parameter   : ACTIVEIPS : list of all active IPs found
  267.     #       global return   : SCANRG : 0 = no scan needed; 1 = scan of ACTIVEIPS to be done
  268.     #   return      : 1 : if no active host has been found
  269.     #         : 0 : if at least one active host has been found
  270.     #
  271.     _ping_active_list()
  272.     {
  273.        CNT=0
  274.        IPING=${iSTART}
  275.  
  276.        if $DEBUG ; then  _log "DEBUG: _ping_active_list(): Scan IPs ${1} for activity." ; fi
  277.  
  278.        for IPADDRESS in "$1"; do
  279.  
  280.           # Ping each IP address in parameter list. if we find one -> CNT != 0 we'll
  281.           # stop as there's really no point continuing to looking for more.
  282.           # added the redirect to /dev/null, as we are only interested in the return value (no output on console)
  283.           if [ "$IPADDRESS" != "" ];then
  284.  
  285.              if $DEBUG ; then  _log "DEBUG: _ping_active_list(): Scan IP ${IPADDRESS} for activity." ; fi
  286.  
  287.              ping -c 1 -s 8 -t 1 ${IPADDRESS} > /dev/null
  288.              if [ $? -eq 0 ]; then
  289.                 # Found one!!
  290.                 _log "INFO: Found IP ${IPADDRESS} still active."
  291.                 let CNT++
  292.                 SCANRG="false"
  293.                 break
  294.              else
  295.                 # mark the list as invalid, as there is at least one obsolete IP in it
  296.                 _log "INFO: Found IP ${IPADDRESS} inactive; triggered scan of network in next execution"
  297.                 SCANRG="true"
  298.  
  299.              fi   # > if [ $? -eq 0 ]; then
  300.  
  301.           else
  302.              # mark the list as invalid, as there is at least one obsolete IP in it
  303.              _log "INFO: Found no valid IP; triggered scan of network in next execution cycle."
  304.              SCANRG="true"
  305.  
  306.           fi   # > if [ "$IPADDRESS" != "" ];then
  307.  
  308.           # As 'ping' takes nearly a second, this loop could be very time consuming
  309.           # Do a check for some active processes, maybe, one never knows...
  310.           # If there is at least one active, we leave this function with a 'bogus find'
  311.           _check_processes &&
  312.              {
  313.                 let CNT++
  314.                 break;
  315.              }
  316.  
  317.  
  318.        done   # > for IPADDRESS in "$1"; do
  319.  
  320.        return ${CNT};
  321.     }
  322.  
  323.     ################################################################
  324.     #
  325.     #   name      : _shutdown
  326.     #   parameter   : none
  327.     #   return      : none, script exit point
  328.     #
  329.     _shutdown()
  330.     {
  331.        # Goodbye and thanks for all the fish!!
  332.        # We've had no responses for the required number of consecutive scans
  333.        # defined in FLAG shutdown & power off.
  334.        _log "INFO: Shutdown issued: shutdown -p now"
  335.        shutdown -p now
  336.        exit 0;
  337.     }
  338.  
  339.     ################################################################
  340.     #
  341.     #   name      : _ident_num_proc
  342.     #   parameter   : $1...$(n-1)    : parameter for command 'top'
  343.     #         : $n      : search pattern for command 'grep'
  344.     #   return      : none
  345.     #
  346.     _ident_num_proc()
  347.     {
  348.        (
  349.        # retrieve all function parameters for the top command; as we know the last command line parameter
  350.        # is the pattern for the grep command, we can stop one parameter before the end
  351.        [[ "$*" =~ (.*)\ (.*)$ ]] &&
  352.           {
  353.              TPPARAM=${BASH_REMATCH[1]}
  354.              GRPPATTERN=${BASH_REMATCH[2]};
  355.           }
  356.        # _log "DEBUG: _ident_num_proc(): top cmd line: $TPPARAM, grep cmd line: $GRPPATTERN"
  357.  
  358.        # call top once, pipe the result to grep and count the number of patterns found
  359.        # the number of found processes is returned to the callee
  360.        RVALUE=$(top ${TPPARAM} | grep -c ${GRPPATTERN})
  361.  
  362.        return $RVALUE
  363.        )
  364.     }
  365.  
  366.     ################################################################
  367.     #
  368.     #   name      : _check_processes
  369.     #   parameter   : none
  370.     #   global return   : NUMPROC: number of active processes, defined in LOADPROCNAMES and TEMPPROCNAMES
  371.     #   return      : 1      : if no active process has been found
  372.     #         : 0      : if at least one active process has been found
  373.     #
  374.     _check_processes()
  375.     {
  376.        RVALUE=1
  377.        NUMPROC=0
  378.        CHECK=0
  379.  
  380.        # check for each given command name in LOADPROCNAMES if it is currently stated active in "top"
  381.        # i found, that for smbd, proftpd, nsfd, ... there are processes always present in "ps" or "top" output
  382.        # this could be due to the "daemon" mechanism... Only chance to identify there is something happening with these
  383.        # processes, is to check if "top" states them active -> "-I" parameter on the command line
  384.        for LPROCESS in ${LOADPROCNAMES//,/ } ; do
  385.           LP=0
  386.           IPROC=0
  387.           for ((N=0;N < ${LPREPEAT};N++ )) ; do
  388.              _ident_num_proc ${STOPPARAM} ${LPROCESS}
  389.              RESULT=$?
  390.              LP=$(($LP|$RESULT))
  391.              [ $RESULT -gt 0 ] && let IPROC++
  392.           done
  393.  
  394.           let NUMPROC=$NUMPROC+$LP
  395.  
  396.           if ! $DEBUG ; then { [ $LP -gt 0 ] && _log "INFO: _check_processes(): Found active process $LPROCESS"; }; fi
  397.  
  398.           if $DEBUG  ; then _log "DEBUG: _check_processes(): > $LPROCESS: found $IPROC of $LPREPEAT cycles active"; fi
  399.  
  400.        done   # > LPROCESS in ${LOADPROCNAMES//,/ } ; do
  401.  
  402.        if ! $DEBUG ; then { [ $NUMPROC -gt 0 ] && _log "INFO: Found $NUMPROC active processes in $LOADPROCNAMES" ; }; fi
  403.  
  404.  
  405.        # check for each given command name in TEMPPROCNAMES if it is currently stated present in "top"
  406.        # i found, that for sshd, ... there are processes only present in "ps" or "top" output when is is used.
  407.        # it can not be guaranteed, that top states these services active, as they usually wait for user input
  408.        # no "-I" parameter on the command line, but shear presence is enough
  409.        for TPROCESS in ${TEMPPROCNAMES//,/ } ; do
  410.           TP=0
  411.           IPROC=0
  412.           for ((N=0;N < ${TPREPEAT};N++ )) ; do
  413.              _ident_num_proc ${CTOPPARAM} ${TPROCESS}
  414.              RESULT=$?
  415.              TP=$(($TP|$RESULT))
  416.              [ $RESULT -gt 0 ] && let IPROC++
  417.           done
  418.  
  419.           let CHECK=$CHECK+$TP
  420.  
  421.           if ! $DEBUG ; then { [ $TP -gt 0 ] && _log "INFO: _check_processes(): Found active process $TPROCESS"; }; fi
  422.  
  423.           if $DEBUG ; then _log "DEBUG: _check_processes(): > $TPROCESS: found $IPROC of $TPREPEAT cycles active"; fi
  424.  
  425.        done   # > for TPROCESS in ${TEMPPROCNAMES//,/ } ; do
  426.  
  427.        if ! $DEBUG ; then { [ $CHECK -gt 0 ] &&_log "INFO: Found $CHECK active processes in $TEMPPROCNAMES" ; }; fi
  428.  
  429.  
  430.       # Check if there are any connection on $PORT
  431.  
  432.       for CHECKPORT in $(echo $PORT); do
  433.  
  434.         # Check how many IPs are connected
  435.         NROFCON=$(netstat -an | grep $CLASS | grep "ESTABLISHED" | grep $FREENASIP.$CHECKPORT | wc -l)
  436.  
  437.         # Check which IP is connected on the specified Port
  438.         CONIP=$(netstat -an | grep $CLASS | grep "ESTABLISHED" | grep $FREENASIP.$CHECKPORT | awk '{print $5}' | sed 's/\.[0-9]*$//g' | uniq)
  439.  
  440.         if [ $NROFCON -gt 0 ]; then {
  441.           let CHECK++
  442.  
  443.           # Set PORTPROTOCOLL
  444.           case $CHECKPORT in
  445.           80)
  446.                 PORTPROTOCOL="HTTP" ;;
  447.           22)
  448.                 PORTPROTOCOL="SSH" ;;
  449.           21)
  450.                           PORTPROTOCOL="FTP" ;;
  451.           8080)
  452.                           PORTPROTOCOL="HTTP" ;;
  453.                     445)
  454.                           PORTPROTOCOL="SMB/CIFS" ;;
  455.           *)
  456.                           PORTPROTOCOL="unknown" ;;
  457.           esac
  458.  
  459.           _log "INFO: Found active Connection on Port $CHECKPORT ($PORTPROTOCOL) from $CONIP"
  460.  
  461.           if $DEBUG ; then {
  462.             _log "DEBUG: check Port: $NROFCON Connections active.";
  463.             _log "DEBUG: NROFCON: $NROFCON ";
  464.             _log "DEBUG: CONIP: $CONIP ";
  465.           }
  466.           fi
  467.         }
  468.         fi
  469.       done
  470.  
  471.     if $DEBUG ; then _log "DEBUG: cat $UNRARLOGDIR/$UNRARLOG = $(cat $UNRARLOGDIR/$UNRARLOG)"; fi
  472.  
  473.     UNRARCHECK=0
  474.     if [ $AUTOUNRARCHECK = "true" ]; then
  475.       if $DEBUG ; then _log "DEBUG: AUTOUNRARCHECK is running now" ; fi
  476.       if [ -f $UNRARLOGDIR/$UNRARLOG ]; then
  477.         if [ $(cat "$UNRARLOGDIR/$UNRARLOG") = "processing job" ]; then
  478.           _log "INFO: unrar-script running - no shutdown."
  479.           UNRARCHECK=1
  480.         fi
  481.       fi
  482.     fi
  483.  
  484.  
  485.  
  486.        let NUMPROC=$NUMPROC+$CHECK
  487.  
  488.        if $DEBUG ; then
  489.        _log "DEBUG: _check_processes(): $NUMPROC process(es) active."
  490.        _log "DEBUG: UNRARCHECK: $UNRARCHECK"
  491.        fi
  492.  
  493.        [[ $NUMPROC -gt 0 ]] || [[ $UNRARCHECK -gt 0 ]] && RVALUE=0
  494.  
  495.        # only return we found a process or unrar running
  496.        return $RVALUE
  497.  
  498.     }
  499.  
  500.  
  501.     ######## START OF BODY FUNCTION SCRIPT AUTOSHUTDOWN.SH ########
  502.  
  503.     # check command line options, on hold as getopt will be available in upcoming release
  504.     #
  505.     ARGS=`getopt "$OPTSTRING" "$*"`
  506.     if [ $? -ne 0 ] ; then
  507.        echo "Command: $(basename $0) [-bdhv] [-C nnn.nnn.nnn] [-R s1..s1+n,i1,s2+m..s2,i2,s3..s3+o] [-f nfc] [-l lproc1,lproc2,lproc3,...] [-t tproc1,tproc2,tproc3,...] [-r nrc] [-s slt (sec)] " 1>&2
  508.        exit 2
  509.     fi
  510.  
  511.     # decoding of command line parameters
  512.     #
  513.     set -- $ARGS
  514.  
  515.     for I do
  516.        case "$1" in
  517.           -C)   shift; CLASS="$1"; [[ "$CLASS" =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]] || { echo " -C $1 : Invalid parameter format; [-C nnn.nnn.nnn]" 1>&2; exit 1; };;
  518.           -R)   shift; RANGE="$1"; [[ "$RANGE" =~ ^[[0-9]{1,3}|[0-9]{1,3}\.{2}[0-9]{1,3}\,]$ ]] || { echo " -R $1 : Invalid parameter list format; [-R v..v+n,w,x+m..x,y,z..z+o]" 1>&2; exit 1; };;
  519.           -b)   BOOTUP="true";;
  520.           -d)   DEBUG="true";;
  521.           -f)   shift; FLAG="$1"; [[ "$FLAG" =~ ^[0-9]{1,3}$ ]] || { echo " -f $1 : Invalid parameter format; [-f nfc]" 1>&2; exit 1; };;
  522.           -l)   shift; LOADPROCNAMES="$1"; [[ "$LOADPROCNAMES" =~ ^[[A-Za-z0-9_]\,]$ ]] || { echo " -l $1 : Invalid parameter list format; [-l lproc1,lproc2,lproc3,...]" 1>&2; exit 1; };;
  523.           -r)   shift; RESCAN="$1"; [[ "$RESCAN" =~ ^[0-9]{1,3}$ ]] || { echo " -r $1 : Invalid parameter format; [-r nrc]" 1>&2; exit 1; };;
  524.           -s)   shift; SLEEP="$1"; [[ "$SLEEP" =~ ^[0-9]{1,3}$ ]] || { echo " -s $1 : Invalid parameter format; [-s slt (sec)]" 1>&2; exit 1; };;
  525.           -t)   shift; TEMPPROCNAMES="$1"; [[ "$TEMPPROCNAMES" =~ ^[[A-Za-z0-9_]\,]$ ]] || { echo " -t $1 : Invalid parameter list format; [-t tproc1,tproc2,tproc3,...]" 1>&2; exit 1; };;
  526.           -v)   VERBOSE="true";;
  527.           -h)   _script_help;;
  528.  
  529.           --)   shift; break ;;
  530.  
  531.        esac   # > case "$1" in
  532.        shift
  533.  
  534.     done   # > for I do
  535.  
  536.     if $DEBUG ; then
  537.        _log "DEBUG: ARGS: $ARGS "
  538.        _log "DEBUG: CLASS: $CLASS "
  539.        _log "DEBUG: RANGE: $RANGE "
  540.        _log "DEBUG: BOOTUP: $BOOTUP "
  541.        _log "DEBUG: FLAG: $FLAG "
  542.        _log "DEBUG: LOADPROCNAMES: $LOADPROCNAMES "
  543.        _log "DEBUG: RESCAN: $RESCAN "
  544.        _log "DEBUG: SLEEP: $SLEEP "
  545.        _log "DEBUG: TEMPPROCNAMES: $TEMPPROCNAMES "
  546.        _log "DEBUG: VERBOSE: $VERBOSE "
  547.        _log "DEBUG: PORT: $PORT "
  548.        _log "DEBUG: AUTOUNRARCHECK: $AUTOUNRARCHECK";
  549.        _log "DEBUG: UNRARLOG: $UNRARLOG";
  550.        _log "DEBUG: UNRARLOGDIR: $UNRARLOGDIR";
  551.        _log "DEBUG: HOURS: $HOURS";
  552.        _log "DEBUG: STARTTIME: $STARTTIME";
  553.        _log "DEBUG: ENDTIME: $ENDTIME";
  554.        #exit 42;
  555.     fi   # > if $DEBUG ;then
  556.  
  557.     # Init the counters
  558.     FCNT=$FLAG
  559.     SCNCNT=$RESCAN
  560.     BGSCNCNT=$BGSCAN
  561.  
  562.     # functional start of script
  563.     _log "INFO:-----------------------------script started--------------------------------------"
  564.     _log "INFO: ${FLAG} test cycles until shutdown is issued."
  565.     _log "INFO: network range is given within \"$RANGE\"."
  566.     _log "INFO: Boot up phase is $(if $BOOTUP ; then echo "ACTIVE"; else echo "DISABLED"; fi)"
  567.  
  568.  
  569.     while : ; do
  570.        _log "INFO:------------------------------------------------------"
  571.        _log "INFO: new supervision cycle started."
  572.        # Main loop, just keep pinging and checking for processes, to decide whether we can shutdown or not...
  573.        
  574.        # A master switch for the scheduler
  575.        if $ENABLESCHED ; then
  576.           # Doing a loop to check if time is right and moon phase is correct
  577.           HOURS=`date +%k`        # this is used to retrieve starting value for loop check. default: `date +%k`
  578.           if $DEBUG ; then _log "DEBUG: check for scheduler loop with values STARTTIME: $STARTTIME ENDTIME: $ENDTIME and HOURS: $HOURS" ; fi
  579.           while [[ $STARTTIME -gt $HOURS && $ENDTIME -lt $HOURS ]]; do
  580.              sleep $SCHEDSLEEP;   # sleeping for predefined seconds
  581.              HOURS=`date +%k`     # updating value for HOURS
  582.              _log "INFO: scheduler in sleep for ${SCHEDSLEEP}s and updating HOURS with $HOURS."
  583.          done    # we're done with scheduler-loop
  584.          _log "INFO: we got out of the scheduled loop succesfully."
  585.        fi    # > ENABLESCHED exist
  586.        
  587.        # Counter to implement maximum $RESCAN number of execution cycles with active IP scanning; then only the
  588.        # IP scan in background once every $BGSCAN cycles is active to reduce network traffic
  589.        #
  590.        if [ $SCNCNT -gt 0 ] ; then
  591.  
  592.           if $DEBUG ; then _log "DEBUG: main: SCNCNT is > 0, SCNCNT: '$SCNCNT', SCANRG: '$SCANRG'" ; fi
  593.  
  594.           # decrease counter
  595.            if $SCANRG ; then if $BOOTUP ;then : ; else let SCNCNT--; fi ; fi
  596.  
  597.        else
  598.           SCANRG="false"   # suppress scanning always
  599.           if $DEBUG ; then _log "DEBUG: main: SCNCNT is 0, SCANRG: '$SCANRG'" ; fi
  600.  
  601.  
  602.        fi   # > if [ $SCNCNT -gt 0 ] ; then
  603.  
  604.        # IP scan in background once every $BGSCAN cycles; the background scan also allows to identify
  605.        # new hosts [IPs] and add them to the $ACTIVEIPS list of active IPs
  606.        #
  607.        if [ $BGSCNCNT -gt 0 ] ; then
  608.  
  609.           if $DEBUG ; then _log "DEBUG: main: BGSCNCNT is > 0, BGSCNCNT: '$BGSCNCNT', SCANRG: '$SCANRG'" ; fi
  610.  
  611.           let BGSCNCNT--
  612.  
  613.        else
  614.  
  615.           BGSCNCNT=$BGSCAN # reset the counter, to start again
  616.           SCANRG="true"    # scan once
  617.  
  618.           if $DEBUG ; then _log "DEBUG: main: BGSCNCNT has been 0, BGSCNCNT: '$BGSCNCNT', SCANRG: '$SCANRG'" ; fi
  619.  
  620.        fi   # > if [ $BGSCNCNT -gt 0 ] ; then
  621.  
  622.        _log "INFO: Current IP scan mode: $(if ( $BOOTUP || $SCANRG ); then echo "FULL"; else echo "BACKGROUND"; fi)"
  623.  
  624.  
  625.        if $SCANRG -o $BOOTUP ; then
  626.        # retrieve all currently active IPs in your network
  627.        # if there has none active found try again after $SLEEP seconds in next execution cycle
  628.  
  629.              _log "INFO: retrieve list of active IPs..."
  630.         if ! $DEBUG  ; then _log "INFO: IPs not shown, use \"autoshutdown.sh -d\" for more Info"; fi
  631.  
  632.         # if there have been active IPs found, there is no need to scan in next execution cycle
  633.              _ping_range || {  BOOTUP="false"; SCNCNT=$RESCAN; }
  634.              RESULT=$?
  635.  
  636.              if $DEBUG ; then
  637.  
  638.                 for IP in $ACTIVEIPS ; do
  639.                    _log "DEBUG: > IP ${IP} currently active."
  640.                 done
  641.  
  642.                 _log "DEBUG: Variable SCANRG: '$SCANRG', BOOTUP: '$BOOTUP', SCNCNT: '$SCNCNT'"
  643.  
  644.              SCANRG="false"
  645.  
  646.              fi   # > if $DEBUG ; then
  647.  
  648.        fi   # > if $SCANRG -o $BOOTUP ; then
  649.  
  650.        # search strategy; 1st ping host adresses
  651.        # check for processes in between each 'ping'
  652.  
  653.        _log "INFO: check number of active hosts in configured network range..."
  654.  
  655.        if _ping_active_list $ACTIVEIPS ; then
  656.           # check if we are still in the boot up phase (no shutdown until we have found our first active IP)
  657.           if $BOOTUP ; then
  658.              _log "INFO: Boot up phase is still ACTIVE"
  659.           else
  660.              if $DEBUG ; then _log "DEBUG: Boot up phase is DISABLED" ; fi
  661.  
  662.              # Nothing found so sub one from the count and check if we can shutdown yet.
  663.              let FCNT--
  664.  
  665.              _log "INFO: No active processes, unraring or hosts within network range, ${FCNT} cycles until shutdown..."
  666.  
  667.              if [ $FCNT -eq 0 ]; then
  668.                 _shutdown;
  669.              fi   # > if [ $FCNT -eq 0 ]; then
  670.           fi   # > if $BOOTUP ; then : ; else
  671.        else
  672.           # Live IP found so reset count
  673.           FCNT=${FLAG};
  674.        fi   # > if { _ping_active_list $ACTIVEIPS }, then
  675.  
  676.        # Wait for the required time before checking again.
  677.        _log "INFO: sleep for ${SLEEP}s."
  678.        sleep $SLEEP;
  679.  
  680.     done   # > while : ; do
  681.  
  682.     #EOF####### END OF SCRIPT AUTOSHUTDOWN.SH ########
Add Comment
Please, Sign In to add comment