Skip to content

Instantly share code, notes, and snippets.

@JuniYadi
Created May 18, 2023 05:39
Show Gist options
  • Save JuniYadi/a0b1fc3273fbf81dbc00180df848fc32 to your computer and use it in GitHub Desktop.
Save JuniYadi/a0b1fc3273fbf81dbc00180df848fc32 to your computer and use it in GitHub Desktop.
proxmox-access-log-block.sh
#!/bin/bash
log_file="/var/log/pveproxy/access.log"
iptables_chain="INPUT"
iptables_action="-A"
iptables_command="/sbin/iptables"
iptables_log_prefix="[BLOCKED IP]"
# Regular expression pattern to match IP addresses and status codes in the log file
log_entry_pattern="([0-9]{1,3}\.){3}[0-9]{1,3}.* 200"
# Filter log entries using awk and extract unique IP addresses
filtered_ips=$(awk '!/'"$log_entry_pattern"'/ { print $1 }' "$log_file" | cut -d":" -f4 | sort | uniq)
# Read the filtered unique IP addresses
while IFS= read -r ip_address; do
# Check if the IP address already exists in iptables
existing_rule=$("$iptables_command" -C "$iptables_chain" -s "$ip_address" -j DROP 2>/dev/null)
if [[ $? -eq 0 ]]; then
# IP address already exists, skip adding the rule
echo "IP address $ip_address already exists in iptables, skipping..."
continue
fi
# Execute iptables command to block the IP address
iptables_rule=("$iptables_command" "$iptables_action" "$iptables_chain" -s "$ip_address" -j DROP)
"${iptables_rule[@]}"
# Log the blocked IP address
echo "$iptables_log_prefix Blocked IP address: $ip_address"
done <<< "$filtered_ips"
# Save iptables rules
"$iptables_command" -w -t filter -L -n > /etc/iptables/rules.v4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment