Using IPTables with Dynamic IP hostnames like dyndns.org

Whenever IPTables has a hostname in a rule it looks up the hostname’s IP address and uses that instead of the actual hostname – so it’s stuck with the IP until the next time IPTables is flushed/restarted. Here’s a quick little python script to stick in a crontab which checks the IP of your dynamic IP hostname (free ones provided by dyndns.org) and will restart iptables if it catches a change in your hostname. Viewable Source After Jump

I just set this up as root and in root’s crontab.

Download Source

Source:

#!/usr/bin/python

import os

def gettextoutput(cmd):
    """Return (status, output) of executing cmd in a shell."""
    pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
    pipe = os.popen(cmd + ' 2>&1', 'r')
    text = pipe.read()
    if text[-1:] == '\n': text = text[:-1]
    return text

home_dyndns = "example.dyndns.org"
log_dyndns = "./new_home_ip_check.log"
last_dyndns = gettextoutput("cat " + log_dyndns)
cur_dyndns = gettextoutput("host " + home_dyndns)

print "Log: "+ last_dyndns
print "Cur: "+ cur_dyndns

if last_dyndns == cur_dyndns:
    print "IPs match, no restart necessary"
else:
    print "Updating last IP with current"
    os.system("echo '" + cur_dyndns + "' > " + log_dyndns)
    print "Restarting iptables to update"
    os.system("/etc/init.d/iptables restart")

Output looks like:

Log: example.dyndns.org has address 114.76.37.112
Cur: example.dyndns.org has address 114.76.37.112
IPs match, no restart necessary

Log: example.dyndns.org has address 114.76.37.113
Cur: example.dyndns.org has address 114.76.37.112
Updating last IP with current
Restarting iptables to update
Flushing firewall rules:                                   [  OK  ]
Setting chains to policy ACCEPT: filter                    [  OK  ]
Unloading iptables modules:                                [  OK  ]
Applying iptables firewall rules:                          [  OK  ]
Loading additional iptables modules: ip_conntrack_netbios_n[  OK  ]
Share and Enjoy:
  • Print
  • Facebook
  • Reddit
  • Digg
  • Tumblr
  • Google Bookmarks
  • del.icio.us
  • StumbleUpon
This entry was posted in code, linux, python. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>