Last active
July 2, 2019 07:42
-
-
Save ashafer01/262e59bd3cf00d4b7c339e5a756083e4 to your computer and use it in GitHub Desktop.
Use the Digital Ocean DNS API to implement dynamic DNS
This file contains hidden or 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 python3 | |
## Setup: | |
## 0. See if you have a better way than the default below to find your WAN IP | |
## 1. Create the record using the control panel manually, set ttl to 30 or 60, set to dummy IP | |
## 2. Create an API token specific to this application | |
## 3. pip/pip3 install requests | |
## 4. Update the variables below and add cron job | |
# config | |
base = 'https://api.digitalocean.com/v2' | |
domain = 'YOUR_DOMAIN' | |
domain_name = 'YOUR_HOSTNAME' | |
token = 'YOUR_API_TOKEN' | |
import requests | |
# the following default for obtaining WAN IP will work fine | |
# however if this 3rd party site is ever compromised or turns malicious, | |
# you and your users could be compromised. A higher security method is | |
# recommended | |
wan_ip = requests.get('https://icanhazip.com').text.strip() | |
# this is what i use to get my WAN IP | |
# SSH's to my router utilizing SSH key for auth and uses the same method | |
# that onboard dynamic DNS uses | |
# (setting up persistant storage on the router to run this there seemed annoying) | |
#from subprocess import check_output | |
#wan_ip = check_output(['ssh', '[email protected]', 'nvram', 'get', 'wan0_ipaddr']).decode('utf-8').strip() | |
## main | |
auth_headers = {'Authorization': f'Bearer {token}'} | |
records = requests.get(f'{base}/domains/{domain}/records', headers=auth_headers).json() | |
record_id = None | |
for rec in records['domain_records']: | |
if rec['name'] == domain_name: | |
record_id = rec['id'] | |
break | |
if not record_id: | |
raise Exception(f'Could not find {domain_name}.{domain}') | |
requests.put(f'{base}/domains/{domain}/records/{record_id}', headers=auth_headers, | |
json={'data': wan_ip}) | |
print(f'Updated {domain_name}.{domain} to {wan_ip}') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment