-
Notifications
You must be signed in to change notification settings - Fork 0
/
dnsHEnet-update.py
95 lines (75 loc) · 2.54 KB
/
dnsHEnet-update.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#!/usr/bin/env python
import argparse
import dns.resolver
import logging
import random
import re
import requests
import yaml
# arguments
parser = argparse.ArgumentParser(description='Python script to update domains on dns.he.net.')
parser.add_argument('configfile', help='set config file')
parser.add_argument('-v', '--verbose', action='store_true', help='set log to DEBUG')
parser.add_argument('-l', '--logfile', help='set log file')
args = parser.parse_args()
# logging
log = logging.getLogger('dnsHEnet-update')
if args.logfile:
FORMAT = '%(asctime)-15s - %(levelname)s - %(message)s'
logging.basicConfig(filename=args.logfile, format=FORMAT)
else:
FORMAT = '%(levelname)s - %(message)s'
logging.basicConfig(format=FORMAT)
if args.verbose:
log.setLevel(logging.DEBUG)
# configuration
with open(args.configfile, "r") as ymlfile:
cfg = yaml.load(ymlfile)
# function - get external IP
def getExternalIP(urls):
url = urls[random.randint(0,len(urls)-1)]
ipPattern = re.compile('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')
response = requests.get(url)
ip = re.findall(ipPattern, response.text)[0]
log.debug("External IP from {url}: {ip}".format(ip=ip, url=url))
return str(ip)
# function - get IP of domain record
def getRecordIP(domains):
domain = dict(domains[0])
domain, password = domain.popitem()
resolver = dns.resolver.Resolver()
resolver.nameservers = ['8.8.8.8']
try:
answer = resolver.query(domain)
ip = answer[0]
except:
log.error("DNS query failed for {domain}.".format(domain=domain))
log.debug("IP from A record ({domain}): {ip}".format(ip=ip, domain=domain))
return str(ip)
# function - update domains
def updateDNS(domains):
for item in domains:
host, password = item.popitem()
url = "https://dyn.dns.he.net/nic/update?hostname={host}&password={pwd}".format(host=host, pwd=password)
response = requests.get(url, verify=False)
log.debug("Response from dyn.dns.he.net: {resp}.".format(resp=response.text))
return True
# main
if cfg is None:
log.error("Config file is empty.")
exit(1)
if 'ipcheck_urls' in cfg:
urls = cfg['ipcheck_urls']
externalIP = getExternalIP(urls)
else:
log.error("Config file: No urls are given to check external IP.")
exit(1)
if 'domains' in cfg:
domains = cfg['domains']
recordIP = getRecordIP(domains)
else:
log.error("Config file: No domains are given.")
exit(1)
if externalIP != recordIP:
log.info("IP has changed. Update domains...")
updateDNS(domains)