def main(): parser = build_parser() options, _args = parser.parse_args() if not options.rrd: parser.error('rrd file is required') if not options.now: # sleep for a random number of seconds, up to thirty minutes # to ensure this is not at a predictable time every time random.seed() time.sleep(random.randint(1, 1800)) # capture stdout, so that we can parse the speedtest output # http://stackoverflow.com/a/22823751/3297734 old_stdout = sys.stdout sys.stdout = mystdout = StringIO() # tell speedtest that we want simple output sys.argv = ['prog', '--simple'] try: speedtest_cli.speedtest() results = mystdout.getvalue().splitlines() ping = float(results[0].split(' ')[1]) download = float(results[1].split(' ')[1]) upload = float(results[2].split(' ')[1]) except: ping = 'U' download = 'U' upload = 'U' # restore stdout sys.stdout = old_stdout data = "N:%f:%f:%f" % (ping, download, upload) subprocess.call(['/usr/bin/rrdupdate', str(options.rrd), data])
def executeTask(self, controller): print("------------------------------------------------------------") print "Name: "+self.NAME print self.DESCRIPTION print("------------------------------------------------------------") controller.sendToClient(str(self.ID)) try: controller.communication.setTimeout(600) print("Waiting for Client to finish the speedtest...") msg = controller.receiveFromClient() if msg == "error": raise Exception("Client error") else: self.CLIENTDOWN = msg print "Download speed on Client: " + self.CLIENTDOWN msg = controller.receiveFromClient() if msg == "error": raise Exception("Client error") else: self.CLIENTUP = msg print "Upload speed on Client: " + self.CLIENTUP if controller.communication.waitForFinished() == False: raise Exception("No 'Finished' response from Client") print "Getting Download, Upload speed on the Router.." print "This will take a few minutes" speedtest_cli.speedtest() self.SERVERDOWN = speedtest_cli.DOWNSPEED self.SERVERUP = speedtest_cli.UPSPEED if self.SERVERDOWN == None: controller.sendToClient("error") raise Exception("Unable to measure download speed on the Server") if self.SERVERUP == None: controller.sendToClient("error") raise Exception("Unable to measure upload speed on the Server") print "\nDownload speed on the Router: "+self.SERVERDOWN controller.sendToClient(self.SERVERDOWN) time.sleep(1) print "Upload speed on the Router: "+self.SERVERUP controller.sendToClient(self.SERVERUP) time.sleep(1) controller.communication.sendFinished() if controller.communication.waitForAck() == False: raise Exception("No 'Ack' response from Client") except Exception,e: print "[Speedtest Error] "+str(e) controller.sendToClient("error")
def runSpeedTestAndGetDownloadUpload(): """ run a speedtest using speedtest-cli, return upload and download results in Mbps """ result = speedtest_cli.speedtest(); return (result[1], result[0]) # [0] = up, [1] = down
def main(): HOST = "192.168.1.1" username = "******" username = str.encode(username) password = passwordContainer.password password = str.encode(password) tn = telnetlib.Telnet(HOST) tn.read_until(b"DD-WRT login:"******"\n") tn.read_until(b"Password:"******"\n") tn.read_until(b"root@DD-WRT:~# ", 1) tn.write(b"stopservice wshaper\n") tn.read_until(b"root@DD-WRT:~# ", 1) result = speedtest_cli.speedtest() download = str(int((result[0] * 1000) * .89)) decodedDownload = download download = str.encode(download) # Upload speed test appears to be bugged and rarely varies. So this will remain # static for my use case and is therefore unneeded. # upload = str(int((result[1] * 1000) * .89)) # decodedUpload = upload # upload = str.encode(upload) tn.read_until(b"root@DD-WRT:~# ", 1) tn.write(b"nvram set wshaper_downlink=" + download + b"\n") tn.read_until(b"root@DD-WRT:~# ", 1) # tn.write(b"nvram set wshaper_uplink=" + upload + b"\n") tn.read_until(b"root@DD-WRT:~# ", 1) tn.write(b"startservice wshaper\n") # Prints download and upload # print("\nQOS settings applied. \n download = " + decodedDownload + "\n upload = " + decodedUpload + "\n") # Prints only download print("\nQOS settings applied. \n download = " + decodedDownload + "\n")
def listen_write(T): from time import time, ctime, sleep from speedtest_cli import speedtest from Twitter import Twitter def mean(l): return float(sum(l)) / len(l) def write_to_log(m): f = open("log", "r") texto = f.read() f.close() f = open("log", "w") texto = texto + "%s" % m f.write(texto) f.close() # Twt = Twitter() data = [] unit = 1000000 print "Simulate for %.2f hours" % T current_T = time() start_T = time() mins_5, dia = 300, 86400 diff_update = 0 diff_tweet = 86400 speeds_down, speeds_up = [], [] while current_T - start_T <= T * 3600: if current_T - start_T >= diff_update: print "%.2f/%.2f hours to go" % (current_T / 3600.0 - start_T / 3600.0, T) try: down, up = speedtest() except: print "Connection error, restarting..." continue speeds_down.append(down) speeds_up.append(up) line = "%s;%.2f;%.2f\n" % (ctime(), down / unit, up / unit) write_to_log(line) # data.append('%s;%.2f;%.2f\n' % (ctime(),down/unit, up/unit)) current_T = time() diff_update += mins_5 # Update every 5 minutes else: sleep(30) current_T = time() if ( current_T - start_T >= diff_tweet and mean(speeds_down) / unit < ideal_down and mean(speeds_up) / unit < ideal_up ): msge = "%.2f Down y %.2f Up (avg diario) es menos de lo acordado o no? #VTR #ParenDeCagarme" % ( mean(speeds_down) / unit, mean(speeds_up) / unit, ) # Twt.tweet(msge) diff_tweet += dia current_T = time()
def main(): stathat = StatHat(STATHAT_KEY) payload = {"ezkey": STATHAT_KEY, "data": []} data = speedtest() stathat.value('Latency', data['latency']) stathat.value('Download', data['download']) stathat.value('Upload', data['upload']) print data
def listen_write(T): from time import time, ctime, sleep from speedtest_cli import speedtest from Twitter import Twitter def mean(l): return float(sum(l))/len(l) def write_to_log(m): f = open('log', 'r') texto = f.read() f.close() f = open('log','w') texto = texto + '%s' % m f.write(texto) f.close() # Twt = Twitter() data = [] unit = 1000000 print 'Simulate for %.2f hours' % T current_T = time() start_T = time() mins_5, dia = 300, 86400 diff_update = 0 diff_tweet = 86400 speeds_down, speeds_up = [], [] while current_T - start_T <= T*3600: if current_T - start_T >= diff_update: print '%.2f/%.2f hours to go' % (current_T/3600.-start_T/3600., T) try: down, up = speedtest() except: print 'Connection error, restarting...' continue speeds_down.append(down) speeds_up.append(up) line = '%s;%.2f;%.2f\n' % (ctime(),down/unit, up/unit) write_to_log(line) #data.append('%s;%.2f;%.2f\n' % (ctime(),down/unit, up/unit)) current_T = time() diff_update += mins_5 # Update every 5 minutes else: sleep(30) current_T = time() if current_T - start_T >= diff_tweet and mean(speeds_down)/unit < ideal_down and mean(speeds_up)/unit < ideal_up: msge = '%.2f Down y %.2f Up (avg diario) es menos de lo acordado o no? #VTR #ParenDeCagarme' % (mean(speeds_down)/unit, mean(speeds_up)/unit) # Twt.tweet(msge) diff_tweet += dia current_T = time()
def run_speedtest(): with Capturing() as output, Argv(['speedtest-cli', '--simple']): speedtest() return output
# Logging configuration logging_level = logging.DEBUG if args.debug else logging.INFO if not args.verbose: logging.basicConfig( level=logging_level, format='%(asctime)s %(levelname)s: %(message)s.', filename='./log/bandwidth-logger.log', ) else: logging.basicConfig(level=logging_level, format='%(asctime)s %(levelname)s: %(message)s.') logging.getLogger('requests').setLevel(logging.WARNING) verbose = True if args.verbose else False results = speedtest_cli.speedtest(server=TEST_SERVERS['movistar'], verbose=verbose) if args.post: config = SafeConfigParser() config.read('./bandwidth_logger.ini') api_url = config.get('server', 'api_url') api_token = config.get('server', 'api_token') device_id = config.get('device', 'device_id') device_url = '%s/devices/%s/' % (api_url, device_id) datastreams = literal_eval(config.get('device', 'datastreams')) api_hdrs = { 'Content-Type': 'application/json', 'Authorization': 'Token token="%s"' % api_token } datastream_ids = [ds['id'] for ds in datastreams] logging.debug("Results: {}".format(results))
import speedtest_cli speedtest_cli.speedtest()
import speedtest_cli as st from datetime import datetime import pandas as pd from collections import OrderedDict csv_location = 'E:\Code\\speedtest\speedtest_table.csv' current_date = datetime.now() dspeed, upspeed, ping, server_info = st.speedtest() raw_data = OrderedDict([('Date', [current_date]), ('Download speed', [dspeed]), ('Upload speed', [upspeed]), ('Ping', [ping]), ('Server', [server_info['sponsor']]), ('S latitude', [server_info['lat']]), ('S longitude', [server_info['lon']]), ('S id', [server_info['id']])]) columns = [k for k in raw_data.keys()] df = pd.DataFrame(data=raw_data, columns=columns) df.to_csv(csv_location, mode='a', ignore_index=True, header=False)
'''simple script for speedtest on remote linux machines''' # '''sudo pip3 install speedtest_cli''' import speedtest_cli as stc stc.speedtest()
#!/usr/bin/python import smtplib import os from datetime import datetime from email.mime.text import MIMEText import speedtest_cli as stc result = stc.speedtest() ping = result["ping"]["latency"] download = (result["download"] / 1000000) * 8 upload = (result["upload"] / 1000000) * 8 time = datetime.now() passpath = os.environ["HOME"] + "/path/to/email/password/text/file/" fp = open(passpath, 'r') # Create a text/plain message passw = fp.read() fp.close() stats = "%s\nPing:\n%s\nDownload:\n%s\nUpload:\n%s" % (time, ping, download, upload) msg = MIMEText(stats, 'plain') me = "the sender's email address" you = "the recipient's email address" ## The recipients email address will be their phone number ## and a specific domain, depending on the carrier: ## AT&T: [email protected] ## T-Mobile: [email protected]
def execute(self, controller, message): ''' Executing the speedtest on the client, then waiting for the server to complete the speedtest on the router. ''' self.RESULT = None print("------------------------------------------------------------") print "Name: "+self.NAME print self.DESCRIPTION print("------------------------------------------------------------") try: controller.communication.setTimeout(600) print "Getting Download, Upload speed on the Client.." print "This may take some time" controller.gui.sendToLog("Getting Download, Upload speed on the Client..") controller.gui.sendToLog("This may take some time") speedtest_cli.speedtest() self.CLIENTDOWN = speedtest_cli.DOWNSPEED self.CLIENTUP = speedtest_cli.UPSPEED if self.CLIENTDOWN == None: controller.sendMessageToServer("error") raise Exception("Unable to measure download speed on client.") if self.CLIENTUP == None: controller.sendMessageToServer("error") raise Exception("Unable to measure upload speed on client") print "\nDowndload speed: "+self.CLIENTDOWN controller.gui.sendToLog("Downdload speed on the Client: "+self.CLIENTDOWN) controller.sendMessageToServer(self.CLIENTDOWN) time.sleep(2) print "Upload speed: "+self.CLIENTUP controller.gui.sendToLog("Upload speed on the Client: "+self.CLIENTUP) controller.sendMessageToServer(self.CLIENTUP) controller.communication.sendFinished() controller.gui.sendToLog("Client finished.") print "Getting Download, Upload speed on the router.." print "This may take a few minutes" controller.gui.sendToLog("Getting Download, Upload speed on the router..") controller.gui.sendToLog("This may take a few minutes") msg = controller.receiveMessageFromServer() self.ROUTERDOWN = msg print "Download speed on the Router: " + self.ROUTERDOWN controller.gui.sendToLog("Download speed on the Router: " + self.ROUTERDOWN) msg = controller.receiveMessageFromServer() self.ROUTERUP = msg print "Upload speed on the Router: " + self.ROUTERUP controller.gui.sendToLog("Upload speed on the Router: " + self.ROUTERUP) if controller.communication.waitForFinished() == False: raise Exception("No 'Finished' response from Server") controller.communication.sendAck() controller.gui.sendToLog("Router finished.") text_result=(" Download speed on this Client: "+self.CLIENTDOWN+''' '''+" Upload speed on this Client: "+self.CLIENTUP+''' '''+" Download speed on the Router: "+self.ROUTERDOWN+''' '''+" Upload speed on the Router: "+self.ROUTERUP)+''' To get the best results make sure that you are connecting to the internet with a cable. Wireless solutions (Wi-Fi, 3G etc. may be negatively affect the results)''' except RuntimeError,e : print "[Speedtest error] "+str(e) controller.gui.sendToLog("[Speedtest error] "+str(e)) text_result = "An error occurred during the task: "+str(e)