VNDL_Kapper

fail2ban-watch.sh

May 27th, 2020
242
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.63 KB | None | 0 0
  1. #!/bin/bash
  2. ## Author: Shaun Reed | Contact: [email protected] | URL: www.shaunreed.com ##
  3. ##                                                                           ##
  4. ## A script to watch for modifications to fail2ban active jail status        ##
  5. ## Emails contents of custom log after its unmodified for 300 secconds       ##
  6. ###############################################################################
  7.  
  8. lockFile=$(find /root/ -name fail2ban-watch.lock -type f -print)
  9.  
  10. #
  11. # Makes script wait until a file is unmodified for a given timeframe
  12. # $1 = file, $2 = time in seconds to wait
  13. checkmod () {
  14.   lastModificationSeconds=$(date +%s -r $1)
  15.   currentSeconds=$(date +%s)
  16.   elapsedSeconds=$((currentSeconds - lastModificationSeconds))
  17.   while [ $elapsedSeconds -lt $2 ]
  18.   do
  19.     lastModificationSeconds=$(date +%s -r $1)
  20.     currentSeconds=$(date +%s)
  21.     elapsedSeconds=$((currentSeconds - lastModificationSeconds))
  22.     # Add some exception for abnormally long elapsedSeconds
  23.   done
  24. }
  25.  
  26.  
  27. if [ -n "$lockFile" ]
  28. then
  29.   # If a lockFile exists, there is already an instance of this script running
  30.   # Do nothing and exit normally.
  31.   exit 0
  32. else
  33.   # If it doesn't exist, create a lockFile
  34.   touch /root/fail2ban-watch.lock
  35.   printf "/root/fail2ban-watch.lock created\n"
  36.   touch /root/fail2bans
  37.   # Wait for /root/fail2bans to go unmodified for 300 seconds before continuing
  38.   checkmod "/root/fail2bans" "300"
  39.  
  40.   # After time has passed, send email
  41.   cat /root/fail2bans | mail -s "Fail2ban active jail status has changed on $HOSTNAME" someone@somedomain.com
  42.   # Clean up files
  43.   rm /root/fail2ban-watch.lock /root/fail2bans
  44. fi
Add Comment
Please, Sign In to add comment