def network_ping(): ping = '\n====NETWORK PING====\n' whatsapp = 'WhatsApp: ' + str( int(pyspeedtest.SpeedTest('web.whatsapp.com').ping())) + 'ms\n' if kelas.cekSiap(): siap = 'System Akademik SIAP: ' + str( int(pyspeedtest.SpeedTest('siap.poltekpos.ac.id').ping())) + 'ms\n' else: siap = 'System Akademik SIAP: DOWN\n' message_ping = ping + whatsapp + siap return message_ping
def post(self): try: if request.args.get('url'): total_length = int( requests.head(request.args.get('url'), stream=True).headers.get('content-length')) size, name = file_size(total_length) st = pyspeedtest.SpeedTest() #bandwith_size,type=file_size(st.download()) estimated = download_time( size, name, 1, 'MB') # 1 MB will be the bandwidth of network. id = random.randrange(10000, 50000, 5) file_name = request.args.get('url').split('/')[-1] collection = get_database() collection.insert_one({ '_id': id, 'Total_file_size': str(size) + ' ' + name, 'Estimated_time_to_complete': estimated, 'Status': 'Downloading', 'FilE_name': file_name }) my_file = requests.get(request.args.get('url'), stream=True) open('/home/shravan/Downloads/' + file_name, 'wb').write(my_file.content) # Put download path collection = get_database() my_query = {"_id": id} new_values = {"$set": {"Status": 'Completed'}} collection.update_one(my_query, new_values) return id else: return "No URL found." except Exception as message: return message
def test_speed(self): # fast_response = requests.get('https://www.fast.com') # if fast_response.status_code != 200: # return self.response('Sorry, I could not connect to python speed test. Please try again'), False # soup = BeautifulSoup(fast_response) # speed_value = soup.find("div",attrs={"class":"speed-results-container","id":"speed-value"}).text # print(speed_value) # speed_unit = soup.find("div",attrs={"class":"speed-units-container","id":"speed-units"}).text # print(speed_unit) st = pyspeedtest.SpeedTest() ping = 'Your ping is: ' + str(st.ping()) + ' milliseconds' down = st.download() / 1000000 if down < 1: down = 'Your download speed is: ' + str( down * 1000) + ' kilobytes per second' else: down = str(down) + ' megabytes per second' up = st.upload() / 1000000 if up < 1: up = 'Your upload speed is: ' + str( up * 1000) + ' kilobytes per second' else: up = str(up) + ' megabytes per second' speed = Speed(ping, up, down) return self.response(speed), True
def loop_of_speed_tests(csvfile): csv_writer = csv.writer(csvfile) csv_writer.writerow(header) print("To end the program, simply close the Terminal window, or type Control + C. The data will be recorded in the Bandwidth_Stopwatch_data.csv in the same directory as this script.") while True: current_time = localtime() st = pyspeedtest.SpeedTest() try: download = st.download(), ping = st.ping(), upload = st.upload() except Exception as e: print(f'Exception encountered while attempting to record at {current_time} with message {e}') continue date_time = strftime("%Y-%m-%d %H:%M:%S", current_time) csv_writer.writerow([date_time, download, ping, upload]) csvfile.flush() print("Speed data recorded: " + strftime("%Y-%m-%d %H:%M:%S", current_time)) time.sleep(120) #two minute wait between pulls.
def speed_test(number_of_iterations=1, interval_minutes=0): print 'starting ' + str(number_of_iterations) + ' iterations at ' + str( interval_minutes) + ' minutes interval' st = pyspeedtest.SpeedTest() dnl_max = 0 dnl_min = 1000 upl_max = 0 upl_min = 1000 ping_max = 0 ping_min = 1000000 for iterations in range(number_of_iterations): ping_msec = st.ping() dnl_mega = st.download() / 1000000 upl_mega = st.upload() / 1000000 ping_min, ping_max = calc_min_max(ping_min, ping_max, ping_msec) dnl_min, dnl_max = calc_min_max(dnl_min, dnl_max, dnl_mega) upl_min, upl_max = calc_min_max(upl_min, upl_max, upl_mega) min_max_string = ' ping min ' + str(ping_min) + ' ping_max ' + str( ping_max) + ' dnl_min ' + str(dnl_min) + ' dnl_max ' + str( dnl_max) + ' upl_min ' + str(upl_min) + ' upl_max ' + str( upl_max) print iterations, 'ping msec ', ping_msec, 'dnl mega', dnl_mega, 'upl mega', upl_mega, min_max_string time.sleep(interval_minutes * 60)
async def speedtest(self, ctx): """Run a network speed test (owner only).""" channel = ctx.message.channel author = ctx.message.author server = ctx.message.guild # Only allow owner isOwner = self.settings.isOwner(ctx.author) if isOwner == None: msg = 'I have not been claimed, *yet*.' await ctx.channel.send(msg) return elif isOwner == False: msg = 'You are not the *true* owner of me. Only the rightful owner can use this command.' await ctx.channel.send(msg) return message = await channel.send('Running speed test...') st = pyspeedtest.SpeedTest() msg = '**Speed Test Results:**\n' msg += '```\n' msg += ' Ping: {}\n'.format(round(st.ping(), 2)) msg += 'Download: {}MB/s\n'.format(round(st.download()/1024/1024, 2)) msg += ' Upload: {}MB/s```'.format(round(st.upload()/1024/1024, 2)) await message.edit(content=msg)
def __init__(self, log_name='internet_speed.log', sleep_time=3): logging.basicConfig(filename=log_name, level=logging.INFO) self.db = MySQLDB.pi_mysql_db() self.sleep_time = sleep_time self.speed_test_api = pyspeedtest.SpeedTest() self.make_mysql_table() self.run_speed_test()
def speedy(site): pst = pyspeedtest.SpeedTest(site) print() nicePrint("Using site", site) nicePrint("Ping", pyspeedtest.pretty_speed(pst.ping())) nicePrint("Download", pyspeedtest.pretty_speed(pst.download())) print()
def main(): speed_test = pyspeedtest.SpeedTest() download = f"Download Speed: {str(speed_test.download())} Bytes/second" upload = f"Upload Speed: {str(speed_test.upload())} Bytes/second" ping = f"Ping: {str(speed_test.ping())}" print(f"------{download}\n{upload}\n{ping}------")
def networkstats(bot, update): printsenderonlcd(update) configParser = configparser.RawConfigParser() configFilePath = r'TelegramBot.config' configParser.read(configFilePath) st = pyspeedtest.SpeedTest(configParser.get('BOTCONFIG', 'speedtestUrl')) print('speedtest initialized') try: ping = "{0:.2f}".format(st.ping()) print(ping) except: ping = "error on ping" print("error ping") try: download = "{0:.2f}".format(st.download()) print(download) except: download = "error on download" print("error download") try: upload = "{0:.2f}".format(st.upload()) print(upload) except: upload = "error on upload" print("error upload") bot.send_message( chat_id, 'Ping={}DW={}UP={}'.format(uptime, ping, download, upload))
def get_latency(url, var): try: st = pyspeedtest.SpeedTest(url) val = "{:.2f} ms".format(st.ping()).encode() var.value = val except Exception as e: print(e)
def run(): print("Twitter init...") api = twitter.Api("y4zqS0roH2NiA153E9a3ai3Zn", "yOdBoQWJ1o58QOCRKuRy5510kdsTRwUiPYhusIsnnJVWAZjiSZ", "879429529508491264-YSiGGrH3ZqzAW1H9xWix7SM5eV5qP25", "eNDEbV88QAJSX3ZizQA5YbPmpOiZcqztg9JdZshdgRMhX") print("Running speed test..") st = pyspeedtest.SpeedTest() # Divide by a million as the values from pyspeedtest are in bytes (I think...) down_speed = st.download() / 1000000 up_speed = st.upload() / 1000000 if down_speed < 50 or up_speed < 3: print("Bad speeds, tweeting") message = "@bendbroadband I'm paying for 100down/5up, why is my speed " + str(round(down_speed, 2)) +\ "down/" + str(round(up_speed, 2)) + "up?" print(message) api.PostUpdate(message) else: print("Normal Speed found, message would be: ") print("@bendbroadband I'm paying for 100down/5up" ", why is my speed " + str(round(down_speed, 2)) + \ "down/" + str(round(up_speed, 2)) + "up?")
def main(): st = pst.SpeedTest() csv_file = os.path.join(os.path.dirname(__file__), "data", "metrics.csv") csv_writer = MetricWriterCSV(csv_file) json_file = os.path.join(os.path.dirname(__file__), "data", "metrics.json") json_writer = MetricWriterJSON(json_file) while True: try: ping = st.ping() upload = st.upload() download = st.download() except KeyboardInterrupt: sys.exit(0) except Exception: ping, upload, download = 0.0, 0.0, 0.0 is_online = False else: is_online = True metric = Metric(ping, upload, download, is_online) csv_writer.write(metric) json_writer.write(metric) print(metric)
def runSpeedTest(): speedTest = pyspeedtest.SpeedTest() try: downloadSpeed = float(round(speedTest.download() / 1048576, 2)) return downloadSpeed except: print 'Speed Test failed. Please check your internet connection' return None
def make_speedtest_object(): speed_tester = pyspeedtest.SpeedTest() # Yes, I know this is ultra-bad practice. I'm overriding the setting # without editing the source of pyspeedtest. speed_tester._host = FORCE_SERVER # pylint: disable=W0212 return speed_tester
def benchmarkGenerator(iterations): st = pyspeedtest.SpeedTest() benchmark = 0 for x in range(0, int(iterations)): benchmark += st.download() benchmark = benchmark / int(iterations) return benchmark
def __init__(self, args, collection, runs = 5): self.args = args self.now = datetime.now() self.runs = runs self.collection = collection self.speedTest = pyspeedtest.SpeedTest(runs=self.runs)
def runSpeedTest(self): st = pyspeedtest.SpeedTest() rundate = self.getDate() ping = st.ping() download = st.download() upload = st.upload() result = {'ping': ping, 'download': download, 'upload': upload} result.update(rundate) return (result)
def latency(): ''' this function will test latency >>> latency() {'latency': ... ''' st = pyspeedtest.SpeedTest() ping = st.ping() return {"latency": ping}
def test(): """ stackoverflow.com/questions/48289636 """ s = pyspeedtest.SpeedTest() res = {'download': 0.0, 'upload': 0.0, 'ping': 0.0} res['download'] = s.download() res['upload'] = s.upload() return res["download"], res["upload"]
def main(): """ Demonstration of pyspeedtest module :return: None """ st = pyspeedtest.SpeedTest(runs=5) print('st.ping:', st.ping(), 'ms') print('st.download:', st.download() / (1024 * 1024), 'Mbps') print('st.upload:', st.upload() / (1024 * 1024), 'Mbps')
def main(path): _path = Path(path) speed_test = pyspeedtest.SpeedTest() with _path.open('a') as f: f.write( str(speed_test.download()) + '\t' + str(speed_test.upload()) + '\t' + str(speed_test.ping()) + '\n' )
async def plot(self): st = pyspeedtest.SpeedTest() print('Drawing network...') print('----------------------------------------------------') start = time.time() responses = [] downloads = [] uploads = [] for ip in self.devices: ping = st.ping() download = st.download() upload = st.upload() if round(ping) > (int(self.average_ping)*1.5): responses.append('HIGH ' + str(round(ping)) + 'ms') else: responses.append('NORMAL ' + str(round(ping)) + 'ms') if round(download/1000000) < (int(self.average_download)*.75): downloads.append('LOW ' + str(round(download/1000000)) + 'Mbps') else: downloads.append('NORMAL ' + str(round(download/1000000)) + 'Mbps') if round(upload/1000000) < (int(self.average_upload)*.75): uploads.append('LOW ' + str(round(upload/1000000)) + 'Mbps') else: uploads.append('NORMAL ' + str(round(upload/1000000)) + 'Mbps') hostnames = [] p = 1 for ip in self.devices: if ip == '192.168.0.1': hostnames.append('Router') else: hostnames.append('Computer ' + str(p)) p += 1 x = [] y = [] for i in range(0, len(self.devices)): x.append(random.random()) y.append(random.random()) area = 20 plt.scatter(x, y, s=area, marker='o') plt.xticks([]) plt.yticks([]) plt.plot(x, y, '-o') for i, txt in enumerate(self.devices): txt = 'Device Name: ' + str(hostnames[i]) + '\n' +\ 'Device IP: ' + str(self.devices[i]) + '\n' + \ 'Ping: ' + str(responses[i]) + '\n' + \ 'Download: ' + str(downloads[i]) + '\n' + \ 'Upload: ' + str(uploads[i]) plt.annotate(txt, (x[i], y[i])) end = time.time() ptime = end - start print('Calculated average upload. Finished in {} seconds.'.format(ptime)) print('====================================================') return plt.show()
def do_speedtest(): start = datetime.datetime.utcnow() st = pyspeedtest.SpeedTest() host = st.host ping = st.ping() down = st.download() up = st.upload() end = datetime.datetime.utcnow() with database.session: SpeedtestRecording(start=start, end=end, host=host, ping=ping, down=down, up=up)
def download(): ''' this function will test the download speeds from the internet >>> download() {'download speed': ... ''' st = pyspeedtest.SpeedTest() dl = st.download() dl = ((dl / 1024) / 1024) return {'download speed': dl}
def upload(): ''' this function will test the upload speeds to the internet >>> upload() {'upload speed': ... ''' st = pyspeedtest.SpeedTest() ul = st.upload() ul = ((ul / 1024) / 1024) return {"upload speed": ul}
def getSpeedtest(self): try: # Speed Test st = pyspeedtest.SpeedTest() self.ping = pyspeedtest.pretty_speed(st.ping()) self.download = pyspeedtest.pretty_speed(st.download()) self.upload = pyspeedtest.pretty_speed(st.upload()) self.timeStamp() # Set Time stamp after Speed Tests if self.verbose: self.printSpeedTestData() except Exception as e: print("Speedtest Error:", e)
def test_speed(): """ Do a speedtest """ speedtest = pyspeedtest.SpeedTest() return { 'ping': speedtest.ping(), 'download': speedtest.download(), 'upload': speedtest.upload(), 'measure_dt': datetime.now() }
def Speed(self): st = pyspeedtest.SpeedTest() ping = st.ping() download = int(st.download()) / 1048576 upload = int(st.upload()) / 1048576 p = str(round(ping, 2)) + " ms" d = str(round(download, 2)) + " Mbps" u = str(round(upload, 2)) + " Mbps" self.ping_input.setText(p) self.download_input.setText(d) self.upload_input.setText(u)
def speed_test(): #Uses Speedtest.net servers print('Starting speed test') st = pyspeedtest.SpeedTest(host='quartz.hns.net:8080') #http://quartz.hns.net:8080/upload?nocache=4804d89e-6eb8-4149-b046-f31071c6fa96 #st.host(st,'http://quartz.hns.net:8080') ping = st.ping() #ms download_bps = st.download() download_mbps = download_bps * 10**-6 upload_bps = st.upload() upload_mbps = upload_bps * 10**-6 return [ping,download_bps,download_mbps,upload_bps,upload_mbps]