-
Notifications
You must be signed in to change notification settings - Fork 0
/
update_dns.py
61 lines (48 loc) · 1.64 KB
/
update_dns.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
from datetime import datetime
import os
import requests
KEY = os.environ['API_KEY']
DOMAIN = os.environ['DOMAIN']
IP_LOOKUP_URL=os.environ.get('IP_LOOKUP_URL', 'https://api.ipify.org/?format=text')
TYPE = 'A'
def get_ip():
res = requests.get(IP_LOOKUP_URL)
res.raise_for_status()
return res.text.strip()
def request(cmd, **kwargs):
params = {
'key': KEY,
'format': 'json',
'cmd': cmd
}
for key in kwargs:
params[key] = kwargs[key]
res = requests.get('https://api.dreamhost.com', params=params)
res.raise_for_status()
return res.json()
def list_dns():
return request('dns-list_records')
def remove_dns(record, type, value):
return request('dns-remove_record', record=record, type=type, value=value)
def add_dns(record, type, value):
return request('dns-add_record', record=record, type=type, value=value, comment=datetime.now().__str__())
if __name__ == '__main__':
my_ip = get_ip()
entries = list_dns()
need_update = True
for domain in DOMAIN.split(','):
found = False
for entry in entries['data']:
if entry['type'] == TYPE and entry['record'] == domain:
found = True
if entry['value'] != my_ip:
# Need to update
remove_dns(entry['record'], entry['type'], entry['value'])
break
else:
need_update = False
if not found or need_update:
print('Updating {} IP to {}'.format(domain, my_ip))
add_dns(domain, TYPE, my_ip)
else:
print('No change for {}'.format(domain))