-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy patharcherUpdateDDNSRecord.py
540 lines (461 loc) · 18.7 KB
/
archerUpdateDDNSRecord.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
#!/usr/bin/env python
# Tool to update the DDNS record for the TP-LINK ARCHER MR600 router
# It uses my web Scrapping package to get the IP Address (public) of the router
# and the noipy package to update the DDNS record at No-IP
import builtins as __builtin__
import inspect
import os
import socket
import sys
import time
import requests
import argparse
import getpass
import shutil
import glob
import initConfig # config.py generator
import authinfo
try:
import dns.resolver
DNS_RESOLVER = True
except:
DNS_RESOLVER = False
class Namespace:
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
# Set config parameters according to cmdline arguments
def setConfigParams(args):
if args.verbose:
config.VERBOSE = True
else:
config.VERBOSE = False
if args.debug:
config.DEBUG = True
if args.fqhn:
config.NOIP_HOSTNAME = args.fqhn
if args.hostName:
config.HOSTNAME = args.hostName
if args.userName:
config.ROUTER_USERNAME = args.userName
if args.password:
config.ROUTER_PASSWORD = args.password
# if not config.PASSWORD:
# password = getpass.getpass()
# if not password:
# myprint('Invalid empty password')
# sys.exit(1)
# config.PASSWORD = password
if args.logFile != None:
if args.logFile == '':
config.LOGFILE = "%s-debug.txt" % config.ROUTER_HOSTNAME
else:
config.LOGFILE = args.logFile
print('Using log file: %s' % config.LOGFILE)
try:
sys.stdout = open(config.LOGFILE, "w")
except:
print('Cannot create log file')
if args.ipaddrfile:
config.IPADDR_FILE = args.ipaddrfile
if config.VERBOSE:
print('TP-Link Archer Router Connection Parameters:')
print('Router Hostname/Address: %s' % config.ROUTER_HOSTNAME)
print('Router User Name: %s' % config.ROUTER_USERNAME)
print('Router User Password: %s' % masked(config.ROUTER_PASSWORD, 3))
# Leave the last 'l' characters of 'text' unmasked
def masked(text, l):
nl=-(l)
masked = text[nl:].rjust(len(text), "#")
return masked
def rebootRouter():
with requests.session() as session:
# Create instance of router at hostName, connect with given credentials
archer = tplas.Archer(config.ROUTER_HOSTNAME, config.ROUTER_USERNAME, config.ROUTER_PASSWORD, session)
# Reboot the router
archer.reboot()
#
# Get some router information
#
def dumpInformationFromRouter(args):
with requests.session() as session:
# Create instance of router at hostName, connect with given credentials
archer = tplas.Archer(config.ROUTER_HOSTNAME, config.ROUTER_USERNAME, config.ROUTER_PASSWORD, session)
# Read current configuration
archerConfig = archer.getConfig()
# Work done. Logout from router
archer.logout()
# Dump configuration
sd = sorted(archerConfig.items())
for k,v in sd:
print("{: <25}: {}".format(k,v))
modelName = archerConfig['modelName']
MACAddress = archerConfig['MACAddress']
ipv4 = archerConfig['ipv4']
bssid = archerConfig['BSSID'].split('; ')[0]
print('Router Host: %s, Model: %s, BSSID: %s, Public IPv4: %s' % (config.ROUTER_HOSTNAME, modelName, bssid, ipv4))
#print('BSSID: %s' % archerConfig['BSSID'])
# Get usage statistics
totalStatistics = int(float(archerConfig['totalStatistics']))
limitation = int(archerConfig['limitation'])
print('Usage: %s / %s' % (humanBytes(totalStatistics), humanBytes(limitation)))
if args.logFile and args.logFile != '':
sys.stdout.close()
#
# Get the public IP address assigned by ISP to the TPLink
# Archer router using Web Scrapping
#
def getIpAddressFromRouter(args):
with requests.session() as session:
# Create instance of router at hostName, connect with given credentials
archer = tplas.Archer(config.ROUTER_HOSTNAME, config.ROUTER_USERNAME, config.ROUTER_PASSWORD, session)
# Read current configuration
archerConfig = archer.getConfig()
# Work done. Logout from router
archer.logout()
ipv4 = archerConfig['ipv4']
if args.logFile and args.logFile != '':
sys.stdout.close()
return ipv4
#
# Update the DDNS Record at No-Ip with current IP address
#
def updateDDNSRecord(args):
if not args.hostname or not args.usertoken or not args.password:
print('%s: Unable to update DDNS record at No-IP. Missing credentials' % ME)
return -1
exe = sys.executable
cmd = "%s -m noipy.main --usertoken %s --password %s --provider %s --hostname %s %s" % \
(exe,
args.usertoken,
args.password,
args.provider,
args.hostname,
args.ip)
#print(cmd)
r = os.system(cmd)
return r
def humanBytes(size):
power = float(2**10) # 2**10 = 1024
n = 0
power_labels = {0 : 'B', 1: 'KB', 2: 'MB', 3: 'GB', 4: 'TB'}
while size > power:
size = float(size / power)
n += 1
return '%s %s' % (('%.2f' % size).rstrip('0').rstrip('.'), power_labels[n])
#
# Get router IP address from DNS
#
def resolveDNS(hostName):
#resolver = dns.resolver.Resolver();
#answer = resolver.query(hostName , "A")
answer = dns.resolver.Resolver().resolve(hostName , "A")
return answer
def getHostByName(hostName):
try:
ipAddress = socket.gethostbyname(hostName)
except:
ipAddress = '0.0.0.0'
print("Unknown host: %s" % hostName)
return ipAddress
####
def cleanLog(logDir):
dirs = list(filter(os.path.isdir, glob.glob(logDir + "16*")))
dirs.sort(key=lambda x: os.path.getmtime(x))
#print('Logs to clean:',dirs[:-1]) # Skip last/current log directory
for d in dirs[:-1]:
shutil.rmtree(d, ignore_errors=True)
print('Deleting:',d)
def module_path(local_function):
''' returns the module path without the use of __file__.
Requires a function defined locally in the module.
from http://stackoverflow.com/questions/729583/getting-file-path-of-imported-module'''
return os.path.abspath(inspect.getsourcefile(local_function))
class color:
PURPLE = '\033[95m'
CYAN = '\033[96m'
DARKCYAN = '\033[36m'
BLUE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
END = '\033[0m'
def myprint(*args, **kwargs):
"""My custom print() function."""
# Adding new arguments to the print function signature
# is probably a bad idea.
# Instead consider testing if custom argument keywords
# are present in kwargs
if config.DEBUG:
__builtin__.print('%s%s()%s:' % (color.BOLD, inspect.stack()[1][3], color.END), *args, **kwargs)
#__builtin__.print('%s():' % inspect.stack()[1][3], *args, **kwargs)
####
# Arguments parser
def parse_argv():
desc = 'Get TP-Link Archer router current configuration, as shown on the first page after login'
parser = argparse.ArgumentParser(description=desc)
parser.add_argument("-d", "--debug",
action="store_true",
dest="debug",
default=False,
help="print debug messages (to stdout)")
parser.add_argument('-f', '--logfile',
dest='logFile',
const='', #config.LOGFILE,
default=None,
action='store',
nargs='?',
metavar = 'FILE',
help="write debug messages to FILE (default to <hostname>-debug.txt)")
parser.add_argument('--fqhn',
dest='fqhn',
action='store',
#nargs='?',
help="TP-Link Archer router Fully Qualified HostName (default to %s)" % config.NOIP_HOSTNAME)
parser.add_argument('-r', '--router',
dest='hostName',
action='store',
#nargs='?',
help="TP-Link Archer router IP address/name (default to %s)" % config.ROUTER_HOSTNAME)
parser.add_argument('-u', '--user',
dest='userName',
required=False,
help="Username for login on Archer router (default = admin)")
parser.add_argument('-p', '--password',
dest='password',
required=False,
help="Password for login on Archer router")
parser.add_argument("--ipfile",
dest="ipaddrfile",
required=False,
help="Write IP address to file")
# Possible Actions
parser.add_argument("-c", "--clean",
action="store_true",
dest="cleanLogs",
default=False,
help="Clean old Logfiles and exit")
parser.add_argument("-i", "--information",
action="store_true",
dest="dumpInformation",
default=False,
help="Dump router information and exit")
parser.add_argument("-n", "--checkonly",
action="store_true",
dest="checkonly",
default=False,
help="Check if IP add needs update but don't do it")
parser.add_argument("-R", "--reboot",
action="store_true",
dest="reboot",
default=False,
help="Reboot the Archer router and exit")
parser.add_argument("-v", "--verbose",
action="store_true",
dest="verbose",
default=False,
help="Verbose mode")
parser.add_argument("-V", "--version",
action="store_true",
dest="version",
default=False,
help="Print version and exit")
args = parser.parse_args()
return args
####
def importModuleByPath(path):
name = os.path.splitext(os.path.basename(path))[0]
if sys.version_info[0] == 2:
import imp
return imp.load_source(name, path)
elif sys.version_info[:2] <= (3, 4):
from importlib.machinery import SourceFileLoader
return SourceFileLoader(name, path).load_module()
else:
import importlib.util
spec = importlib.util.spec_from_file_location(name, path)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod
#
# Import given module.
#
def importModule(moduleDirPath, moduleName, name):
modulePath = os.path.join(moduleDirPath, moduleName)
mod = importModuleByPath(modulePath)
globals()[name] = mod
####
def main():
ME = os.path.basename(sys.argv[0])
print('%s: Running at: %s' % (ME, time.strftime('%m/%d/%y %H:%M:%S', time.localtime())))
# Parse arguments
args = parse_argv()
if args.version:
print('%s: version 1.1' % ME)
sys.exit(0)
# Clean old logfiles
#if config.VERBOSE:
# print('%s: Cleaning logs in %s' % (ME, '/volume1/Logs/synoscheduler/3/'))
#cleanLog('/volume1/Logs/synoscheduler/3/')
if args.cleanLogs:
sys.exit(0)
noip_username, noip_password = authinfo.decodeKey(config.NOIP_AUTH.encode('utf-8'))
# If username / paswword have been provided on the command-line, use them
try:
a = getattr(config, 'NOIP_USERNAME')
except:
setattr(config, 'NOIP_USERNAME', noip_username)
try:
a = getattr(config, 'NOIP_PASSWORD')
except:
setattr(config, 'NOIP_PASSWORD', noip_password)
router_username, router_password = authinfo.decodeKey(config.ROUTER_AUTH.encode('utf-8'))
# If username / paswword have been provided on the command-line, use them
try:
a = getattr(config, 'ROUTER_USERNAME')
except:
setattr(config, 'ROUTER_USERNAME', router_username)
try:
a = getattr(config, 'ROUTER_PASSWORD')
except:
setattr(config, 'ROUTER_PASSWORD', router_password)
if not config.ROUTER_USERNAME or not config.ROUTER_PASSWORD:
print('%s: Missing mandatory fields (username and/or password)' % (ME))
sys.exit(1)
# Set config parameters from CLI args
setConfigParams(args)
if args.dumpInformation:
curTime = time.strftime('%m/%d/%y %H:%M:%S', time.localtime())
print('%s: Router Configuration (IP: %s)' % (curTime, config.ROUTER_HOSTNAME))
dumpInformationFromRouter(args)
sys.exit(0)
if args.reboot:
curTime = time.strftime('%m/%d/%y %H:%M:%S', time.localtime())
print('%s: Rebooting router (IP: %s)...' % (curTime, config.ROUTER_HOSTNAME))
rebootRouter()
sys.exit(0)
# No action specified. Check router public address and update it if out of date
# Get current IP address of router from DNS
if DNS_RESOLVER:
try:
rec = resolveDNS(config.NOIP_HOSTNAME)
except:
curTime = time.strftime('%m/%d/%y %H:%M:%S', time.localtime())
print('%s: No DNS Record for %s' % (curTime,config.NOIP_HOSTNAME))
dnsRecord = ''
else:
for item in rec:
dnsRecord = ','.join([str(item), ''])
dnsRecord = dnsRecord.rstrip(',')
dnsIpAddr = dnsRecord
#print('Current DDNS Record for %s: %s' % (config.NOIP_HOSTNAME, dnsIpAddr))
else:
dnsIpAddr = getHostByName(config.NOIP_HOSTNAME)
# Read IP address as assigned by ISP from router web interface
routerIpAddr = getIpAddressFromRouter(args)
if routerIpAddr == '':
curTime = time.strftime('%m/%d/%y %H:%M:%S', time.localtime())
print('%s: Unable to retrieve IPv4 address for router (IP: %s)' % (curTime, config.ROUTER_HOSTNAME))
print('Rebooting router')
rebootRouter()
sys.exit(1)
# Update file with IP address
wsi = config.IPADDR_FILE
try:
ipAddrFile = wsi if wsi else 'index.html'
if config.VERBOSE:
curTime = time.strftime('%m/%d/%y %H:%M:%S', time.localtime())
print('%s: Updating file: %s' % (curTime, ipAddrFile))
out = open(ipAddrFile, 'w')
out.write(routerIpAddr)
out.close()
except IOError as e:
msg = "I/O error: Creating %s: %s" % (ipAddrFile, "({0}): {1}".format(e.errno, e.strerror))
print(msg)
#sys.exit(1)
if args.checkonly:
curTime = time.strftime('%m/%d/%y %H:%M:%S', time.localtime())
msg = "{}: {} IP address of {} is: {}".format(curTime, 'DNS' if DNS_RESOLVER else 'Host', config.NOIP_HOSTNAME, dnsIpAddr)
print(msg)
print("{}: Public IP address (ISP) of {} is: {}".format(curTime, config.NOIP_HOSTNAME, routerIpAddr))
if routerIpAddr in dnsIpAddr:
print('%s: %sNo update is required.%s' % (curTime,color.RED,color.END))
else:
print('%s: %sSkipping update.%s' % (curTime, color.RED, color.END))
sys.exit(0)
# If uptodate, exit
if routerIpAddr in dnsIpAddr:
curTime = time.strftime('%m/%d/%y %H:%M:%S', time.localtime())
print('%s: IP Address: %s' % (curTime,routerIpAddr))
print('%s: %sNo update is required. Exiting%s' % (curTime,color.RED,color.END))
sys.exit(0)
# Create a namespace to pass arguments
noip_args = Namespace(config = '%s' % (os.path.expanduser("~")),
provider = 'noip',
hostname = '%s' % config.NOIP_HOSTNAME,
ip = '%s' % routerIpAddr,
usertoken= '%s' % config.NOIP_USERNAME,
password = '%s' % config.NOIP_PASSWORD,
store = False,
url = None)
r = updateDDNSRecord(noip_args)
if r:
print('%sFailed to update DDNS Record at No-Ip (%d)%s' % (color.RED,r,color.END))
sys.exit(1)
# Record change in log file
chLogFile = os.path.splitext(os.path.abspath(__file__))[0]+'.ipChangeLog'
#print(chLogFile)
with open(chLogFile, 'a') as logf:
curTime = time.strftime('%m/%d/%y %H:%M:%S', time.localtime())
msg = "{}: IP address updated. old: {} new: {}\n".format(curTime, dnsIpAddr, routerIpAddr)
logf.write(msg)
# Update host aliases
try:
noh = getattr(config, "config.NOIP_OTHER_HOSTS")
print(noh)
except:
noh = None
if noh:
otherHosts = noh.split(';')
for host in otherHosts:
curTime = time.strftime('%m/%d/%y %H:%M:%S', time.localtime())
print('%s: Updating host %s with IP %s' % (curTime,host,routerIpAddr))
noip_args = Namespace(config = '%s' % (os.path.expanduser("~")),
provider = 'noip',
hostname = '%s' % host,
ip = '%s' % routerIpAddr,
usertoken= '%s' % config.NOIP_USERNAME,
password = '%s' % config.NOIP_PASSWORD,
store = False,
url = None)
r = updateDDNSRecord(noip_args)
if r:
print('%sFailed to update DDNS Record at No-Ip (%d)%s' % (color.RED,r,color.END))
sys.exit(1)
# Entry point
if __name__ == "__main__":
# Absolute pathname of directory containing this module
moduleDirPath = os.path.dirname(module_path(main))
# Create config.py with Mandatory/Optional fields
mandatoryFields = [('b','VERBOSE'),
('b','DEBUG'),
('s','NOIP_HOSTNAME'),
('a',['NOIP_AUTH', ('s','NOIP_USERNAME'), ('p','NOIP_PASSWORD')]),
('s','ROUTER_HOSTNAME'),
('a',['ROUTER_AUTH', ('s','ROUTER_USERNAME'), ('p','ROUTER_PASSWORD')]),
]
optionalFields = [('s','IPADDR_FILE'),
('s','NOIP_OTHER_HOSTS'),
('s','LOGFILE'),
]
initConfig.initConfig(moduleDirPath, mandatoryFields, optionalFields)
# Import generated module
try:
import config
except:
print('config.py initialization has failed. Exiting')
sys.exit(1)
# config parameters updated. Import Archer module
importModule(moduleDirPath, 'archer.py', 'tplas')
main()