Update: you can find a fully automated script here. If you’d rather do it manually.. keep reading…
Here’s a quick guide to unban all ip’s from a fail2ban jail in linux.
This is semi-automatic with some user input involved. You also may need to change file paths and script commands to cater for your system’s configuration. Lets get started.
Gather a list of IP’s currently banned.
We need a list of currently banned IP’s;
# sudo fail2ban-client status sshd | cat > /home/MyUser/banned.txt
This queries the fail2ban jail status and passes the output into banned.txt in your user’s home directory. (change f2b jail status command and MyUser or PATH to fit your configuration)
Modify the newly created banlist file
Next, if you look at your newly created file, you should see some jail information and finally the banned IP’s on a single row. We need to make the file readable before we send it over to the unban script for processing. The script is simple, but can only read IP’s line by line. For modification, we will now use ‘sed’ to get the IP’s in line.
# sed 's/\s/\n/g' /home/MyUser/banned.txt | cat > /home/MyUser/bannedips.txt
This command uses sed to replace any SPACE BAR characters (the spaces seperating the IP’s from eachother) with a NEW LINE character; thus placing each IP on it’s own line. It then sends the altered file to a new file called bannedips.txt in your home user DIR. You can now delete bannned.txt.
Secondly, you will need to clean up bannedips.txt. If you load the file into an editor, you’ll notice that text is now scattered all over the top of the list of IP’s. Remove all text from this file, until the first IP is at the top of the file. Save the file.
Automate the banning process
Here’s a really small script that you will need. Open your editor under the name ‘fail2ban-unban-script.sh’ and enter the details as follows:
#!/bin/bash input="/home/MyUser/bannedips.txt" while IFS= read -r var do sudo fail2ban-client set sshd unbanip $var done < "$input"
Again, please change the “input” line or the fail2ban unbanip command to suite your system.
Issue this command to make this script executable:
# chmod +x /home/MyUser/fail2ban-unban-script.sh
Now you have all the pieces to start your mas-unban campaign!
To run your script, simply type:
It will unban the IP’s one at a time; if you have many, it could take a while.
Hope this helps!