Last active
February 23, 2019 10:45
-
-
Save Tam/d85cc926ee1fd88dd0cf352ce54b0f23 to your computer and use it in GitHub Desktop.
Digital Ocean IP A record updater
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
*/15 * * * * python /path/to/ddns.py |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import urllib2 | |
import json | |
# Config | |
# NOTE: Requires Python 2.7 | |
apiKey = '' # Your DO api key | |
domain = '' # The domain who's record you want to update (i.e. example.com) | |
record = '' # The record (hostname) you want to update (i.e. myrecord of myrecord.example.com) | |
# Internal Consts | |
url = 'https://api.digitalocean.com/v2/domains/' + domain + '/records' | |
headers = { | |
'Content-type': 'application/json', | |
'Authorization': 'Bearer ' + apiKey, | |
} | |
# Internal functions | |
# Query the DO API | |
def query(p='', data=None): | |
req = urllib2.Request(url + p, data, headers) | |
if data is not None: | |
req.get_method = lambda: 'PUT' | |
res = urllib2.urlopen(req) | |
return res.read().decode('utf8') | |
# Get the record | |
def get_record(): | |
res = json.loads(query()) | |
for rec in res['domain_records']: | |
if rec['type'] == 'A' and rec['name'] == record: | |
return rec | |
raise Exception('Couldn\'t find record: %s' % record) | |
# 1. Get the current IP | |
ip = urllib2.urlopen('https://ipinfo.io/ip').read().strip() | |
# 2. Update the record | |
query( | |
'/' + str(get_record()['id']), | |
json.dumps({'data': ip}).encode('utf8') | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment