Unitymedia Speedtest mit Python

sia

gesperrt
Registriert
26 März 2015
Beiträge
5.926
Ort
FFM (NSFW)
Hi Leute,

Ich hab folgendes Script:
[src=python]#!/usr/bin/env python3
from splinter import Browser
from time import sleep
from urllib import parse

### global variables
answers = {}
answers['plz'] = '12345'
answers['provider'] = 'Unitymedia'
answers['providerId'] = '450'
answers['speed'] = '400 Mbit/s'
answers['speedVal'] = '400000'
answers['speedId'] = '53192'
answers['tarif'] = '2play FLY 400'
answers['tarifId'] = '53205'

### do not change anything below this line

browser = Browser('chrome')
browser.visit('https://breitbandmessung.de/test')

# click "start"
print('Clicking start…')
browser.find_by_css('.question-0 .button-blue-big-start').first.click()
# wait a bit while the JS animation plays
sleep(1)

# answer "Ja" to the question if you're using an Ethernet cable
print('Answering that we\'re using a LAN cable…')
browser.find_by_css('label[for="lan-ja"]').first.click()
browser.find_by_css('.question-5 .button-blue-big-forward').first.click()
sleep(1)

# answer "Ja" to the question whether you eliminated influence factors
print('Answering that we eliminated influence factors…')
browser.find_by_css('label[for="optimal-ja"]').first.click()
browser.find_by_css('.question-10 .button-blue-big-forward').first.click()
sleep(1)

# input Postleitzahl
print('Filling PLZ…')
browser.fill('plz', answers['plz'])
browser.find_by_css('.question-20 .button-blue-big-forward').first.click()
sleep(1)

#select provider (over ID)
print('Filling provider…')
browser.execute_script('$("#provider").val("'+answers['providerId']+'").trigger("chosen:updated");')
browser.find_by_css('.question-30 .button-blue-big-forward').first.click()
sleep(1)

# select speed (over ID)
print('Filling speed…')
browser.execute_script('$("#speed").val("'+answers['speedId']+'").trigger("chosen:updated");')
browser.find_by_css('.question-40 .button-blue-big-forward').first.click()
sleep(1)

# select tariff (over ID)
print('Filling tariff…')
browser.execute_script('$("#tarif").val("'+answers['tarifId']+'").trigger("chosen:updated");')
browser.find_by_css('.question-50 .button-blue-big-forward').first.click()
sleep(1)

# select "no limit" for download limits
print('Selecting "no limit"…')
browser.find_by_css('label[for="limit-nein"]').first.click()
browser.find_by_css('.question-120 .button-blue-big-forward').first.click()
sleep(1)

# start the test
print('Starting the test…')
browser.find_by_css('.question-60').find_by_text('5').first.click()
browser.find_by_css('.question-60 .button-blue-big-forward').first.click()
sleep(1)

# wait for completion
print('Waiting…')
if browser.is_text_present('Messung abgeschlossen', wait_time=70):
print('Measurement complete!')
sleep(5)

# print results
browser.execute_script('showdetails.click()')

results = {}
results['download'] = browser.evaluate_script('$(".results-download .results-val").text()')
results['upload'] = browser.evaluate_script('$(".results-upload .results-val").text()')
results['ping'] = browser.evaluate_script('$(".results-ping .results-val").text()')
results['id'] = browser.evaluate_script('$(".test-details .val-id").text()')

print(results)
[/src]

Und folgendes Pipfile:
[src=python][[source]]

url = "https://pypi.python.org/simple"
verify_ssl = true
name = "pypi"

[packages]
splinter = "*"[/src]

(Laufen lassen mit pipenv run python breitbandmessung.py3)

Würde das jetzt gerne so umschreiben, dass das Script nicht mehr wild irgendwelche Buttons klickt, sondern die vom Speedtest intern verwendeten Variablen und .click-Funktionen nutzt (wie bei "print results" schon getan). Allerdings komme ich nicht an die Variablen im Array internal dran… Ich checke allerdings auch nicht, wo genau sie die internen Variablen löschen, sonst könnte man diese Funktion ja überschreiben bzw. überladen.
 
  • Thread Starter Thread Starter
  • #3
Also mittlerweile haben sie den erneuert und es gibt eine , Inhalt:

[src=javascript]
var unitymedia = window.unitymedia || {};
unitymedia.speedtest = unitymedia.speedtest || {};
var currentSpeedtestId = currentSpeedtestId || null;
(function(a, h) {
var k = 10;
a.init_done = !1;
a.ipv6 = null;
a.retry = {
download: !1,
upload: !1
};
a.is_ios = /(iPhone|iPod|iPad)/i.test(navigator.userAgent);
a.max_bytes_ios = 209715200;
a.provider_download = 0;
a.provider_upload = 0;
a.provider_ping = 0;
a.remote_port = null;
a.id = null;
a.helper = {};
a.timeSection = null;
a.timeStart = null;
a.download_streams = {};
a.upload_streams = {};
a.upload_xhr = new XMLHttpRequest;
a.bytes_loaded = {};
a.bytes_loaded_last_section = 0;
a.bytes_loaded_push = 0;
a.trigger_pingtimeout = null;
a.data = "0";
a.result = {
download_raw: [],
upload_raw: [],
ping_raw: [],
overall_time: [],
overall_bytes: [],
download: 0,
upload: 0,
ping: 0,
jitter: 0
};
a.detectIE = function() {
var a = window.navigator.userAgent,
c = a.indexOf("MSIE ");
if (0 < c) return parseInt(a.substring(c + 5, a.indexOf(".", c)), 10);
if (0 < a.indexOf("Trident/")) return c = a.indexOf("rv:"), parseInt(a.substring(c + 3, a.indexOf(".", c)), 10);
c = a.indexOf("Edge/");
return 0 < c ? parseInt(a.substring(c + 5, a.indexOf(".", c)), 10) : 0
};
a.init = function() {
a.init_ipv6()
};
a.init_ipv6 = function() {
var b = a.config.checkurl.replace(/\.speedtest/g,
"v6.speedtest") + "/empty.txt";
h.ajax({
url: b,
error: function(b) {
a.ipv6 = !1;
a.init_rpd()
},
success: function(b) {
a.ipv6 = !0;
a.config.checkurl = a.config.checkurl.replace(/\.speedtest/g, "v6.speedtest");
a.init_sbc()
},
timeout: 2E3
})
};
a.init_sbc = function() {
h.ajax({
url: "/ajax/speedtest-init/",
contentType: "application/json",
dataType: "json",
data: {
port: a.remote_port
},
error: function(b) {
a.config.callback_error(20);
a.log("SBC-Init (Error): " + JSON.stringify(b));
a.track("init_sbc_error#" + currentSpeedtestId + "#Error: " + b)
},
success: function(b) {
0 < b.downstreamSpeed && 0 < b.upstreamSpeed && (a.provider_download = b.downstreamSpeed, a.provider_upload = b.upstreamSpeed);
currentSpeedtestId = b.speedtestId;
a.config.callback_progress("init", {
speedtest_id: b.speedtestId,
downstream_init: b.downstreamSpeed,
upstream_init: b.upstreamSpeed,
downstream_booked: b.downstreamBooked,
upstream_booked: b.upstreamBooked,
isp: b.isp,
clientIp: b.clientIp,
modemType: b.modemType
});
a.init_done = !0;
a.log("SBC-Init (Success): " + JSON.stringify(b));
a.track("init_sbc_success#" +
currentSpeedtestId + "#DownstreamSpeed: " + b.downstreamSpeed + ", UpstreamSpeed: " + b.upstreamSpeed + ", SpeedtestId: " + b.speedtestId + ", DownstreamBooked: " + b.downstreamBooked + ", UpstreamBooked: " + b.upstreamBooked + ", ISP: " + b.isp + ", ModemType: " + b.modemType)
},
timeout: 6E4
})
};
a.init_rpd = function() {
h.ajax({
url: "//rpd.speedtest.unitymedia.de/",
contentType: "application/json",
dataType: "json",
crossDomain: !0,
error: function(b) {
a.config.callback_error(20);
a.log("SBC-Init-Rpd (Error): " + JSON.stringify(b));
a.track("init_rpd_error#" +
currentSpeedtestId + "#Error: " + b)
},
success: function(b) {
a.remote_port = b.port;
a.init_sbc();
a.log("SBC-Init-Rpd (Success): " + JSON.stringify(b));
a.track("init_rpd_success#" + currentSpeedtestId + "#Port: " + b.port)
},
timeout: 5E3
})
};
a.run = function(b) {
switch (b) {
case "download":
a.startDownload();
break;
case "upload":
a.startUpload();
break;
case "ping":
a.startPing()
}
};
a.transferEnd = function(b) {
a.getSectionSpeed()
};
a.transferEndWS = function(b) {
a.getSectionSpeedWS();
a.stopUploadTestWS()
};
a.stopDownloadTest = function() {
a.stopHandler &&
window.clearTimeout(a.stopHandler);
a.stopHandler = null;
for (var b = 0; 6 > b; b++) a.download_streams.req.abort();
a.running = null;
a.helper.result_from_arr(a.result.download_raw, "download", a.provider_download, a.result.overall_time.download, a.result.overall_bytes.download)
};
a.stopUploadTest = function() {
a.stopHandler && window.clearTimeout(a.stopHandler);
a.stopHandler = null;
a.upload_xhr.abort();
a.running = null;
a.helper.result_from_arr(a.result.upload_raw, "upload", a.provider_upload, a.result.overall_time.upload, a.result.overall_bytes.upload)
};
a.stopUploadTestWS = function() {
a.stopHandler && window.clearTimeout(a.stopHandler);
a.stopHandler = null;
a.socket.disconnect();
a.running = null;
a.helper.result_from_arr(a.result.upload_raw, "upload", a.provider_upload, a.result.overall_time.upload, a.result.overall_bytes.upload)
};
a.stopPingTest = function() {
null != a.running && (a.running = null, a.result.overall_time.ping = (new Date).getTime() - a.timeStart.getTime(), a.helper.result_from_arr(a.result.ping_raw, "ping", a.provider_ping, a.result.overall_time.ping, null), h("#runarea").removeAttr("src"))
};
a.getBytesUntilNow = function() {
var b = 0;
if ("download" == a.running)
for (var c = 0; 6 > c; c++) b += a.bytes_loaded[c];
"upload" == a.running && (b = a.bytes_loaded[0] + a.bytes_loaded_push);
return b
};
a.getSectionSpeed = function() {
var b = a.getBytesUntilNow(),
c = new Date,
e = b - a.bytes_loaded_last_section,
f = c.getTime() - a.timeSection.getTime(),
g = c.getTime() - a.timeStart.getTime(),
d = Math.round(8 * e / f);
a.result.overall_time[a.running] = g;
a.result.overall_bytes[a.running] = b;
0 < e && 0 < f && (a.timeSection = c, a.bytes_loaded_last_section = b, 375 <
f && ("download" == a.running && (c = g / 10 / k, a.result.download_raw.push(d), a.config.callback_progress("download_im_result", d), a.is_ios && b > a.max_bytes_ios && (a.config.callback_progress("statusbar", 100), a.stopDownloadTest()), a.config.callback_progress("statusbar", c)), "upload" == a.running && (c = g / 10 / 10, a.result.upload_raw.push(d), a.config.callback_progress("upload_im_result", d), a.config.callback_progress("statusbar_reverse", c))))
};
a.getSectionSpeedWS = function() {
var b = a.getBytesUntilNow(),
c = a.timestamp_push,
e = b -
a.bytes_loaded_last_section,
f = c - a.timeSectionWS,
g = c - a.timeStartWS,
d = Math.round(8 * e / f);
a.result.overall_time[a.running] = g;
a.result.overall_bytes[a.running] = b;
0 < e && 0 < f && (a.timeSectionWS = c, a.bytes_loaded_last_section = b, 375 < f && "upload" == a.running && (b = g / 10 / 10, a.result.upload_raw.push(d), a.config.callback_progress("statusbar_reverse", b)))
};
a.log = function(a) {};
a.track = function(a) {};
a.startDownload = function() {
if (null == a.running) {
a.running = "download";
a.config.callback_progress("download_start");
for (var b =
a.bytes_loaded_last_section = 0; 6 > b; b++) a.bytes_loaded = 0, a.download_streams = {
url: a.config.checkurl + "/data.zero.bin.256M?" + Math.random(),
req: new XMLHttpRequest,
updateProgress: function(b) {
a.bytes_loaded[this.id] = b.loaded
}
}, a.download_streams.req.id = b, a.download_streams.req.open("GET", a.download_streams.url, !0), a.download_streams.req.onprogress = a.download_streams.updateProgress, a.download_streams.req.onload = a.transferEnd, a.download_streams.req.onerror = a.transferEnd, a.download_streams.req.onabort =
a.transferEnd, a.download_streams.req.responseType = "blob";
a.helper.interval(a.getSectionSpeed, 750, a.helper.intervalRoundTrips(k, 750));
"number" === typeof a.stopHandler && (a.log("resetting Timeout download"), window.clearTimeout(a.stopHandler), a.stopHandler = null);
a.stopHandler = window.setTimeout(a.stopDownloadTest, 1E3 * k);
a.timeStart = new Date;
a.timeSection = a.timeStart;
for (b = 0; 6 > b; b++) a.download_streams.req.send();
a.track("start_download#" + currentSpeedtestId + "#TimeStart: " + a.timeStart)
}
};
a.pushData =
function() {
var b = a.config.checkurl + "/empty.txt";
a.bytes_loaded_push = 0;
a.upload_xhr.open("POST", b, !0);
a.upload_xhr.onerror = a.transferEnd;
a.upload_xhr.onabort = a.transferEnd;
a.upload_xhr.onload = function() {
a.bytes_loaded[0] += a.bytes_loaded_push;
a.bytes_loaded_push = 0;
a.pushData()
};
a.upload_xhr.contentType = "application/octet-stream";
a.upload_xhr.responseType = "blob";
a.upload_xhr.upload.onprogress = function(b) {
a.bytes_loaded_push = b.loaded
};
a.upload_xhr.send(a.data)
};
a.pushDataWS = function() {
a.bytes_loaded_last_section =
0;
a.bytes_loaded[0] = 0;
a.bytes_loaded_push = 0;
a.timeStartWS = null;
a.socket = io(a.config.checkurl, {
secure: !0,
path: "/upload/socket.io"
}).connect();
var b = new SocketIOFileUpload(a.socket);
b.chunkSize = 262144;
b.addEventListener("complete", function(c) {
a.bytes_loaded[0] += a.bytes_loaded_push;
a.bytes_loaded_push = 0;
a.bytes_loaded_last_section = 0;
b.submitFiles([a.helper.generateFile()])
});
a.socket.addEventListener("error", a.transferEndWS);
a.socket.on("upload.start", function(b) {
null == a.timeStartWS && (a.timeStartWS =
b.start);
a.timeSectionWS = a.timeStartWS
});
a.socket.on("upload.progress", function(b) {
a.bytes_loaded_push = b.bytesProcessed;
a.timestamp_push = b.timeStamp
});
a.socket.on("upload.done", function(a) {});
b.submitFiles([a.helper.generateFile()])
};
a.startUpload = function() {
if (null == a.running) {
a.running = "upload";
a.data = "0";
for (var b = 0; 9999999 > b; b++) a.data += "0";
15 > a.detectIE() && (a.data += a.data);
a.config.callback_progress("upload_start");
a.bytes_loaded_last_section = 0;
a.bytes_loaded[0] = 0;
a.helper.interval(a.getSectionSpeed,
1E3, a.helper.intervalRoundTrips(10, 1E3));
"number" === typeof a.stopHandler && (a.log("resetting Timeout upload"), window.clearTimeout(a.stopHandler), a.stopHandler = null);
a.stopHandler = window.setTimeout(a.stopUploadTest, 1E4);
a.timeStart = new Date;
a.timeSection = a.timeStart;
a.pushData();
a.track("start_upload#" + currentSpeedtestId + "#TimeStart: " + a.timeStart)
}
};
a.startUploadWS = function() {
if (null == a.running) {
a.running = "upload";
a.data = "0";
for (var b = 0; 9999999 > b; b++) a.data += "0";
a.config.callback_progress("upload_start");
a.helper.interval(a.getSectionSpeedWS, 1E3, a.helper.intervalRoundTrips(10, 1E3));
"number" === typeof a.stopHandler && (a.log("resetting Timeout uploadWS"), window.clearTimeout(a.stopHandler), a.stopHandler = null);
a.stopHandler = window.setTimeout(a.transferEndWS, 1E4);
a.pushDataWS();
a.track("start_upload_ws#" + currentSpeedtestId + "#TimeStart: " + a.timeStart)
}
};
a.startPing = function() {
a.config.callback_progress("ping_start");
a.timeStart = new Date;
a.running = "ping";
h("#runarea").attr("src", a.config.pingurl + "/rtt/");
"number" === typeof a.stopHandler && (a.log("resetting Timeout ping"), window.clearTimeout(a.stopHandler), a.stopHandler = null);
a.stopHandler = window.setTimeout(a.stopPingTest, 8E3);
h(window).on("message", function(b) {
b = b.originalEvent.data; - 1 == b ? (window.clearTimeout(a.stopHandler), a.stopHandler = null, a.stopPingTest()) : (a.result.ping_raw.push(b), a.config.callback_progress("ping_im_result", b))
});
a.track("start_ping#" + currentSpeedtestId + "#TimeStart: " + a.timeStart)
};
a.check_error = function(b) {
a.status.running = 1;
a.config.callback_error(b)
};
a.helper.result_from_arr = function(b, c, e, f, g) {
h.ajax({
url: "/ajax/result/",
cache: !1,
dataType: "json",
method: "POST",
data: {
values: b,
type: c,
ref: e,
time: f,
bytes: g
},
success: function(b) {
switch (b.type) {
case "download":
a.result.download = b.value;
0 == parseInt(b.value, 10) ? 0 == a.retry.download ? (a.log("second download test"), a.retry.download = !0, k = 5, a.startDownload()) : a.config.callback_error(500) : (a.config.callback_progress("download_finished", a.result.download), window.setTimeout(function() {
a.run("upload")
},
500));
break;
case "upload":
a.result.upload = b.value;
a.config.callback_progress("upload_finished", a.result.upload);
window.setTimeout(function() {
a.run("ping")
}, 500);
break;
case "ping":
a.result.ping = b.value, a.result.jitter = b.jitter, a.config.callback_progress("ping_finished", a.result.ping), window.setTimeout(function() {
a.config.callback_progress("finished")
}, 500)
}
}
})
};
a.helper.median = function(b) {
b = b.sort(a.helper.sortNumber);
var c = b.length;
return 0 == c % 2 ? (c /= 2, (parseFloat(b[c - 1]) + parseFloat(b[c])) / 2) : b[(c -
1) / 2]
};
a.helper.sum_array = function(a) {
for (var b = 0, e = 0; e <= a.length - 1; e++) b += a[e];
return b
};
a.helper.sortNumber = function(a, c) {
return a - c
};
a.helper.f = function(b) {
return 0 == b ? 1 : 1 == b ? 1 : b * a.f(b - 1)
};
a.helper.generateFile = function() {
var b = Math.random(),
c = new File([a.data], "empty" + b + ".txt", {
type: "application/octet-stream"
});
a.log("file.name: empty." + b + ".txt, _$.data payload size: " + c.size);
return c
};
a.helper.interval = function(b, c, e) {
var f = function(c, d) {
return function() {
if ("undefined" === typeof d || 0 < d--) {
setTimeout(f,
c);
try {
b.call(null), a.log("interval: #" + d + " @" + new Date)
} catch (l) {
throw d = 0, l.toString();
}
}
}
}(c, e);
setTimeout(f, c)
};
a.helper.intervalRoundTrips = function(a, c) {
return Math.round(1E3 * a / c) + 1
};
a.helper.generateFile = function() {
var b = Math.random(),
c = new File([a.data], "empty" + b + ".txt", {
type: "application/octet-stream"
});
a.log("file.name: empty." + b + ".txt, _$.data payload size: " + c.size);
return c
};
a.helper.interval = function(b, c, e) {
var f = function(c, d) {
return function() {
if ("undefined" === typeof d || 0 < d--) {
setTimeout(f,
c);
try {
b.call(null), a.log("interval: #" + d + " @" + new Date)
} catch (l) {
throw d = 0, l.toString();
}
}
}
}(c, e);
setTimeout(f, c)
};
a.helper.intervalRoundTrips = function(a, c) {
return Math.round(1E3 * a / c) + 1
}
})(unitymedia.speedtest || {}, jQuery);[/src]

Diese lädt folgende Datei herunter:

Hinter dem Fragezeichen steht eine zufällige Nummer, vermutlich um Caching zu vermeiden. Wie setze ich das jetzt als Speedtest-CLI um?

EDIT: Schneller Speedtest mit Bash: [src=bash]curl https://speedtest-01v6.speedtest.unitymedia.de/data.zero.bin.256M -o /dev/null -w '%{speed_download}' | sed 's/,[0-9]*/\/1024\n/' | bc[/src]
Output ist die Durchschnittsgeschwindigkeit in KiB/s.
 
Zuletzt bearbeitet:
Was ich schon mal sagen kann, die Nummer ist "random", siehe hier:
[src=javascript]url: a.config.checkurl + "/data.zero.bin.256M?" + Math.random(),[/src]

Das heißt du kannst theoretisch irgend eine Zahl <= 1.0 nehmen - diese wird an [kw]a.config.checkurl/data.zero.bin.256M?[/kw] angefügt.

Was ist denn deine Frage, wie du das mit CURL oder wget realisieren kannst?
Naja, für den Download einfach die URL ansprechen.

Was nicht klar ist, was "a.config.checkurl" ist, das steht nicht in deinem Quelltext, aber anhand der URL und das "v6.speedtest" = IPV6 mit "replace" ersetzt wird in der URL:
IPV4:
[src=text]https://speedtest-01.speedtest.unitymedia.de/data.zero.bin.256M?[/src]

IPV6:
[src=txt]https://speedtest-01v6.speedtest.unitymedia.de/data.zero.bin.256M?[/src]

[src=javascript] var b = a.config.checkurl.replace(/\.speedtest/g, "v6.speedtest")[/src]

Also wird die [kw]a.config.checkurl[/kw] Basis so aussehen:
[src=text]https://speedtest-01.speedtest.unitymedia.de[/src]

Hier könnte "-01" der jeweilige Server sein.

Also am Ende so mit CURL:
[src=text]curl -o https://speedtest-01.speedtest.unitymedia.de/data.zero.bin.256M?0.1234567 > data.zero.bin.256M[/src]
 
Zuletzt bearbeitet:
  • Thread Starter Thread Starter
  • #5
Wäre halt cool, wenn ich ein Script schreiben könnte, was den Unitymedia-Speedtest nutzt und die Speedtest-ID und die anderen Werte ausgeben kann.

Dummerweise will Unitymedia von Speed-Problemen nämlich nie was wissen, wenn man nicht deren hauseigenen Speedtest nutzt.

Breitbandmessung.de bietet leider auch keine API an :/

info@breitbandmessung.de schrieb:
Die Bundesnetzagentur hat Kriterien zur Bestimmung einer nicht vertragskonformen Leistung bei Breitband-Festnetzanschlüssen im Download festgelegt. Die Kriterien können Sie der Mitteilung Nr. 485/2017 der Bundesnetzagentur entnehmen. Die Mitteilung ist unter dem folgenden Link abrufbar: www.bundesnetzagentur.de/breitbandgeschwindigkeiten.

die Bereitstellung einer API zur Nutzung der Breitbandmessung ist nicht in Planung. Für diesen Zweck wird die Breitbandmessung Desktop-App zur Verfügung gestellt, um die von der Bundesnetzagentur festgelegten Kriterien für einen Nutzer ein einfacher Form abbilden zu können.

Die installierbare Desktop-App befindet sich derzeit in der Entwicklung und soll in Kürze veröffentlicht werden. Mit der Desktop-App können Messkampagnen durchgeführt und Messprotokoll generiert werden.

Die Anwendung wird für Windows, MacOS und Linux bereitgestellt.
 
Just in diesem Moment sehe ich da kein Problem so etwas umzusetzen. Du willst das als Python Skript, oder Bash schreiben?

Was ich spontan sehe:
1) JSON kommt drin vor, muß also geschrieben/gelesen werden können
2) Dateien müssen generiert werden [kw]a.data[/kw] für den Upload
3) Curl mit Binding oder requests? (Und )
 
Zuletzt bearbeitet:
Hier jetzt Download und Upload in einem:

speedtest.py # (default) Download + Upload Tests
speedtest.py -u # Upload
speedtest.py -d # Download
speedtest.py -u -d # Upload + Download

[src=python]
#!/usr/bin/env python3
import sys
import random
import time
from os import path, remove

import pycurl


# Download size in MB, can be power of 8
dlSize = 256

# URI
baseURI = 'https://speedtest-01.speedtest.unitymedia.de'
baseURIipv6 = 'https://speedtest-01v6.speedtest.unitymedia.de'
baseDownload = '/data.zero.bin.' + str(dlSize) + 'M'

# ------------------------------------------------------------------------
random.seed(time.time())
randomComponent = random.random()

# ------------------------------------------------------------------------
def downloadSpeedTest():
global dlSize, blockSize
speedCollection = [0]
downloadURL = baseURI + baseDownload + '?' + str(randomComponent)
downloadData = []
downloadSize = dlSize * (1024 * 1024)
blockSize = 0
blockStepSize = downloadSize / 100

def writeLoop(data):
global blockSize
blockSize += len(data)
if blockSize >= blockStepSize:
print('.', end='', flush=True)
blockSize -= blockStepSize

downloadData.append(data)

def writeProgress(dlTotal, dlNow, ulTotal, ulNow):
if speedCollection[len(speedCollection) - 1] != dlNow:
speedCollection.append(dlNow)

print('Starting download of URI: \'%s\'\n' % downloadURL)
c = pycurl.Curl()
c.setopt(c.URL, downloadURL)
c.setopt(c.USERAGENT, 'curl')
c.setopt(c.VERBOSE, False)
c.setopt(c.USE_SSL, True)
c.setopt(c.ENCODING, 'utf-8')
c.setopt(c.WRITEFUNCTION, writeLoop)
c.setopt(c.PROGRESSFUNCTION, writeProgress)
c.setopt(c.NOPROGRESS, False)
c.perform()

dlName = path.basename(baseDownload)
dlSpeed = c.getinfo(c.SPEED_DOWNLOAD) / 1000.0 / 1000.0
dlSize = c.getinfo(c.SIZE_DOWNLOAD)
dlTime = c.getinfo(c.TOTAL_TIME)

speedCollection = speedCollection[1:]
speedCollection.reverse()
speedCollection = speedCollection[1:]

speedMin = speedCollection[0]
speedMax = speedCollection[0]
speedTotal = 0

for index, item in enumerate(speedCollection):
try:
speed = item - speedCollection[index + 1]
except:
break

if speed < speedMin:
speedMin = speed
if speed > speedMax:
speedMax = speed
speedTotal += speed

speedMin = speedMin / 1024.0
speedMax = speedMax / 1024.0
speedAverage = speedTotal / len(speedCollection)

print('\n\nFinished downloading \'%s\', %d bytes ( %.3f MB)\n\nAverage speed of %.3f MiB\n[MIN: %.3f KB ::: MAX: %.3f Kb ::: AVG: %.3f KB]\n\nMeasured in %d minutes and %d seconds (%.3f seconds total)\n\n' % (
dlName, dlSize, dlSize / 1024.0 / 1024.0, dlSpeed, speedMin, speedMax * 2.0, speedAverage, dlTime / 60, dlTime % 60.0, dlTime))

c.close()

# ------------------------------------------------------------------------

def uploadSpeedtest():
speedCollection = [0]
ulName = 'empty.txt'
uploadURI = baseURI + '/empty.txt'
uploadData = "0" * (10000000 * 2)

with open(ulName, 'w') as uploadFile:
uploadFile.write(uploadData)

ulSize = len(uploadData)

def readProgress(dlTotal, dlNow, ulTotal, ulNow):
if speedCollection[len(speedCollection) - 1] != ulNow:
speedCollection.append(ulNow)

print('Starting upload of URI: \'%s\'\n' % uploadURI)

c = pycurl.Curl()
c.setopt(c.URL, uploadURI)
c.setopt(c.USERAGENT, 'curl')
c.setopt(c.VERBOSE, False)
c.setopt(c.HTTPHEADER, ['Content-Type: application/octet-stream'])
c.setopt(c.UPLOAD, True)
c.setopt(c.USE_SSL, True)
c.setopt(c.READFUNCTION, open('empty.txt', 'rb').read)
c.setopt(c.PROGRESSFUNCTION, readProgress)
c.setopt(c.NOPROGRESS, False)
c.perform()

remove(ulName)

speedCollection = speedCollection[1:]
speedCollection.reverse()
speedCollection = speedCollection[1:]

speedMin = speedCollection[0]
speedMax = speedCollection[0]
speedTotal = 0

ulSpeed = c.getinfo(c.SPEED_UPLOAD) / 1000.0 / 1000.0
ulSize = c.getinfo(c.SIZE_UPLOAD)
ulTime = c.getinfo(c.TOTAL_TIME)

for index, item in enumerate(speedCollection):
try:
speed = item - speedCollection[index + 1]
except:
break

if speed < speedMin:
speedMin = speed
if speed > speedMax:
speedMax = speed

speedTotal += speed

speedMin = speedMin / 1024.0
speedMax = speedMax / 1024.0
speedAverage = speedTotal / len(speedCollection)

print('\n\nFinished uploading \'%s\', %d bytes ( %.3f MB)\n\nAverage speed of %.3f MiB\n[MIN: %.3f KB ::: MAX: %.3f Kb ::: AVG: %.3f KB]\n\nMeasured in %d minutes and %d seconds (%.3f seconds total)\n\n' % (
ulName, ulSize, ulSize / 1024.0 / 1024.0, ulSpeed, speedMin, speedMax * 2.0, speedAverage, ulTime / 60, ulTime % 60.0, ulTime))

c.close()

# ------------------------------------------------------------------------

if __name__ == "__main__":
if len(sys.argv) == 1:
downloadSpeedTest()
uploadSpeedtest()
else:
for option in sys.argv:
if option == '-d':
downloadSpeedTest()
elif option == '-u':
uploadSpeedtest()
[/src]

*edit: Download als Anhang - ".txt" einfach entfernen.
 

Anhänge

Zuletzt bearbeitet:
  • Thread Starter Thread Starter
  • #10
krasser Typ ey :D danke

wenn die das jetzt noch in ihrem System sehen… ich ruf mal bei der Hotline an wenn mir langweilig ist :D
 
Ich habe noch eine Version bei der der Provider/ISP ermittelt und angezeigt werden, einzig allein das "Post" zum Speichern funktioniert nicht, ich weiß nur nicht warum und weshalb. Vermutlich weil die ID dynamisch ermittelt wird, I dont know unfortunately. Aber von der API bekomme ich ein "OK" zurück. Nur wirds irgendwo anders hapern.
 

Anhänge

Zurück
Oben