diff adslstats.py @ 32:1af6865189ce

Update to work with Python 3.
author Daniel O'Connor <darius@dons.net.au>
date Sat, 14 Nov 2020 14:54:05 +1030
parents 39bf6dec0753
children 7d8bee5e3c80
line wrap: on
line diff
--- a/adslstats.py	Sat Nov 14 14:10:50 2020 +1030
+++ b/adslstats.py	Sat Nov 14 14:54:05 2020 +1030
@@ -33,7 +33,7 @@
 import base64
 import binascii
 import bs4
-import ConfigParser
+import configparser
 import json
 import mechanize
 import mysrp as srp
@@ -45,9 +45,10 @@
 import rrdtool
 import sys
 import time
-import urllib
+import urllib.request, urllib.parse, urllib.error
+from functools import reduce
 
-conf = ConfigParser.ConfigParser()
+conf = configparser.ConfigParser()
 conf.add_section('global')
 
 conflist = []
@@ -117,7 +118,7 @@
 
 def getstats():
     stats = DSLStats()
-    parser = ConfigParser.ConfigParser()
+    parser = configparser.ConfigParser()
     base = 'http://%s' % (args.name)
     br = mechanize.Browser()
     #br.set_debug_http(True)
@@ -147,13 +148,13 @@
     usr = srp.User(username, password, hash_alg = srp.SHA256, ng_type = srp.NG_2048)
     uname, A = usr.start_authentication()
 
-    req = mechanize.Request(base + '/authenticate', data = urllib.urlencode({'CSRFtoken' : token, 'I' : uname, 'A' : binascii.hexlify(A)}))
+    req = mechanize.Request(base + '/authenticate', data = urllib.parse.urlencode({'CSRFtoken' : token, 'I' : uname, 'A' : binascii.hexlify(A)}))
     r = br.open(req)
     j = json.decoder.JSONDecoder().decode(r.read())
     #print('Sent challenge, got ' + str(j))
 
     M = usr.process_challenge(binascii.unhexlify(j['s']), binascii.unhexlify(j['B']))
-    req = mechanize.Request(base + '/authenticate', data = urllib.urlencode({'CSRFtoken' : token, 'M' : binascii.hexlify(M)}))
+    req = mechanize.Request(base + '/authenticate', data = urllib.parse.urlencode({'CSRFtoken' : token, 'M' : binascii.hexlify(M)}))
     r = br.open(req)
     j = json.decoder.JSONDecoder().decode(r.read())
     #print('Got response ' + str(j))
@@ -174,10 +175,10 @@
     # Helper function to extract data
     def getvals(bs, text, mult = 1):
         subs = bs.findAll('label', text = text)[0].fetchNextSiblings()[0].strings
-        tmp = map(lambda s: float(s.split()[0]), subs)
-        return map(lambda s: s * mult, tmp)
+        tmp = [float(s.split()[0]) for s in subs]
+        return [s * mult for s in tmp]
 
-    if map(None, bs.findAll('label', text = 'DSL Status')[0].fetchNextSiblings()[0].strings)[0] == 'Up':
+    if list(bs.findAll('label', text = 'DSL Status')[0].fetchNextSiblings()[0].strings)[0] == 'Up':
         stats.linkup = True
     else:
         stats.linkup = False
@@ -188,19 +189,19 @@
     stats.nmup, stats.nmdown = getvals(bs, 'Noise Margin')
 
     # Line attenuation returns several values for each direction, parse specially and just take the first one
-    upattens, downattens = map(None, bs.findAll('label', text = 'Line Attenuation')[0].fetchNextSiblings()[0].strings)
+    upattens, downattens = list(bs.findAll('label', text = 'Line Attenuation')[0].fetchNextSiblings()[0].strings)
     stats.attenup = float(re.findall('([0-9.N/A]+)', upattens)[0])
     stats.attendown = float(re.findall('([0-9.N/A]+)', downattens)[0])
 
     # Convert something like '2days 17hours 28min 19sec' into seconds
-    uptime = re.findall('([0-9]+)', map(None, bs.findAll('label', text = 'DSL Uptime')[0].fetchNextSiblings()[0].strings)[0])
+    uptime = re.findall('([0-9]+)', list(bs.findAll('label', text = 'DSL Uptime')[0].fetchNextSiblings()[0].strings)[0])
     uptime.reverse() # End up with an array of seconds, minutes, hours, etc
     mults = [1, 60, 60 * 60, 24 * 60 * 60]
-    if len(uptime) > mults:
-        print('Too many uptime elements to work out')
+    if len(uptime) != len(mults):
+        print('Unexpected number of uptime elements (%s)' % str(uptime))
         stats.uptime = None
     else:
-        stats.uptime = reduce(lambda a, b: a + b, map(lambda a: int(a[0]) * a[1], zip(uptime, mults)))
+        stats.uptime = reduce(lambda a, b: a + b, [int(a[0]) * a[1] for a in zip(uptime, mults)])
 
     return True
 
@@ -407,23 +408,23 @@
         # Handle the wrapper passing us its $0 as our $1
         args.munin = args.munin.split('_')[-1]
         if args.munin not in ['signal', 'sync']:
-            print "Unknown data type ", args.munin
+            print("Unknown data type ", args.munin)
             sys.exit(1)
         if len(args.rest) > 0:
             if args.rest[0] == 'config':
                 if args.munin == 'signal':
-                    print '''graph_category adsl
+                    print('''graph_category adsl
 graph_title DSL Signal Quality
 graph_args --base 1000 -l 0
-graph_vlabel dB'''
+graph_vlabel dB''')
                     for n in names:
                         name = n.translate(None, ' ()').lower()
-                        print '''%s.label %s
+                        print('''%s.label %s
 %s.type GAUGE
 %s.max 100
-%s.min 0''' % (name, n, name, name, name)
+%s.min 0''' % (name, n, name, name, name))
                 elif args.munin == 'sync':
-                    print '''graph_category adsl
+                    print('''graph_category adsl
 graph_title DSL Sync Speed
 graph_args --base 1024 -l 0
 graph_vlabel kbit/sec
@@ -442,37 +443,37 @@
 downmax.label Down (max)
 downmax.type GAUGE
 downmax.max 150000
-downmax.min 0'''
+downmax.min 0''')
             sys.exit(0)
     if args.update or args.munin:
         stats = getdata()
         if args.verbose:
             if stats == None:
-                print "Modem is offline"
+                print("Modem is offline")
             else:
-                print stats
+                print(stats)
     if (args.update or args.munin != None) and stats != None:
         if args.update:
             try:
                 os.stat(rrdname)
-            except OSError, e:
+            except OSError as e:
                 if e.errno == 2:
-                    print "rrd not found, creating.."
+                    print("rrd not found, creating..")
                     makerrd(rrdname)
             updaterrd(rrdname, int(time.time()), stats)
         if args.munin != None:
             if args.munin == 'signal':
-                print '''noisemarginup.value %.1f
+                print('''noisemarginup.value %.1f
 noisemargindown.value %.1f
 attenuationup.value %.1f
-attenuationdown.value %.1f''' % (stats.nmup, stats.nmdown, stats.attenup, stats.attendown)
+attenuationdown.value %.1f''' % (stats.nmup, stats.nmdown, stats.attenup, stats.attendown))
             elif args.munin == 'sync':
                 s = '''up.value %.1f
 down.value %.1f\n''' % (stats.upstream, stats.downstream)
                 if hasattr(stats, 'upstreammax'):
                     s += '''upmax.value %.1f
 downmax.value %.1f''' % (stats.upstreammax, stats.downstreammax)
-                print s
+                print(s)
     if args.graph:
         gengraph()