Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import threading
- import warnings
- import requests
- import getpass
- import sys
- import re
- from time import sleep, gmtime, strftime
- from telnetlib import Telnet
- from os import system
- from weather import Weather, Unit
- # Some variables
- useDefaultIP = True
- timer = 5 # Time (in seconds) between each update, try not to spam yourself too much
- file_name = strftime("%d %b %Y", gmtime()) + ".csv"
- # Ignore some warning
- if not sys.warnoptions:
- import warnings
- warnings.simplefilter("ignore")
- # Init bullcrap
- print("Sagemcom Stats Retriever 1.0")
- print("BlackScout/bscout9956\n")
- print("----------------------------------------")
- # User details
- if useDefaultIP == True:
- hostname = "192.168.1.1"
- else:
- hostname = input("Provide your router's internal IP Address: ")
- username = input("Provide your router's access account username: ")
- password = getpass.getpass() #Not obfuscated
- # Backup CSV
- def csvBackup():
- print("Backup in progress...")
- with open('line_stats.csv', 'r') as bs: # Backup Source
- backup_content = bs.read()
- backup_filename = 'line_stats_backup_' + strftime("%H.%M.%S_UTC", gmtime()) + '.csv'
- with open(backup_filename, 'w+') as bf: # Backup File
- bf.write(backup_content)
- print("Backed up as:", backup_filename)
- # Stupid line break
- def lineBreak():
- print("----------------------------------------")
- # Write the CSV
- print("Do you wish to clean the last CSV generated?")
- if input("\nyes | no\n") == "yes":
- while True:
- try:
- with open(file_name, 'w+') as ls:
- ls.writelines(["Date", ";", "DS SNR", ";",
- "US SNR", ";", "DS PWR", ";",
- "US PWR", ";", "DS HEC", ";",
- "US HEC", ";", "DS OCD", ";",
- "US OCD", ";", "DS ATT", ";",
- "US ATT", ";", "DS ACT", ";",
- "US ACT", ";", "WTEMP", ";",
- "MEMTOTAL", ";", "MEMFREE", ";",
- "MEMCACHE\n"])
- break
- except PermissionError:
- print("ERROR: The file is currently being used by another process")
- if input("Do you wish to try again?\nyes | no: ") == "yes":
- print("\nRetrying...\n")
- else:
- break
- def csvWrite(line_params, param_count):
- timeVar = strftime("%d %b %Y %H:%M:%S", gmtime())
- listArg = [timeVar]
- for x in range(0, param_count):
- listArg.append(";")
- listArg.append(line_params[x])
- listArg.append("\n")
- try:
- with open(file_name, 'a') as ls:
- ls.writelines(listArg)
- print("File written successfully\n")
- except PermissionError:
- print("ERROR: The file is being used by another process.")
- print("!! SAVING FAILED !!\n")
- while True:
- try:
- print("IRL Data")
- lineBreak()
- # Time stuff
- currentTime = strftime("%H:%M:%S", gmtime())
- print("The time now is:", currentTime)
- # Weather Stuff for Correlation
- weather = Weather(unit=Unit.CELSIUS)
- try:
- lookup = weather.lookup_by_location('rio de janeiro')
- condition = lookup.condition
- print("The temperature outside is now:", condition.temp, "degrees Celsius\n")
- except requests.exceptions.ConnectionError:
- print("It was not possible to retrieve weather data right now...\n")
- print("Either the service is down or you have no connection to the Internet\n")
- lineBreak()
- tn = Telnet(hostname)
- tn.read_until(b"Login: ")
- tn.write(username.encode('ascii') + b"\n")
- if password:
- tn.read_until(b"Password: ")
- tn.write(password.encode('ascii') + b"\n")
- tn.write(b"adsl info --show\n")
- tn.write(b"sh\n") #Entering busybox
- tn.write(b"cat /proc/uptime\n")
- tn.write(b"cat /proc/meminfo\n")
- tn.write(b"exit\n") #Exiting busybox
- tn.write(b"exit\n") #Exiting Telnet
- line = str(tn.read_all().decode('ascii'))
- #print(line)
- #
- """
- if Stats != Showtime then
- do not parse downstream garbage
- or anything else that isnt possible to parse
- with adsl info show when it its not connected.
- endif
- """
- # Parse Status
- stat_parsed = re.findall(r"(\n)(Status)(:)(\s+)(\w+)", line)
- stat_parsed = list(stat_parsed[0]) #De-tuple
- status = stat_parsed[4]
- print("Status:", status)
- if status == "Showtime":
- # ------------ Parse the speeds -------------
- speeds_parse = re.finditer(r"(\s+)(\w+)(\s)(\w+)(\s)(=)(\s)(\d+)(\s)(Kbps)", line)
- speeds_list = [None]
- for m in speeds_parse:
- speeds_list += list(m.groups())
- while True:
- try:
- speeds_list.remove(" ")
- except:
- break
- # ------------ Downstream Speeds ------------
- ds_attainable = speeds_list[10]
- ds_actual = speeds_list[20]
- print("Attainable Downstream rate =", ds_attainable, "Kbps")
- print("Actual Downstream rate =", ds_actual, "Kbps")
- lineBreak()
- # ------------ Upstream Speeds ------------
- us_attainable = speeds_list[5]
- us_actual = speeds_list[15]
- print("Attainable Upstream rate =", us_attainable, "Kbps")
- print("Actual Upstream rate =", us_actual, "Kbps")
- lineBreak()
- # Parse and Print other stats
- print("Other Line Stats\n")
- # SNR
- snr_parsed = re.findall(r"(SNR)(\s+)(\(dB\))(:)(\s+)([+-]?\d*\.\d+)(?![-+0-9\.])(\s+)([+-]?\d*\.\d+)(?![-+0-9\.])", line) # Hell
- snr_parsed = list(snr_parsed[0]) # De-tuple
- snr_downstream = snr_parsed[5]
- snr_upstream = snr_parsed[7]
- print("SNR: Down:", snr_downstream + " dB", "|", "Up:", snr_upstream + " dB")
- # PWR
- pw_parsed = re.findall(r"(Pwr)(\(dBm\))(:)(\s+)([+-]?\d*\.\d+)(?![-+0-9\.])(\s+)([+-]?\d*\.\d+)(?![-+0-9\.])", line) # Hell
- pw_parsed = list(pw_parsed[0]) # De-tuple
- pw_downstream = pw_parsed[4]
- pw_upstream = pw_parsed[6]
- print("PWR: Down:", pw_downstream + " dB" , "|", "Up:", pw_upstream + " dB")
- # HEC Errors
- hec_parsed = re.findall(r"(HEC)(:)(\s+)(\d+)(\s+)(\d+)", line)
- hec_parsed = list(hec_parsed[0]) # De-tuple
- hec_downstream = hec_parsed[3]
- hec_upstream = hec_parsed[5]
- print("HEC Errors:", "Down:", hec_downstream, "|", "Up:", hec_upstream)
- # OCD Errors
- ocd_parsed = re.findall(r"(OCD)(:)(\s+)(\d+)(\s+)(\d+)", line)
- ocd_parsed = list(ocd_parsed[0]) # De-tuple
- ocd_downstream = ocd_parsed[3]
- ocd_upstream = ocd_parsed[5]
- print("OCD Errors:", "Down:", ocd_downstream, "|", "Up:", ocd_upstream)
- # Lines
- lineBreak()
- # Useless Information
- # Router Uptime (Not DSL Sync Uptime)
- uptime_parsed = re.findall(r"(cat)(\s+)(\/proc\/uptime)(\s+)([+-]?\d*\.\d+)(?![-+0-9\.])", line)
- uptime_parsed = list(uptime_parsed[0]) #De-tuple
- uptime_parsed = float(uptime_parsed[4])
- if float(uptime_parsed) >= 86400:
- uptime_days = str(int(uptime_parsed/86400)) if int(uptime_parsed/86400) < 10 else str(int(uptime_parsed/86400))
- print("Router's Uptime is:", "0" + uptime_days + ":" + strftime("%H:%M:%S", gmtime(uptime_parsed)))
- else:
- print("Router's Uptime is:", strftime("%H:%M:%S", gmtime(uptime_parsed)))
- lineBreak()
- # Memory Info
- 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)
- meminfo_parsed = list(meminfo_parsed[0])
- meminfo_total = meminfo_parsed[7]
- meminfo_free = meminfo_parsed[14]
- meminfo_cache = meminfo_parsed[28]
- print("MemTotal:", meminfo_total, "kB")
- print("MemFree:", meminfo_free, "kB")
- print("Cache:", meminfo_cache, "kB")
- # Lines
- lineBreak()
- # Update Interval
- sleep(timer)
- # Write to CSV
- print("Writing to file...\n")
- # Huge mess of parameters
- line_parameters = [snr_downstream, snr_upstream, pw_downstream,
- pw_upstream, hec_downstream, hec_upstream,
- ocd_downstream, ocd_upstream, ds_attainable,
- us_attainable, ds_actual, us_actual, condition.temp,
- meminfo_total, meminfo_free, meminfo_cache]
- csvWrite(line_parameters, len(line_parameters))
- except IndexError:
- print("IndexError - > Something Happened")
- #print(line)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement