Skip to content

Setup: Dynamic iptables update

Aaron Priebe edited this page Jan 30, 2023 · 2 revisions
touch ~/relay_ip_log

Create /etc/iptables_update.bash

#!/bin/bash
#allow a dyndns name

HOSTNAME=<hostname>
LOGFILE=/home/cardano/relay_ip_log
ETH=eno1
PORT=6014

Current_IP=$(host $HOSTNAME | cut -f4 -d' ' | tr -d '\n')
echo 'Current IP: '$Current_IP

if [ ! -s $LOGFILE ] ; then
  echo 'Adding rule for ' $Current_IP
  echo 'test'
  iptables -I INPUT -p tcp -s $Current_IP --dport $PORT -j ACCEPT
  echo $Current_IP > $LOGFILE
else

  Old_IP=$(cat $LOGFILE)
  Old_IP=$(echo $Old_IP|tr -d '\n')
  echo 'Old IP: ' $Old_IP

  if [ "$Current_IP" = "$Old_IP" ] ; then
    echo IP address has not changed
  else
    echo 'Removing rule for ' $Old_IP
    iptables -D INPUT -i $ETH -s $Old_IP -j ACCEPT

    echo 'Adding rule for ' $Current_IP
    iptables -I INPUT -p tcp -s $Current_IP --dport $PORT -j ACCEPT

    /etc/init.d/iptables save
    echo $Current_IP > $LOGFILE
    echo iptables have been updated
  fi
fi

Then:

sudo crontab -e

Paste at the end

*/5 * * * * root /etc/iptables_update.bash