Advertisement
Masoko

OpenVPN Stats HTML

Oct 2nd, 2016
388
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.76 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3.  
  4. import os, sys,subprocess,web, pickle,glob
  5.  
  6. web.config.debug = False
  7. urls = ('/', 'cputemp','/vpn', 'vpn')
  8. app = web.application(urls, globals(),autoreload=True)
  9.  
  10. STATUS = "/var/log/openvpn-status.log"
  11. fmt = "%(cn)-25s %(real)-15s %(sent)13s %(recv)13s %(since)25s"
  12.  
  13. db_folder = "db"
  14.  
  15. sizes = [  
  16.     (1<<50L, 'PB'),
  17.     (1<<40L, 'TB'),
  18.     (1<<30L, 'GB'),
  19.     (1<<20L, 'MB'),
  20.     (1<<10L, 'KB'),
  21.     (1,       'B')
  22. ]
  23.  
  24. headers = {  
  25.     'cn':    'Common Name',
  26.     'real':  'Real Address',
  27.     'sent':  'Download',
  28.     'recv':  'Upload',
  29.     'since': 'Connected Since'
  30. }
  31.    
  32.    
  33. headers_total = {  
  34.     'cn':    'Common Name',
  35.     'real':  'Real Address',
  36.     'sent':  'Download',
  37.     'recv':  'Upload',
  38.     'since': 'Last Online'
  39. }
  40.  
  41.  
  42. def byte2str(size):  
  43.     for f, suf in sizes:
  44.         if size >= f:
  45.             break
  46.  
  47.     return "%.2f %s" % (size / float(f), suf)
  48.  
  49. def getScriptPath(): #gets script directory
  50.     return os.path.dirname(os.path.realpath(sys.argv[0]))
  51.  
  52.  
  53. def print_current():
  54.     status_file = open(STATUS, 'r')  
  55.     stats = status_file.readlines()  
  56.     status_file.close()
  57.        
  58.     hosts = []
  59.  
  60.     for line in stats:  
  61.         cols = line.split(',')
  62.  
  63.         if len(cols) == 5 and not line.startswith('Common Name'):
  64.             host  = {}
  65.             host['cn']    = cols[0]
  66.             host['real']  = cols[1].split(':')[0]
  67.             host['recv']  = byte2str(int(cols[2]))
  68.             host['sent']  = byte2str(int(cols[3]))
  69.             host['since'] = cols[4].strip()
  70.             hosts.append(host)
  71.  
  72.     return fmt % headers + "<br/>" + "<br/>".join([fmt % h for h in hosts])  
  73.    
  74. def print_total():
  75. #   print "------- Total --------"
  76.     log_files = glob.glob(os.path.join(getScriptPath(), db_folder) + "/*.log")
  77.     stats = []
  78.  
  79.     for lf in log_files:
  80.        
  81.         old_host = pickle.load(open( lf, "rb" )) #read data from file
  82.         old_host[0]['recv'] += old_host[1]['recv']
  83.         old_host[0]['sent'] += old_host[1]['sent']
  84.         old_host[0]['recv']  = byte2str(old_host[0]['recv'])
  85.         old_host[0]['sent']  = byte2str(old_host[0]['sent'])
  86.         stats.append(old_host[0])
  87.    
  88.     return (fmt % headers_total + "<br/>" + "<br/>".join([fmt % s for s in stats])).replace(" ", "&nbsp;")
  89.  
  90.  
  91. # Return CPU temperature as a character string
  92. def getCPUtemperature():
  93.     s = subprocess.check_output(["/opt/vc/bin/vcgencmd","measure_temp"])
  94.     return s.split('=')[1][:-3]
  95.  
  96.  
  97. class cputemp:
  98.     def GET(self):
  99.         temp1=getCPUtemperature()
  100.         return "CPU temp "+str(temp1)
  101.        
  102. class vpn:
  103.     def GET(self):
  104.         stats = print_total().replace (" ", "&nbsp;")
  105.         cur_stats = print_current().replace (" ", "&nbsp;")
  106.         return "<BODY BGCOLOR='e5e5e5'> <div style='font-family:Courier,monospace;'> ------- Total --------<br/>" + stats +"<br/>------- Current --------<br/>"+ cur_stats+"</div></body>"
  107.                
  108. if __name__ == '__main__':
  109.     app.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement