Advertisement
Guest User

Sagemcom3

a guest
Sep 29th, 2018
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.35 KB | None | 0 0
  1. import threading
  2. import warnings
  3. import requests
  4. import getpass
  5. import sys
  6. import re
  7. from time import sleep, gmtime, strftime
  8. from telnetlib import Telnet
  9. from os import system
  10. from weather import Weather, Unit
  11.  
  12. # Some variables
  13.  
  14. useDefaultIP = True
  15. timer = 5 # Time (in seconds) between each update, try not to spam yourself too much
  16. file_name = strftime("%d %b %Y", gmtime()) + ".csv"
  17.  
  18. # Ignore some warning
  19.  
  20. if not sys.warnoptions:
  21.     import warnings
  22.     warnings.simplefilter("ignore")
  23.  
  24. # Init bullcrap
  25.  
  26. print("Sagemcom Stats Retriever 1.0")
  27. print("BlackScout/bscout9956\n")
  28. print("----------------------------------------")
  29.  
  30. # User details
  31.  
  32. if useDefaultIP == True:
  33.     hostname = "192.168.1.1"
  34. else:
  35.     hostname = input("Provide your router's internal IP Address: ")
  36.  
  37. username = input("Provide your router's access account username: ")
  38. password = getpass.getpass() #Not obfuscated
  39.  
  40. # Backup CSV
  41.  
  42. def csvBackup():
  43.     print("Backup in progress...")
  44.     with open('line_stats.csv', 'r') as bs: # Backup Source
  45.         backup_content = bs.read()
  46.     backup_filename = 'line_stats_backup_' + strftime("%H.%M.%S_UTC", gmtime()) + '.csv'
  47.     with open(backup_filename, 'w+') as bf: # Backup File
  48.         bf.write(backup_content)
  49.     print("Backed up as:", backup_filename)
  50.  
  51.  
  52. # Stupid line break
  53.  
  54. def lineBreak():
  55.     print("----------------------------------------")
  56.  
  57. # Write the CSV
  58.  
  59. print("Do you wish to clean the last CSV generated?")
  60.  
  61. if input("\nyes | no\n") == "yes":
  62.     while True:
  63.         try:
  64.             with open(file_name, 'w+') as ls:
  65.                 ls.writelines(["Date", ";", "DS SNR", ";",
  66.                                "US SNR", ";", "DS PWR", ";",
  67.                                "US PWR", ";", "DS HEC", ";",
  68.                                "US HEC", ";", "DS OCD", ";",
  69.                                "US OCD", ";", "DS ATT", ";",
  70.                                "US ATT", ";", "DS ACT", ";",
  71.                                "US ACT", ";", "WTEMP", ";",
  72.                                "MEMTOTAL", ";", "MEMFREE", ";",
  73.                                "MEMCACHE\n"])
  74.                 break
  75.         except PermissionError:
  76.             print("ERROR: The file is currently being used by another process")
  77.             if input("Do you wish to try again?\nyes | no: ") == "yes":
  78.                     print("\nRetrying...\n")
  79.             else:
  80.                 break
  81.  
  82. def csvWrite(line_params, param_count):
  83.     timeVar = strftime("%d %b %Y %H:%M:%S", gmtime())
  84.    
  85.     listArg = [timeVar]
  86.     for x in range(0, param_count):
  87.         listArg.append(";")
  88.         listArg.append(line_params[x])
  89.     listArg.append("\n")
  90.    
  91.     try:
  92.         with open(file_name, 'a') as ls:
  93.             ls.writelines(listArg)
  94.             print("File written successfully\n")
  95.     except PermissionError:
  96.         print("ERROR: The file is being used by another process.")
  97.         print("!! SAVING FAILED !!\n")
  98.        
  99.    
  100.  
  101. while True:
  102.     try:
  103.         print("IRL Data")
  104.         lineBreak()
  105.  
  106.         # Time stuff
  107.        
  108.         currentTime = strftime("%H:%M:%S", gmtime())
  109.         print("The time now is:", currentTime)
  110.        
  111.         # Weather Stuff for Correlation
  112.  
  113.         weather = Weather(unit=Unit.CELSIUS)
  114.         try:
  115.             lookup = weather.lookup_by_location('rio de janeiro')
  116.             condition = lookup.condition
  117.             print("The temperature outside is now:", condition.temp, "degrees Celsius\n")
  118.         except requests.exceptions.ConnectionError:
  119.             print("It was not possible to retrieve weather data right now...\n")
  120.             print("Either the service is down or you have no connection to the Internet\n")
  121.        
  122.         lineBreak()
  123.        
  124.         tn = Telnet(hostname)
  125.  
  126.         tn.read_until(b"Login: ")
  127.         tn.write(username.encode('ascii') + b"\n")
  128.         if password:
  129.             tn.read_until(b"Password: ")
  130.             tn.write(password.encode('ascii') + b"\n")
  131.  
  132.         tn.write(b"adsl info --show\n")
  133.         tn.write(b"sh\n") #Entering busybox
  134.         tn.write(b"cat /proc/uptime\n")
  135.         tn.write(b"cat /proc/meminfo\n")
  136.         tn.write(b"exit\n") #Exiting busybox
  137.         tn.write(b"exit\n") #Exiting Telnet
  138.  
  139.         line = str(tn.read_all().decode('ascii'))
  140.         #print(line)
  141.  
  142.         #
  143.         """
  144.        if Stats != Showtime then
  145.        do not parse downstream garbage
  146.        or anything else that isnt possible to parse
  147.        with adsl info show when it its not connected.
  148.        endif
  149.        """
  150.  
  151.         # Parse Status
  152.  
  153.         stat_parsed = re.findall(r"(\n)(Status)(:)(\s+)(\w+)", line)
  154.         stat_parsed = list(stat_parsed[0]) #De-tuple
  155.         status = stat_parsed[4]
  156.         print("Status:", status)
  157.  
  158.         if status == "Showtime":
  159.             # ------------ Parse the speeds -------------
  160.  
  161.             speeds_parse = re.finditer(r"(\s+)(\w+)(\s)(\w+)(\s)(=)(\s)(\d+)(\s)(Kbps)", line)
  162.             speeds_list = [None]
  163.             for m in speeds_parse:
  164.                 speeds_list += list(m.groups())
  165.             while True:
  166.                 try:
  167.                     speeds_list.remove(" ")
  168.                 except:
  169.                     break
  170.  
  171.             # ------------ Downstream Speeds ------------
  172.            
  173.             ds_attainable = speeds_list[10]
  174.             ds_actual = speeds_list[20]
  175.             print("Attainable Downstream rate =", ds_attainable, "Kbps")
  176.             print("Actual Downstream rate =", ds_actual, "Kbps")
  177.             lineBreak()
  178.  
  179.             # ------------ Upstream Speeds ------------
  180.  
  181.             us_attainable = speeds_list[5]
  182.             us_actual = speeds_list[15]
  183.             print("Attainable Upstream rate =", us_attainable, "Kbps")
  184.             print("Actual Upstream rate =", us_actual, "Kbps")
  185.             lineBreak()
  186.  
  187.             # Parse and Print other stats
  188.  
  189.             print("Other Line Stats\n")
  190.  
  191.             # SNR
  192.  
  193.             snr_parsed = re.findall(r"(SNR)(\s+)(\(dB\))(:)(\s+)([+-]?\d*\.\d+)(?![-+0-9\.])(\s+)([+-]?\d*\.\d+)(?![-+0-9\.])", line) # Hell
  194.             snr_parsed = list(snr_parsed[0]) # De-tuple
  195.             snr_downstream = snr_parsed[5]
  196.             snr_upstream = snr_parsed[7]
  197.             print("SNR: Down:", snr_downstream + " dB", "|", "Up:", snr_upstream + " dB")
  198.  
  199.             # PWR
  200.            
  201.             pw_parsed = re.findall(r"(Pwr)(\(dBm\))(:)(\s+)([+-]?\d*\.\d+)(?![-+0-9\.])(\s+)([+-]?\d*\.\d+)(?![-+0-9\.])", line) # Hell
  202.             pw_parsed = list(pw_parsed[0]) # De-tuple
  203.             pw_downstream = pw_parsed[4]
  204.             pw_upstream = pw_parsed[6]
  205.             print("PWR: Down:", pw_downstream + " dB" , "|", "Up:", pw_upstream + " dB")
  206.  
  207.             # HEC Errors
  208.  
  209.             hec_parsed = re.findall(r"(HEC)(:)(\s+)(\d+)(\s+)(\d+)", line)
  210.             hec_parsed = list(hec_parsed[0]) # De-tuple
  211.             hec_downstream = hec_parsed[3]
  212.             hec_upstream = hec_parsed[5]
  213.             print("HEC Errors:", "Down:", hec_downstream, "|", "Up:", hec_upstream)
  214.  
  215.             # OCD Errors
  216.  
  217.             ocd_parsed = re.findall(r"(OCD)(:)(\s+)(\d+)(\s+)(\d+)", line)
  218.             ocd_parsed = list(ocd_parsed[0]) # De-tuple
  219.             ocd_downstream = ocd_parsed[3]
  220.             ocd_upstream = ocd_parsed[5]
  221.             print("OCD Errors:", "Down:", ocd_downstream, "|", "Up:", ocd_upstream)
  222.        
  223.         # Lines
  224.  
  225.         lineBreak()
  226.  
  227.         # Useless Information
  228.  
  229.         # Router Uptime (Not DSL Sync Uptime)
  230.  
  231.         uptime_parsed = re.findall(r"(cat)(\s+)(\/proc\/uptime)(\s+)([+-]?\d*\.\d+)(?![-+0-9\.])", line)
  232.         uptime_parsed = list(uptime_parsed[0]) #De-tuple
  233.         uptime_parsed = float(uptime_parsed[4])
  234.         if float(uptime_parsed) >= 86400:
  235.             uptime_days = str(int(uptime_parsed/86400)) if int(uptime_parsed/86400) < 10 else str(int(uptime_parsed/86400))
  236.             print("Router's Uptime is:", "0" + uptime_days + ":" + strftime("%H:%M:%S", gmtime(uptime_parsed)))
  237.         else:
  238.             print("Router's Uptime is:", strftime("%H:%M:%S", gmtime(uptime_parsed)))
  239.         lineBreak()
  240.  
  241.         # Memory Info
  242.  
  243.         meminfo_parsed = re.findall(r"(cat)(\s+)(\/proc\/meminfo)(\s+)(MemTotal)(:)(\s+)(\d+)(\s+)(kB)(\s+)(MemFree)(:)(\s+)(\d+)(\s+)(kB)(\s+)(Buffers)(:)(\s+)(\d+)(\s+)(kB)(\s+)(Cached)(:)(\s+)(\d+)(\s+)(kB)",line)
  244.         meminfo_parsed = list(meminfo_parsed[0])
  245.         meminfo_total = meminfo_parsed[7]
  246.         meminfo_free = meminfo_parsed[14]
  247.         meminfo_cache = meminfo_parsed[28]
  248.         print("MemTotal:", meminfo_total, "kB")
  249.         print("MemFree:", meminfo_free, "kB")
  250.         print("Cache:", meminfo_cache, "kB")
  251.  
  252.         # Lines
  253.        
  254.         lineBreak()
  255.  
  256.         # Update Interval
  257.        
  258.         sleep(timer)
  259.  
  260.         # Write to CSV
  261.  
  262.         print("Writing to file...\n")
  263.         # Huge mess of parameters
  264.         line_parameters = [snr_downstream, snr_upstream, pw_downstream,
  265.                            pw_upstream, hec_downstream, hec_upstream,
  266.                            ocd_downstream, ocd_upstream, ds_attainable,
  267.                            us_attainable, ds_actual, us_actual, condition.temp,
  268.                            meminfo_total, meminfo_free, meminfo_cache]
  269.        
  270.         csvWrite(line_parameters, len(line_parameters))
  271.     except IndexError:
  272.         print("IndexError - > Something Happened")
  273.         #print(line)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement