fail2ban_clear.sh 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #!/bin/bash
  2. # Original script by Walter Heitman Jr, first published on http://blog.shanock.com
  3. #
  4. # Permission is hereby given to use, modify, or redistribute this code in any form or
  5. # fashion for any purpose, private or commercial, so long as the credit comment is left intact.
  6. # Location of Fail2Ban sqlite database
  7. DATABASE=/var/lib/fail2ban/fail2ban.sqlite3
  8. # iprables prefix for Fail2ban chains. Default is "fail2ban"
  9. JAILPREFIX="f2b"
  10. # Get Jails. You can manually change this to a list of jails, as per the commented-out example
  11. JAILS=$(fail2ban-client status | grep "Jail list" | cut -f2- | sed 's/,//g')
  12. #JAILS="postfix-sasl sshd apache-auth"
  13. # See if user wants to force the unban via direct iptables command (i.e. fail2ban lost its database)
  14. FORCE=0
  15. while getopts "f" OPTION; do
  16. case $OPTION in
  17. f)
  18. FORCE=1
  19. shift $(($OPTIND - 1))
  20. ;;
  21. esac
  22. done
  23. # Loop through each jail
  24. for JAIL in $JAILS; do
  25. # Ask iptables and loop through each IP in the jail
  26. for IPADDRESS in $(iptables -L $JAILPREFIX-$JAIL -n | grep -Eo '([0-9]{1,3}\.){3}[1-9]{1,3}' | grep -v '0.0.0.0'); do
  27. # Check for parameters, which should be individual IPs to unban
  28. if [ $1 ]; then
  29. # Loop through parameters
  30. for UNBANTHIS in "$@"; do
  31. # If match, unban it the "correct" way
  32. if [ $UNBANTHIS == $IPADDRESS ]; then
  33. fail2ban-client set $JAIL unbanip $IPADDRESS
  34. # If force, make sure IP is unbanned via direct command to iptables
  35. if [ $FORCE == 1 ]; then
  36. /sbin/iptables -D $JAILPREFIX-$JAIL -s $IPADDRESS -j REJECT
  37. fi
  38. fi
  39. done
  40. else
  41. # If no parameters are specified, just unban everything we find
  42. fail2ban-client set $JAIL unbanip $IPADDRESS
  43. fi
  44. done
  45. done
  46. # Force clear from fail2ban database
  47. if [ $1 ]; then
  48. # Loop through parameters, clear each IP from all jails
  49. for UNBANTHIS in "$@"; do
  50. echo -e ".timeout 10000\ndelete from bans where ip = '$UNBANTHIS';" | sqlite3 -echo $DATABASE
  51. done
  52. else
  53. # If no parameters are specified, just purge the entire database
  54. echo -e ".timeout 10000\ndelete from bans;" | sqlite3 -echo $DATABASE
  55. if [ $FORCE == 1 ]; then
  56. # If force, flush every iptables chain
  57. for JAIL in $JAILS; do
  58. /sbin/iptables -F $JAILPREFIX-$JAIL
  59. done
  60. fi
  61. fi