porkbun-dynamic-dns-python/porkbun-ddns.py
2022-07-21 14:26:39 -05:00

47 lines
1.3 KiB
Python
Executable file

#!/usr/bin/python
from argparse import ArgumentParser
from ipaddress import ip_address
from json import load, loads, dumps
from requests import post
endpoint = 'https://porkbun.com/api/json/v3/'
endpoint_ipv4 = 'https://api-ipv4.porkbun.com/api/json/v3/'
# Parse arguments and load config
parser = ArgumentParser()
parser.add_argument('config', help='path to config file')
args = parser.parse_args()
data = load(open(args.config))
if 'name' in data:
domain = data['name'] + '.' + data['domain']
else:
domain = data['domain']
def api(url):
"""Make a request to the Porkbun API"""
return loads(post(url, dumps(data)).text)
def edit_record(id, ip):
"""Edit a A or AAAA record to point to a new IP address"""
print('Updating ' + data['domain'] + ' to ' + str(ip))
data['type'] = 'A' if ip.version == 4 else 'AAAA'
data['content'] = str(ip)
return api(endpoint + 'dns/edit/' + data['domain'] + '/' + id)
# Update records
for record in api(endpoint + 'dns/retrieve/' + data['domain'])['records']:
if record['name'] == domain and record['type'] in 'AAAA':
ip = ip_address(api((endpoint_ipv4 if record['type'] == 'A' else endpoint) + 'ping')['yourIp'])
if not str(ip) == record['content']:
print(edit_record(record['id'], ip))