]>
Commit | Line | Data |
---|---|---|
b0ae83b0 MF |
1 | #!/usr/bin/env python3 |
2 | ||
3 | """Update HS DNS settings behind Google WiFi systems.""" | |
4 | ||
5 | import argparse | |
6 | import json | |
7 | import urllib.request | |
8 | import urllib.parse | |
9 | import sys | |
10 | ||
11 | import dns.resolver | |
12 | ||
13 | ||
14 | WIFI_STATUS_URI = 'http://192.168.86.1/api/v1/status' | |
15 | ||
16 | ||
17 | def get_wan_ip(): | |
18 | with urllib.request.urlopen(WIFI_STATUS_URI) as req: | |
19 | data = req.read() | |
20 | status = json.loads(data) | |
21 | return status['wan']['localIpAddress'] | |
22 | ||
23 | ||
24 | def update_ip(hostname, password, ip=None): | |
25 | """Update HE DNS with new settings.""" | |
26 | params = { | |
27 | 'hostname': hostname, | |
28 | 'password': password, | |
29 | } | |
30 | if ip: | |
31 | params['myip'] = ip | |
32 | body = urllib.parse.urlencode(params).encode() | |
33 | ||
34 | url = 'https://dyn.dns.he.net/nic/update' | |
35 | req = urllib.request.Request(url, body) | |
36 | ||
37 | with urllib.request.urlopen(req) as response: | |
38 | return response.read() | |
39 | ||
40 | ||
41 | def get_parser(): | |
42 | """Get CLI parser.""" | |
43 | parser = argparse.ArgumentParser(description=__doc__) | |
44 | parser.add_argument('--hostname', required=True) | |
45 | parser.add_argument('-p', '--password', '--key', required=True) | |
46 | parser.add_argument('-a', '--address', '--ip') | |
47 | parser.add_argument('-q', '--quiet', action='store_true') | |
48 | return parser | |
49 | ||
50 | ||
51 | def main(argv): | |
52 | """The main entry point for scripts.""" | |
53 | parser = get_parser() | |
54 | opts = parser.parse_args(argv) | |
55 | ||
56 | if opts.quiet: | |
57 | p = lambda *args: None | |
58 | else: | |
59 | p = print | |
60 | ||
61 | curr_ip = get_wan_ip() | |
62 | p('Current IP', curr_ip) | |
63 | ||
64 | p('Looking up', opts.hostname, '...') | |
65 | answers = dns.resolver.resolve(opts.hostname, 'A') | |
66 | for msg in answers: | |
67 | p('Current DNS', msg.to_text()) | |
68 | if curr_ip != msg.to_text(): | |
69 | p('Updating IP') | |
70 | resp = update_ip(opts.hostname, opts.password, opts.address) | |
71 | p(resp) | |
72 | else: | |
73 | p('Up-to-date!') | |
74 | break | |
75 | ||
76 | ||
77 | if __name__ == '__main__': | |
78 | sys.exit(main(sys.argv[1:])) |