Created
March 28, 2024 01:59
-
-
Save EnisBerk/06ccc8241a1ab30a8699d9ce43a222df to your computer and use it in GitHub Desktop.
bash script to unblock IP from iptables and denyhosts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Check if an IP address is provided | |
if [ -z "$1" ]; then | |
echo "Usage: $0 <IP>" | |
exit 1 | |
fi | |
# Check if the provided argument is a valid IP address | |
if ! echo "$1" | grep -Pq '^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$'; then | |
echo "Invalid IP address: $1" | |
exit 1 | |
fi | |
# Unblock an IP address from denyhosts and iptables | |
IP=$1 | |
# Check if IP is blocked in denyhosts | |
denyhosts_blocked=$(grep -l $IP /var/lib/denyhosts/* /etc/hosts.deny) | |
# Check if IP is blocked in iptables | |
iptables_blocked=$(iptables -L INPUT -v -n | grep $IP) | |
if [ -z "$denyhosts_blocked" ] && [ -z "$iptables_blocked" ]; then | |
echo "IP $IP is not blocked. Exiting." | |
exit 0 | |
fi | |
echo "IP $IP is blocked. Unblocking..." | |
/etc/init.d/denyhosts stop | |
for f in /var/lib/denyhosts/* /etc/hosts.deny ; do | |
grep -v $IP $f > tmp | |
mv tmp $f | |
done | |
# Loop over iptables rules and remove all instances of the IP | |
while iptables -D INPUT -s $IP -j DROP 2> /dev/null; do | |
echo "Removed iptables rule for IP $IP" | |
done | |
/etc/init.d/denyhosts start | |
echo "IP $IP has been unblocked." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment