Script Linux to check Dynamic Source IP and Add to IPTables Whitelist


#!/bin/bash
# DNS address to resolve
DNS_ADDRESS="server.ddns.com"
# Path to store the last resolved IP
IP_FILE="/etc/asterisk/last_ip.txt"

# Function to resolve DNS and update iptables rule
# Resolve DNS to get the current IP
NEW_IP=$(dig +short $DNS_ADDRESS | tail -1)

# Read the last saved IP
LAST_IP=$(cat $IP_FILE 2>/dev/null)

# Compare the IPs
if [ "$NEW_IP" != "$LAST_IP" ]; then
# Delete old iptables rule if it exists
sudo iptables -D INPUT -s $LAST_IP -j ACCEPT 2>/dev/null
# Update iptables rule
sudo iptables -I INPUT -s $NEW_IP -j ACCEPT 2>/dev/null
# Save the new IP to file
echo $NEW_IP > $IP_FILE
#        echo "IP updated to $NEW_IP"
#    else
#        echo "IP is already up to date"
fi

Execute Permission:

Chmod +x /etc/asterisk/script_atualiza_IP

Crontab:

*/59 * * * * root /etc/asterisk/script_atualiza_ip

Deixe um comentário