Monday, November 09, 2015

Script to update godaddy dns A record

Recently, I have setup my raspberry pi as a download machine. The aim was to be able to access the machine from anywhere and be able to add files to download. Now, since the machine is connected via airtel broadband, it is bound to go down and come up as and when the electricity in my location does.

Everytime, when the machine came up, i would be having a different public ip address to access the machine as my ADSL modem+router would also go down.

At first, i setup a cron to be run at boot time which would give me the public ip address.

#!/usr/bin/env python
import pif
public_ip = pif.get_public_ip()
print(public_ip)
view raw ip.py hosted with ❤ by GitHub
The corresponding cron entry is
@reboot /home/pi/progs/godaddy.py

I also created a dns entry to access the machine. And then wrote a script to update the dns record in godaddy whenever the machine reboots. Here is the script.

#!/usr/bin/env python
import pygodaddy
import logging
import pif
godaddy_log_file = '/tmp/godaddy.log'
ip_address_file = '/home/pi/progs/ipaddress'
logging.basicConfig(filename=godaddy_log_file, format='%(asctime)s %(message)s', level=logging.INFO)
logging.getLogger("requests").setLevel(logging.DEBUG)
public_ip = pif.get_public_ip()
logging.info("INFO : ip_address = %s",str(public_ip))
ipfile = open(ip_address_file,'r')
old_public_ip = ipfile.read()
ipfile.close()
if public_ip == old_public_ip:
logging.info("INFO : ip address %s not changed",str(old_public_ip))
quit()
logging.info("INFO : Updating ip address")
client = pygodaddy.GoDaddyClient()
U = "username"
P = "password"
success = client.login(U,P)
if success:
domains = client.find_domains()
for domain in domains:
logging.info("INFO : Domain - %s",str(domain))
dns_records = client.find_dns_records(domain)
for record in dns_records:
logging.info("INFO : processing >>> %s", str(record))
if record.hostname == 'home':
logging.info("INFO : Found domain - home | updating...")
if record.value != public_ip:
client.update_dns_record('home.jayantkumar.in', public_ip)
logging.info("INFO : dns updated!!!")
logging.info("INFO : updating local file")
ipfile = open(ip_address_file,'w')
ipfile.truncate()
ipfile.write(public_ip)
ipfile.close()
logging.info("INFO : local file updated")
print("all done...\n")
view raw godaddy.py hosted with ❤ by GitHub
Now whenever my pi reboots, it checks and updates the corresponding DNS record at godaddy. And i can ssh my machine from anywhere.

No comments: