Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Update Dynamic DNS record when it's really needed.
#!/usr/bin/python2
# -*- coding: utf-8 -*-
import logging
import os
import re
import subprocess
import sys
import syslog
import dns.resolver
DNS_MASTER = '106.187.55.63'
INSTRUCTION_FILE = '/tmp/ddns_update.txt'
def get_current_ip():
p = subprocess.Popen('ifconfig ppp0', shell=True, stdout=subprocess.PIPE)
stdout, _ = p.communicate()
rc = p.returncode
m = re.compile('inet (\d+\.\d+\.\d+\.\d+)').search(stdout)
ip = m.group(1)
return ip
def update(hostname, ip, zone="momoka.net", ttl=60):
ins = """
server %(dns_master)s
zone %(zone)s
update del %(hostname)s.%(zone)s. A
update add %(hostname)s.%(zone)s. %(ttl)s A %(ip)s
send
""" % dict(
dns_master=DNS_MASTER,
zone=zone,
hostname=hostname,
ip=ip,
ttl=ttl
)
with open(INSTRUCTION_FILE, 'w') as f:
f.write(ins)
p = subprocess.Popen(
('/usr/bin/nsupdate -k '\
'/root/Kyukari.dyn.areverie.org.+157+27661.private %s') % INSTRUCTION_FILE,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
os.remove(INSTRUCTION_FILE)
if p.returncode == 0:
syslog.syslog('%s.%s updated to %s' % (hostname, zone, ip) )
else:
syslog.syslog(syslog.LOG_ERR, '%s.%s updated error: %s' % (hostname, zone, stderr))
def update_momoka(hostname, zone):
current_ip = get_current_ip()
r = dns.resolver.Resolver()
r.nameservers = [DNS_MASTER]
domain = '%s.%s' % (hostname, zone)
try:
a = r.query(domain, 'A')
result = a[0].to_text()
if result != current_ip:
update(hostname, current_ip, zone)
except dns.resolver.NXDOMAIN:
update(hostname, current_ip, zone)
except Exception as err:
logging.exception(err)
syslog.syslog(syslog.LOG_ERR, str(err))
def main():
domains = {
'momoka.net': ['dyn', 'wiki', 'mirrors', 'maven', 'r', 'reader', 'mail', 'cgit']
}
for zone in domains:
hostnames = domains.get(zone)
for hostname in hostnames:
update_momoka(hostname, zone)
if __name__ == '__main__':
sys.exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.