Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/bin/bash
- # Filename : autoshutdown.sh
- ######## VARIABLE DEFINITION ########
- RESULT=0 # declare reusable RESULT variable to check function return values
- ACTIVEIPS="" # declare empty list of active IPs
- ######## CONSTANT DEFINITION ########
- SCANRG="true" # control the rescanning of the defined IP range
- # (default="true" is needed for preparation scan on boot up)
- OPTSTRING="C:R:bdf:hl:t:r:s:v" # option string for function 'getopt'
- ######## DEFAULT CONFIGURATION DEFINITION ########
- CLASS=192.168.0 # Set the default IP base CLASS.
- DEBUG="false" # default status of debug log outputs (default="false")
- PORT="445" # Set the Ports to watch for connection, separated with space
- # default "22 80 445" # SSH, Webinterface and SMB/CIFS-Transfer
- # SSH = 22
- # HTTP = 80 (Webinterface)
- # SMB/CIFS = 445
- # If any local IP in $CLASS is connected, FreeNAS is not shut down
- FREENASIP=192.168.0.191 # Set the IP of Freenas, used for checking connection in with netstat
- #### Auto-Unrar Check ####
- # If you don't know what this is, leave it by default
- AUTOUNRARCHECK=false # Check, if auto-unrar is extracting something
- # If an extraction-Process is running, the NAS is not shut down
- # default="false"
- UNRARLOGDIR="/mnt/Data_on_CF/logs" # Set the log-Dir of status.info
- UNRARLOG="status.info" # Set the filename of "status.info"
- FLAG=5 # Set the number of total failures before shutdown. (default=10)
- RESCAN=1 # Number of cycles with full scan activity, before changing to background IP scan (default=10)
- BGSCAN=1 # Number of cycles after which one background IP scan is triggered (default=15, ~30 min)
- SLEEP=30 # Numbers of seconds between each check/loop. (default=120, 2 min)
- BOOTUP="false" # activate a boot up phase: no shutdown will be triggered
- # until at least one active IP has been found before (default="false)
- # WARNING: This may lead to a NAS that will stay on, if no other host
- # will show active in the network !
- RANGE="0" # define a range of IPs which should be scanned, (default="2..254")
- # via XXX.XXX.XXX.xxx last triple of IP address in a list
- # The following scheme is mandatory
- # "v..v+m,w,x..x+m,y+o..y,z"
- # define an ip range : <start>..<end> -> the two dots are mandatory
- # define a single ip : <ip>
- # all list entries seperated by comma ','
- # Please make sure to leave 1 and 255 out of the list !
- LOADPROCNAMES="proftpd,smbd,nfsd,transmission-daemon,mt-daapd"
- # command names of processes with load dependent children
- # (default="proftpd smbd nfsd transmission-daemon mt-daapd")
- TEMPPROCNAMES="in.tftpd"
- # command names of processes only started when active
- # (default="in.tftpd")
- LPREPEAT=50 # number of test cycles for finding and active L-Process (default=50)
- TPREPEAT=10 # number of test cycles for finding and active T-Process (default=10)
- CTOPPARAM="-d 1" # define common parameters for the top command line (default="-d 1")
- STOPPARAM="-I $CTOPPARAM" # add specific parameters for the top command line (default="-I $CTOPPARAM")
- SYSLOG="true" # activate write to syslog (default="true")
- VERBOSE="true" # use the verbose mode, with additional info on the command line (default="true")
- LOGGER="/usr/bin/logger" # path and name of logger (default="/usr/bin/logger")
- FACILITY="local6" # facility to log to -> see syslog.conf and add the line (default="local6")
- # "local6.* %/var/log/autoshutdown.log"
- # loop to disable the script running from daytime
- ENABLESCHED="true" # enable or disable the scheduling function - comment to disable or set as false (default="true")
- STARTTIME=20 # when to start running the loop (disabling shutdown) in 24h form. accepts hours only. (for example 02,03,..,22,23,00)
- ENDTIME=21 # when to stop running the loop (disabling shutdown) in 24h form. accepts hours only. (see above)
- SCHEDSLEEP=120 # run script every n seconds. (default=900)
- ######## FUNCTION DECLARATION ########
- ################################################################
- #
- # name : _script_help
- # parameter : none
- # return : none
- #
- _script_help()
- {
- 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)]
- -----------------------------------------------
- Command line option details:
- -b : activate boot up phase (no shutdown until at least one host [IP] has been found active before)
- NOTE: If it is a normal state of your network, to have no active hosts [IPs], but the NAS started
- this will keep your NAS awake. In this case deactive '-b', as script scans
- 'nfc' times for active hosts in any case (see option '-r')
- [default: deactivated]
- -d : activate additional debugging output in log file
- [default: deactivated]
- -h : display this information
- -v : activate verbose logging, all log informations are also visible
- in the terminal
- -C nnn.nnn.nnn : define CLASS of network (first three triples of IPV4 address) for scanning
- with ping, e.g. 192.168.1
- [default: 192.168.1]
- -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
- or IP ranges can be defined, seperated by commas:
- IP range : <s[ss]>..<e[ee]>
- -> numbers with 1..3 digits are allowed; two dots as range indicator are mandatory
- single IP: <i[ii]>
- -> numbers with 1..3 digits are allowed
- valid parameter lists:
- e.g. -R 1..2,3,4..10,11,254..12
- e.g. -R 1..254
- e.g. -R 10..20,50..100,150..200
- in valid parameter lists:
- e.g. -R 1...2,3, 4.1011 254..12 (missing commas will lead to wrong ip ranges)
- IP ranges are usually scanned from <s[ss]> UP to <e[ee]>, starting at <s[ss]>.
- <s[ss]> can be chosen bigger than <e[ee]>, this will lead to a DOWN search, starting at <s[ss]>
- [default: 2..254]
- -l lproc1,lproc2,... : define one or multiple commands of processes to be supervised on activity
- all of these commands spawn active 'clones' in 'top' on activity, e.g. smbd
- [default: proftpd,smbd,nfsd,transmission-daemon,mt-daapd]
- -t tproc1,tproc2,... : define one or multiple commands of processes to be supervised on activity
- all of these commands are only shown in 'top' on activity, e.g. sshd
- [default: sshd,in.tftpd]
- -f nfc : define number of execution cycles without activity, before shutdown is issued
- [default: 10]
- -r nrc : define number of IP scan cycles without any active host [IP] found, before entering
- background scan mode without an active host [IP] present, the script scans
- 'nfc' times the bus ('burst scan'). Then scanning on every execution cycle is deactivated.
- NOTE: Background IP scanning every x execution cycles is always active.
- [default: 10]
- -s slt (sec) : define how long the script will sleep [seconds], before checking again
- [default: 120]
- " 1>&2
- exit 0;
- }
- ################################################################
- #
- # name : _log
- # parameter : $LOGMESSAGE : logmessage in format "PRIORITY: MESSAGE"
- # return : none
- #
- _log()
- {(
- [[ "$*" =~ ^([A-Za-z]*):(.*) ]] &&
- {
- PRIORITY=${BASH_REMATCH[1]}
- LOGMESSAGE=${BASH_REMATCH[2]}
- [[ "$(basename "$0")" =~ ^(.*)\. ]] && LOGMESSAGE="${BASH_REMATCH[1]}[$$]: $PRIORITY: $LOGMESSAGE";
- }
- if $VERBOSE ; then
- # next line only with implementation where logger does not support option '-s'
- # echo "$(date '+%b %e %H:%M:%S'):$LOGMESSAGE"
- [ $SYSLOG ] && $LOGGER -s -t "$(date '+%b %e %H:%M:%S'): $USER" -p $FACILITY.$PRIORITY $LOGMESSAGE
- else
- [ $SYSLOG ] && $LOGGER -p $FACILITY.$PRIORITY $LOGMESSAGE
- fi # > if [ "$VERBOSE" = "NO" ]; then
- )}
- ################################################################
- #
- # name : _ping_range
- # parameter : none
- # global return : ACTIVEIPS : list of all active hosts in given IP range, separated by blank
- # global return : SCANRG : 0 = at least one active IP found
- # return value : CNT : number of active IP hosts within given IP range
- _ping_range()
- {
- CNT=0
- ACTIVEIPS=""
- IPING=
- # separate the IP end number from the loop counter, to give the user a chance to configure the search "algorithm"
- # COUNTUP = 1 means starting at the lowest IP address; COUNTUP=0 will start at the upper end of the given range
- if $DEBUG ; then _log "DEBUG: _ping_range(): RANGE: '$RANGE'" ; fi
- for RG in ${RANGE//,/ } ; do
- if [[ ! "$RG" =~ \.{2} ]]; then
- FINIT="J=$RG"
- FORCHECK="J<=$RG"
- STEP="J++"
- if $DEBUG ; then _log "DEBUG: _ping_range(): Single Number, RG: '$RG', FINIT: '$FINIT', FORCHECK: '$FORCHECK', STEP: '$STEP'" ; fi
- elif [[ "$RG" =~ ^([0-9]{1,3})\.{2}([0-9]{1,3}$) ]]; then
- 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
- if [ ${BASH_REMATCH[2]} -gt ${BASH_REMATCH[1]} ]; then
- FINIT="J=${BASH_REMATCH[1]}"
- FORCHECK="J<=${BASH_REMATCH[2]}"
- STEP="J++"
- if $DEBUG ; then _log "DEBUG: _ping_range(): START < END, RG: '$RG', FINIT: '$FINIT', FORCHECK: '$FORCHECK', STEP: '$STEP'" ; fi
- else
- FINIT="J=${BASH_REMATCH[1]}"
- FORCHECK="J>=${BASH_REMATCH[2]}"
- STEP="J--";
- if $DEBUG ; then _log "DEBUG: _ping_range(): END > START, RG: '$RG', FINIT: '$FINIT', FORCHECK: '$FORCHECK', STEP: '$STEP'" ; fi
- fi # > if [ ${BASH_REMATCH[2]} -gt ${BASH_REMATCH[1]} ]; then
- fi # > iif [[ "$RG" =~ [0-9]{1,3} ]]; then
- for (( $FINIT;$FORCHECK;$STEP )); do
- # Ping each IP address in turn. if we find one -> CNT ++
- # added the redirect to /dev/null, as we are only interested in the return value (no output on console)
- # Log the IP-adresses to ping only in DEBUG-Mode
- if $DEBUG ; then _log "DEBUG: Scan IP $CLASS.$J for active host."; fi
- ping -c 1 -s 8 -t 1 $CLASS.$J > /dev/null &&
- {
- # Found one!!
- _log "INFO: Found IP $CLASS.$J as active host."
- ACTIVEIPS="$ACTIVEIPS$CLASS.$J "
- SCANRG="false"
- let CNT++;
- }
- done # > for (( J=$iSTART;$FORCHECK;$STEP )); do
- done # > for RG in ${RANGE//,/ } ; do
- if $DEBUG ; then _log "DEBUG: _ping_range(): ACTIVEIPS: '$ACTIVEIPS', SCANRG: '$SCANRG', CNT: '$CNT'" ; fi
- return ${CNT};
- }
- ################################################################
- #
- # name : _ping_active_list
- # parameter : ACTIVEIPS : list of all active IPs found
- # global return : SCANRG : 0 = no scan needed; 1 = scan of ACTIVEIPS to be done
- # return : 1 : if no active host has been found
- # : 0 : if at least one active host has been found
- #
- _ping_active_list()
- {
- CNT=0
- IPING=${iSTART}
- if $DEBUG ; then _log "DEBUG: _ping_active_list(): Scan IPs ${1} for activity." ; fi
- for IPADDRESS in "$1"; do
- # Ping each IP address in parameter list. if we find one -> CNT != 0 we'll
- # stop as there's really no point continuing to looking for more.
- # added the redirect to /dev/null, as we are only interested in the return value (no output on console)
- if [ "$IPADDRESS" != "" ];then
- if $DEBUG ; then _log "DEBUG: _ping_active_list(): Scan IP ${IPADDRESS} for activity." ; fi
- ping -c 1 -s 8 -t 1 ${IPADDRESS} > /dev/null
- if [ $? -eq 0 ]; then
- # Found one!!
- _log "INFO: Found IP ${IPADDRESS} still active."
- let CNT++
- SCANRG="false"
- break
- else
- # mark the list as invalid, as there is at least one obsolete IP in it
- _log "INFO: Found IP ${IPADDRESS} inactive; triggered scan of network in next execution"
- SCANRG="true"
- fi # > if [ $? -eq 0 ]; then
- else
- # mark the list as invalid, as there is at least one obsolete IP in it
- _log "INFO: Found no valid IP; triggered scan of network in next execution cycle."
- SCANRG="true"
- fi # > if [ "$IPADDRESS" != "" ];then
- # As 'ping' takes nearly a second, this loop could be very time consuming
- # Do a check for some active processes, maybe, one never knows...
- # If there is at least one active, we leave this function with a 'bogus find'
- _check_processes &&
- {
- let CNT++
- break;
- }
- done # > for IPADDRESS in "$1"; do
- return ${CNT};
- }
- ################################################################
- #
- # name : _shutdown
- # parameter : none
- # return : none, script exit point
- #
- _shutdown()
- {
- # Goodbye and thanks for all the fish!!
- # We've had no responses for the required number of consecutive scans
- # defined in FLAG shutdown & power off.
- _log "INFO: Shutdown issued: shutdown -p now"
- shutdown -p now
- exit 0;
- }
- ################################################################
- #
- # name : _ident_num_proc
- # parameter : $1...$(n-1) : parameter for command 'top'
- # : $n : search pattern for command 'grep'
- # return : none
- #
- _ident_num_proc()
- {
- (
- # retrieve all function parameters for the top command; as we know the last command line parameter
- # is the pattern for the grep command, we can stop one parameter before the end
- [[ "$*" =~ (.*)\ (.*)$ ]] &&
- {
- TPPARAM=${BASH_REMATCH[1]}
- GRPPATTERN=${BASH_REMATCH[2]};
- }
- # _log "DEBUG: _ident_num_proc(): top cmd line: $TPPARAM, grep cmd line: $GRPPATTERN"
- # call top once, pipe the result to grep and count the number of patterns found
- # the number of found processes is returned to the callee
- RVALUE=$(top ${TPPARAM} | grep -c ${GRPPATTERN})
- return $RVALUE
- )
- }
- ################################################################
- #
- # name : _check_processes
- # parameter : none
- # global return : NUMPROC: number of active processes, defined in LOADPROCNAMES and TEMPPROCNAMES
- # return : 1 : if no active process has been found
- # : 0 : if at least one active process has been found
- #
- _check_processes()
- {
- RVALUE=1
- NUMPROC=0
- CHECK=0
- # check for each given command name in LOADPROCNAMES if it is currently stated active in "top"
- # i found, that for smbd, proftpd, nsfd, ... there are processes always present in "ps" or "top" output
- # this could be due to the "daemon" mechanism... Only chance to identify there is something happening with these
- # processes, is to check if "top" states them active -> "-I" parameter on the command line
- for LPROCESS in ${LOADPROCNAMES//,/ } ; do
- LP=0
- IPROC=0
- for ((N=0;N < ${LPREPEAT};N++ )) ; do
- _ident_num_proc ${STOPPARAM} ${LPROCESS}
- RESULT=$?
- LP=$(($LP|$RESULT))
- [ $RESULT -gt 0 ] && let IPROC++
- done
- let NUMPROC=$NUMPROC+$LP
- if ! $DEBUG ; then { [ $LP -gt 0 ] && _log "INFO: _check_processes(): Found active process $LPROCESS"; }; fi
- if $DEBUG ; then _log "DEBUG: _check_processes(): > $LPROCESS: found $IPROC of $LPREPEAT cycles active"; fi
- done # > LPROCESS in ${LOADPROCNAMES//,/ } ; do
- if ! $DEBUG ; then { [ $NUMPROC -gt 0 ] && _log "INFO: Found $NUMPROC active processes in $LOADPROCNAMES" ; }; fi
- # check for each given command name in TEMPPROCNAMES if it is currently stated present in "top"
- # i found, that for sshd, ... there are processes only present in "ps" or "top" output when is is used.
- # it can not be guaranteed, that top states these services active, as they usually wait for user input
- # no "-I" parameter on the command line, but shear presence is enough
- for TPROCESS in ${TEMPPROCNAMES//,/ } ; do
- TP=0
- IPROC=0
- for ((N=0;N < ${TPREPEAT};N++ )) ; do
- _ident_num_proc ${CTOPPARAM} ${TPROCESS}
- RESULT=$?
- TP=$(($TP|$RESULT))
- [ $RESULT -gt 0 ] && let IPROC++
- done
- let CHECK=$CHECK+$TP
- if ! $DEBUG ; then { [ $TP -gt 0 ] && _log "INFO: _check_processes(): Found active process $TPROCESS"; }; fi
- if $DEBUG ; then _log "DEBUG: _check_processes(): > $TPROCESS: found $IPROC of $TPREPEAT cycles active"; fi
- done # > for TPROCESS in ${TEMPPROCNAMES//,/ } ; do
- if ! $DEBUG ; then { [ $CHECK -gt 0 ] &&_log "INFO: Found $CHECK active processes in $TEMPPROCNAMES" ; }; fi
- # Check if there are any connection on $PORT
- for CHECKPORT in $(echo $PORT); do
- # Check how many IPs are connected
- NROFCON=$(netstat -an | grep $CLASS | grep "ESTABLISHED" | grep $FREENASIP.$CHECKPORT | wc -l)
- # Check which IP is connected on the specified Port
- CONIP=$(netstat -an | grep $CLASS | grep "ESTABLISHED" | grep $FREENASIP.$CHECKPORT | awk '{print $5}' | sed 's/\.[0-9]*$//g' | uniq)
- if [ $NROFCON -gt 0 ]; then {
- let CHECK++
- # Set PORTPROTOCOLL
- case $CHECKPORT in
- 80)
- PORTPROTOCOL="HTTP" ;;
- 22)
- PORTPROTOCOL="SSH" ;;
- 21)
- PORTPROTOCOL="FTP" ;;
- 8080)
- PORTPROTOCOL="HTTP" ;;
- 445)
- PORTPROTOCOL="SMB/CIFS" ;;
- *)
- PORTPROTOCOL="unknown" ;;
- esac
- _log "INFO: Found active Connection on Port $CHECKPORT ($PORTPROTOCOL) from $CONIP"
- if $DEBUG ; then {
- _log "DEBUG: check Port: $NROFCON Connections active.";
- _log "DEBUG: NROFCON: $NROFCON ";
- _log "DEBUG: CONIP: $CONIP ";
- }
- fi
- }
- fi
- done
- if $DEBUG ; then _log "DEBUG: cat $UNRARLOGDIR/$UNRARLOG = $(cat $UNRARLOGDIR/$UNRARLOG)"; fi
- UNRARCHECK=0
- if [ $AUTOUNRARCHECK = "true" ]; then
- if $DEBUG ; then _log "DEBUG: AUTOUNRARCHECK is running now" ; fi
- if [ -f $UNRARLOGDIR/$UNRARLOG ]; then
- if [ $(cat "$UNRARLOGDIR/$UNRARLOG") = "processing job" ]; then
- _log "INFO: unrar-script running - no shutdown."
- UNRARCHECK=1
- fi
- fi
- fi
- let NUMPROC=$NUMPROC+$CHECK
- if $DEBUG ; then
- _log "DEBUG: _check_processes(): $NUMPROC process(es) active."
- _log "DEBUG: UNRARCHECK: $UNRARCHECK"
- fi
- [[ $NUMPROC -gt 0 ]] || [[ $UNRARCHECK -gt 0 ]] && RVALUE=0
- # only return we found a process or unrar running
- return $RVALUE
- }
- ######## START OF BODY FUNCTION SCRIPT AUTOSHUTDOWN.SH ########
- # check command line options, on hold as getopt will be available in upcoming release
- #
- ARGS=`getopt "$OPTSTRING" "$*"`
- if [ $? -ne 0 ] ; then
- 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
- exit 2
- fi
- # decoding of command line parameters
- #
- set -- $ARGS
- for I do
- case "$1" in
- -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; };;
- -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; };;
- -b) BOOTUP="true";;
- -d) DEBUG="true";;
- -f) shift; FLAG="$1"; [[ "$FLAG" =~ ^[0-9]{1,3}$ ]] || { echo " -f $1 : Invalid parameter format; [-f nfc]" 1>&2; exit 1; };;
- -l) shift; LOADPROCNAMES="$1"; [[ "$LOADPROCNAMES" =~ ^[[A-Za-z0-9_]\,]$ ]] || { echo " -l $1 : Invalid parameter list format; [-l lproc1,lproc2,lproc3,...]" 1>&2; exit 1; };;
- -r) shift; RESCAN="$1"; [[ "$RESCAN" =~ ^[0-9]{1,3}$ ]] || { echo " -r $1 : Invalid parameter format; [-r nrc]" 1>&2; exit 1; };;
- -s) shift; SLEEP="$1"; [[ "$SLEEP" =~ ^[0-9]{1,3}$ ]] || { echo " -s $1 : Invalid parameter format; [-s slt (sec)]" 1>&2; exit 1; };;
- -t) shift; TEMPPROCNAMES="$1"; [[ "$TEMPPROCNAMES" =~ ^[[A-Za-z0-9_]\,]$ ]] || { echo " -t $1 : Invalid parameter list format; [-t tproc1,tproc2,tproc3,...]" 1>&2; exit 1; };;
- -v) VERBOSE="true";;
- -h) _script_help;;
- --) shift; break ;;
- esac # > case "$1" in
- shift
- done # > for I do
- if $DEBUG ; then
- _log "DEBUG: ARGS: $ARGS "
- _log "DEBUG: CLASS: $CLASS "
- _log "DEBUG: RANGE: $RANGE "
- _log "DEBUG: BOOTUP: $BOOTUP "
- _log "DEBUG: FLAG: $FLAG "
- _log "DEBUG: LOADPROCNAMES: $LOADPROCNAMES "
- _log "DEBUG: RESCAN: $RESCAN "
- _log "DEBUG: SLEEP: $SLEEP "
- _log "DEBUG: TEMPPROCNAMES: $TEMPPROCNAMES "
- _log "DEBUG: VERBOSE: $VERBOSE "
- _log "DEBUG: PORT: $PORT "
- _log "DEBUG: AUTOUNRARCHECK: $AUTOUNRARCHECK";
- _log "DEBUG: UNRARLOG: $UNRARLOG";
- _log "DEBUG: UNRARLOGDIR: $UNRARLOGDIR";
- _log "DEBUG: HOURS: $HOURS";
- _log "DEBUG: STARTTIME: $STARTTIME";
- _log "DEBUG: ENDTIME: $ENDTIME";
- #exit 42;
- fi # > if $DEBUG ;then
- # Init the counters
- FCNT=$FLAG
- SCNCNT=$RESCAN
- BGSCNCNT=$BGSCAN
- # functional start of script
- _log "INFO:-----------------------------script started--------------------------------------"
- _log "INFO: ${FLAG} test cycles until shutdown is issued."
- _log "INFO: network range is given within \"$RANGE\"."
- _log "INFO: Boot up phase is $(if $BOOTUP ; then echo "ACTIVE"; else echo "DISABLED"; fi)"
- while : ; do
- _log "INFO:------------------------------------------------------"
- _log "INFO: new supervision cycle started."
- # Main loop, just keep pinging and checking for processes, to decide whether we can shutdown or not...
- # A master switch for the scheduler
- if $ENABLESCHED ; then
- # Doing a loop to check if time is right and moon phase is correct
- HOURS=`date +%k` # this is used to retrieve starting value for loop check. default: `date +%k`
- if $DEBUG ; then _log "DEBUG: check for scheduler loop with values STARTTIME: $STARTTIME ENDTIME: $ENDTIME and HOURS: $HOURS" ; fi
- while [[ $STARTTIME -gt $HOURS && $ENDTIME -lt $HOURS ]]; do
- sleep $SCHEDSLEEP; # sleeping for predefined seconds
- HOURS=`date +%k` # updating value for HOURS
- _log "INFO: scheduler in sleep for ${SCHEDSLEEP}s and updating HOURS with $HOURS."
- done # we're done with scheduler-loop
- _log "INFO: we got out of the scheduled loop succesfully."
- fi # > ENABLESCHED exist
- # Counter to implement maximum $RESCAN number of execution cycles with active IP scanning; then only the
- # IP scan in background once every $BGSCAN cycles is active to reduce network traffic
- #
- if [ $SCNCNT -gt 0 ] ; then
- if $DEBUG ; then _log "DEBUG: main: SCNCNT is > 0, SCNCNT: '$SCNCNT', SCANRG: '$SCANRG'" ; fi
- # decrease counter
- if $SCANRG ; then if $BOOTUP ;then : ; else let SCNCNT--; fi ; fi
- else
- SCANRG="false" # suppress scanning always
- if $DEBUG ; then _log "DEBUG: main: SCNCNT is 0, SCANRG: '$SCANRG'" ; fi
- fi # > if [ $SCNCNT -gt 0 ] ; then
- # IP scan in background once every $BGSCAN cycles; the background scan also allows to identify
- # new hosts [IPs] and add them to the $ACTIVEIPS list of active IPs
- #
- if [ $BGSCNCNT -gt 0 ] ; then
- if $DEBUG ; then _log "DEBUG: main: BGSCNCNT is > 0, BGSCNCNT: '$BGSCNCNT', SCANRG: '$SCANRG'" ; fi
- let BGSCNCNT--
- else
- BGSCNCNT=$BGSCAN # reset the counter, to start again
- SCANRG="true" # scan once
- if $DEBUG ; then _log "DEBUG: main: BGSCNCNT has been 0, BGSCNCNT: '$BGSCNCNT', SCANRG: '$SCANRG'" ; fi
- fi # > if [ $BGSCNCNT -gt 0 ] ; then
- _log "INFO: Current IP scan mode: $(if ( $BOOTUP || $SCANRG ); then echo "FULL"; else echo "BACKGROUND"; fi)"
- if $SCANRG -o $BOOTUP ; then
- # retrieve all currently active IPs in your network
- # if there has none active found try again after $SLEEP seconds in next execution cycle
- _log "INFO: retrieve list of active IPs..."
- if ! $DEBUG ; then _log "INFO: IPs not shown, use \"autoshutdown.sh -d\" for more Info"; fi
- # if there have been active IPs found, there is no need to scan in next execution cycle
- _ping_range || { BOOTUP="false"; SCNCNT=$RESCAN; }
- RESULT=$?
- if $DEBUG ; then
- for IP in $ACTIVEIPS ; do
- _log "DEBUG: > IP ${IP} currently active."
- done
- _log "DEBUG: Variable SCANRG: '$SCANRG', BOOTUP: '$BOOTUP', SCNCNT: '$SCNCNT'"
- SCANRG="false"
- fi # > if $DEBUG ; then
- fi # > if $SCANRG -o $BOOTUP ; then
- # search strategy; 1st ping host adresses
- # check for processes in between each 'ping'
- _log "INFO: check number of active hosts in configured network range..."
- if _ping_active_list $ACTIVEIPS ; then
- # check if we are still in the boot up phase (no shutdown until we have found our first active IP)
- if $BOOTUP ; then
- _log "INFO: Boot up phase is still ACTIVE"
- else
- if $DEBUG ; then _log "DEBUG: Boot up phase is DISABLED" ; fi
- # Nothing found so sub one from the count and check if we can shutdown yet.
- let FCNT--
- _log "INFO: No active processes, unraring or hosts within network range, ${FCNT} cycles until shutdown..."
- if [ $FCNT -eq 0 ]; then
- _shutdown;
- fi # > if [ $FCNT -eq 0 ]; then
- fi # > if $BOOTUP ; then : ; else
- else
- # Live IP found so reset count
- FCNT=${FLAG};
- fi # > if { _ping_active_list $ACTIVEIPS }, then
- # Wait for the required time before checking again.
- _log "INFO: sleep for ${SLEEP}s."
- sleep $SLEEP;
- done # > while : ; do
- #EOF####### END OF SCRIPT AUTOSHUTDOWN.SH ########
Add Comment
Please, Sign In to add comment