2
0

speedtest-cli 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Copyright 2013 Matt Martz
  4. # All Rights Reserved.
  5. #
  6. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  7. # not use this file except in compliance with the License. You may obtain
  8. # a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  14. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  15. # License for the specific language governing permissions and limitations
  16. # under the License.
  17. __version__ = '0.2.4'
  18. # Some global variables we use
  19. source = None
  20. shutdown_event = None
  21. import math
  22. import time
  23. import os
  24. import sys
  25. import threading
  26. import re
  27. import signal
  28. import socket
  29. # Used for bound_interface
  30. socket_socket = socket.socket
  31. try:
  32. import xml.etree.cElementTree as ET
  33. except ImportError:
  34. try:
  35. import xml.etree.ElementTree as ET
  36. except ImportError:
  37. from xml.dom import minidom as DOM
  38. ET = None
  39. # Begin import game to handle Python 2 and Python 3
  40. try:
  41. from urllib2 import urlopen, Request, HTTPError, URLError
  42. except ImportError:
  43. from urllib.request import urlopen, Request, HTTPError, URLError
  44. try:
  45. from Queue import Queue
  46. except ImportError:
  47. from queue import Queue
  48. try:
  49. from urlparse import urlparse
  50. except ImportError:
  51. from urllib.parse import urlparse
  52. try:
  53. from urlparse import parse_qs
  54. except ImportError:
  55. try:
  56. from urllib.parse import parse_qs
  57. except ImportError:
  58. from cgi import parse_qs
  59. try:
  60. from hashlib import md5
  61. except ImportError:
  62. from md5 import md5
  63. try:
  64. from argparse import ArgumentParser as ArgParser
  65. except ImportError:
  66. from optparse import OptionParser as ArgParser
  67. try:
  68. import builtins
  69. except ImportError:
  70. def print_(*args, **kwargs):
  71. """The new-style print function taken from
  72. https://pypi.python.org/pypi/six/
  73. """
  74. fp = kwargs.pop("file", sys.stdout)
  75. if fp is None:
  76. return
  77. def write(data):
  78. if not isinstance(data, basestring):
  79. data = str(data)
  80. fp.write(data)
  81. want_unicode = False
  82. sep = kwargs.pop("sep", None)
  83. if sep is not None:
  84. if isinstance(sep, unicode):
  85. want_unicode = True
  86. elif not isinstance(sep, str):
  87. raise TypeError("sep must be None or a string")
  88. end = kwargs.pop("end", None)
  89. if end is not None:
  90. if isinstance(end, unicode):
  91. want_unicode = True
  92. elif not isinstance(end, str):
  93. raise TypeError("end must be None or a string")
  94. if kwargs:
  95. raise TypeError("invalid keyword arguments to print()")
  96. if not want_unicode:
  97. for arg in args:
  98. if isinstance(arg, unicode):
  99. want_unicode = True
  100. break
  101. if want_unicode:
  102. newline = unicode("\n")
  103. space = unicode(" ")
  104. else:
  105. newline = "\n"
  106. space = " "
  107. if sep is None:
  108. sep = space
  109. if end is None:
  110. end = newline
  111. for i, arg in enumerate(args):
  112. if i:
  113. write(sep)
  114. write(arg)
  115. write(end)
  116. else:
  117. print_ = getattr(builtins, 'print')
  118. del builtins
  119. def bound_socket(*args, **kwargs):
  120. """Bind socket to a specified source IP address"""
  121. global source
  122. sock = socket_socket(*args, **kwargs)
  123. sock.bind((source, 0))
  124. return sock
  125. def distance(origin, destination):
  126. """Determine distance between 2 sets of [lat,lon] in km"""
  127. lat1, lon1 = origin
  128. lat2, lon2 = destination
  129. radius = 6371 # km
  130. dlat = math.radians(lat2 - lat1)
  131. dlon = math.radians(lon2 - lon1)
  132. a = (math.sin(dlat / 2) * math.sin(dlat / 2) + math.cos(math.radians(lat1))
  133. * math.cos(math.radians(lat2)) * math.sin(dlon / 2)
  134. * math.sin(dlon / 2))
  135. c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
  136. d = radius * c
  137. return d
  138. class FileGetter(threading.Thread):
  139. """Thread class for retrieving a URL"""
  140. def __init__(self, url, start):
  141. self.url = url
  142. self.result = None
  143. self.starttime = start
  144. threading.Thread.__init__(self)
  145. def run(self):
  146. self.result = [0]
  147. try:
  148. if (time.time() - self.starttime) <= 10:
  149. f = urlopen(self.url)
  150. while 1 and not shutdown_event.isSet():
  151. self.result.append(len(f.read(10240)))
  152. if self.result[-1] == 0:
  153. break
  154. f.close()
  155. except IOError:
  156. pass
  157. def downloadSpeed(files, quiet=False):
  158. """Function to launch FileGetter threads and calculate download speeds"""
  159. start = time.time()
  160. def producer(q, files):
  161. for file in files:
  162. thread = FileGetter(file, start)
  163. thread.start()
  164. q.put(thread, True)
  165. if not quiet and not shutdown_event.isSet():
  166. sys.stdout.write('.')
  167. sys.stdout.flush()
  168. finished = []
  169. def consumer(q, total_files):
  170. while len(finished) < total_files:
  171. thread = q.get(True)
  172. while thread.isAlive():
  173. thread.join(timeout=0.1)
  174. finished.append(sum(thread.result))
  175. del thread
  176. q = Queue(6)
  177. prod_thread = threading.Thread(target=producer, args=(q, files))
  178. cons_thread = threading.Thread(target=consumer, args=(q, len(files)))
  179. start = time.time()
  180. prod_thread.start()
  181. cons_thread.start()
  182. while prod_thread.isAlive():
  183. prod_thread.join(timeout=0.1)
  184. while cons_thread.isAlive():
  185. cons_thread.join(timeout=0.1)
  186. return (sum(finished) / (time.time() - start))
  187. class FilePutter(threading.Thread):
  188. """Thread class for putting a URL"""
  189. def __init__(self, url, start, size):
  190. self.url = url
  191. chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  192. data = chars * (int(round(int(size) / 36.0)))
  193. self.data = ('content1=%s' % data[0:int(size) - 9]).encode()
  194. del data
  195. self.result = None
  196. self.starttime = start
  197. threading.Thread.__init__(self)
  198. def run(self):
  199. try:
  200. if ((time.time() - self.starttime) <= 10 and
  201. not shutdown_event.isSet()):
  202. f = urlopen(self.url, self.data)
  203. f.read(11)
  204. f.close()
  205. self.result = len(self.data)
  206. else:
  207. self.result = 0
  208. except IOError:
  209. self.result = 0
  210. def uploadSpeed(url, sizes, quiet=False):
  211. """Function to launch FilePutter threads and calculate upload speeds"""
  212. start = time.time()
  213. def producer(q, sizes):
  214. for size in sizes:
  215. thread = FilePutter(url, start, size)
  216. thread.start()
  217. q.put(thread, True)
  218. if not quiet and not shutdown_event.isSet():
  219. sys.stdout.write('.')
  220. sys.stdout.flush()
  221. finished = []
  222. def consumer(q, total_sizes):
  223. while len(finished) < total_sizes:
  224. thread = q.get(True)
  225. while thread.isAlive():
  226. thread.join(timeout=0.1)
  227. finished.append(thread.result)
  228. del thread
  229. q = Queue(6)
  230. prod_thread = threading.Thread(target=producer, args=(q, sizes))
  231. cons_thread = threading.Thread(target=consumer, args=(q, len(sizes)))
  232. start = time.time()
  233. prod_thread.start()
  234. cons_thread.start()
  235. while prod_thread.isAlive():
  236. prod_thread.join(timeout=0.1)
  237. while cons_thread.isAlive():
  238. cons_thread.join(timeout=0.1)
  239. return (sum(finished) / (time.time() - start))
  240. def getAttributesByTagName(dom, tagName):
  241. """Retrieve an attribute from an XML document and return it in a
  242. consistent format
  243. Only used with xml.dom.minidom, which is likely only to be used
  244. with python versions older than 2.5
  245. """
  246. elem = dom.getElementsByTagName(tagName)[0]
  247. return dict(list(elem.attributes.items()))
  248. def getConfig():
  249. """Download the speedtest.net configuration and return only the data
  250. we are interested in
  251. """
  252. uh = urlopen('http://www.speedtest.net/speedtest-config.php')
  253. configxml = []
  254. while 1:
  255. configxml.append(uh.read(10240))
  256. if len(configxml[-1]) == 0:
  257. break
  258. if int(uh.code) != 200:
  259. return None
  260. uh.close()
  261. try:
  262. root = ET.fromstring(''.encode().join(configxml))
  263. config = {
  264. 'client': root.find('client').attrib,
  265. 'times': root.find('times').attrib,
  266. 'download': root.find('download').attrib,
  267. 'upload': root.find('upload').attrib}
  268. except AttributeError:
  269. root = DOM.parseString(''.join(configxml))
  270. config = {
  271. 'client': getAttributesByTagName(root, 'client'),
  272. 'times': getAttributesByTagName(root, 'times'),
  273. 'download': getAttributesByTagName(root, 'download'),
  274. 'upload': getAttributesByTagName(root, 'upload')}
  275. del root
  276. del configxml
  277. return config
  278. def closestServers(client, all=False):
  279. """Determine the 5 closest speedtest.net servers based on geographic
  280. distance
  281. """
  282. uh = urlopen('http://www.speedtest.net/speedtest-servers.php')
  283. serversxml = []
  284. while 1:
  285. serversxml.append(uh.read(10240))
  286. if len(serversxml[-1]) == 0:
  287. break
  288. if int(uh.code) != 200:
  289. return None
  290. uh.close()
  291. try:
  292. root = ET.fromstring(''.encode().join(serversxml))
  293. elements = root.getiterator('server')
  294. except AttributeError:
  295. root = DOM.parseString(''.join(serversxml))
  296. elements = root.getElementsByTagName('server')
  297. servers = {}
  298. for server in elements:
  299. try:
  300. attrib = server.attrib
  301. except AttributeError:
  302. attrib = dict(list(server.attributes.items()))
  303. d = distance([float(client['lat']), float(client['lon'])],
  304. [float(attrib.get('lat')), float(attrib.get('lon'))])
  305. attrib['d'] = d
  306. if d not in servers:
  307. servers[d] = [attrib]
  308. else:
  309. servers[d].append(attrib)
  310. del root
  311. del serversxml
  312. del elements
  313. closest = []
  314. for d in sorted(servers.keys()):
  315. for s in servers[d]:
  316. closest.append(s)
  317. if len(closest) == 5 and not all:
  318. break
  319. else:
  320. continue
  321. break
  322. del servers
  323. return closest
  324. def getBestServer(servers):
  325. """Perform a speedtest.net "ping" to determine which speedtest.net
  326. server has the lowest latency
  327. """
  328. results = {}
  329. for server in servers:
  330. cum = []
  331. url = os.path.dirname(server['url'])
  332. for i in range(0, 3):
  333. try:
  334. uh = urlopen('%s/latency.txt' % url)
  335. except HTTPError:
  336. cum.append(3600)
  337. continue
  338. start = time.time()
  339. text = uh.read(9)
  340. total = time.time() - start
  341. if int(uh.code) == 200 and text == 'test=test'.encode():
  342. cum.append(total)
  343. else:
  344. cum.append(3600)
  345. uh.close()
  346. avg = round((sum(cum) / 3) * 1000000, 3)
  347. results[avg] = server
  348. fastest = sorted(results.keys())[0]
  349. best = results[fastest]
  350. best['latency'] = fastest
  351. return best
  352. def ctrl_c(signum, frame):
  353. """Catch Ctrl-C key sequence and set a shutdown_event for our threaded
  354. operations
  355. """
  356. global shutdown_event
  357. shutdown_event.set()
  358. raise SystemExit('\nCancelling...')
  359. def version():
  360. """Print the version"""
  361. raise SystemExit(__version__)
  362. def speedtest():
  363. """Run the full speedtest.net test"""
  364. global shutdown_event, source
  365. shutdown_event = threading.Event()
  366. signal.signal(signal.SIGINT, ctrl_c)
  367. description = (
  368. 'Command line interface for testing internet bandwidth using '
  369. 'speedtest.net.\n'
  370. '------------------------------------------------------------'
  371. '--------------\n'
  372. 'https://github.com/sivel/speedtest-cli')
  373. parser = ArgParser(description=description)
  374. # Give optparse.OptionParser an `add_argument` method for
  375. # compatibility with argparse.ArgumentParser
  376. try:
  377. parser.add_argument = parser.add_option
  378. except AttributeError:
  379. pass
  380. parser.add_argument('--share', action='store_true',
  381. help='Generate and provide a URL to the speedtest.net '
  382. 'share results image')
  383. parser.add_argument('--simple', action='store_true',
  384. help='Suppress verbose output, only show basic '
  385. 'information')
  386. parser.add_argument('--list', action='store_true',
  387. help='Display a list of speedtest.net servers '
  388. 'sorted by distance')
  389. parser.add_argument('--server', help='Specify a server ID to test against')
  390. parser.add_argument('--mini', help='URL of the Speedtest Mini server')
  391. parser.add_argument('--source', help='Source IP address to bind to')
  392. parser.add_argument('--version', action='store_true',
  393. help='Show the version number and exit')
  394. options = parser.parse_args()
  395. if isinstance(options, tuple):
  396. args = options[0]
  397. else:
  398. args = options
  399. del options
  400. # Print the version and exit
  401. if args.version:
  402. version()
  403. # If specified bind to a specific IP address
  404. if args.source:
  405. source = args.source
  406. socket.socket = bound_socket
  407. if not args.simple:
  408. print_('Retrieving speedtest.net configuration...')
  409. try:
  410. config = getConfig()
  411. except URLError:
  412. print_('Cannot retrieve speedtest configuration')
  413. sys.exit(1)
  414. if not args.simple:
  415. print_('Retrieving speedtest.net server list...')
  416. if args.list or args.server:
  417. servers = closestServers(config['client'], True)
  418. if args.list:
  419. serverList = []
  420. for server in servers:
  421. line = ('%(id)4s) %(sponsor)s (%(name)s, %(country)s) '
  422. '[%(d)0.2f km]' % server)
  423. serverList.append(line)
  424. # Python 2.7 and newer seem to be ok with the resultant encoding
  425. # from parsing the XML, but older versions have some issues.
  426. # This block should detect whether we need to encode or not
  427. try:
  428. unicode()
  429. print_('\n'.join(serverList).encode('utf-8', 'ignore'))
  430. except NameError:
  431. print_('\n'.join(serverList))
  432. except IOError:
  433. pass
  434. sys.exit(0)
  435. else:
  436. servers = closestServers(config['client'])
  437. if not args.simple:
  438. print_('Testing from %(isp)s (%(ip)s)...' % config['client'])
  439. if args.server:
  440. try:
  441. best = getBestServer(filter(lambda x: x['id'] == args.server,
  442. servers))
  443. except IndexError:
  444. print_('Invalid server ID')
  445. sys.exit(1)
  446. elif args.mini:
  447. name, ext = os.path.splitext(args.mini)
  448. if ext:
  449. url = os.path.dirname(args.mini)
  450. else:
  451. url = args.mini
  452. urlparts = urlparse(url)
  453. try:
  454. f = urlopen(args.mini)
  455. except:
  456. print_('Invalid Speedtest Mini URL')
  457. sys.exit(1)
  458. else:
  459. text = f.read()
  460. f.close()
  461. extension = re.findall('upload_extension: "([^"]+)"', text.decode())
  462. if not urlparts or not extension:
  463. print_('Please provide the full URL of your Speedtest Mini server')
  464. sys.exit(1)
  465. servers = [{
  466. 'sponsor': 'Speedtest Mini',
  467. 'name': urlparts[1],
  468. 'd': 0,
  469. 'url': '%s/speedtest/upload.%s' % (url.rstrip('/'), extension[0]),
  470. 'latency': 0,
  471. 'id': 0
  472. }]
  473. try:
  474. best = getBestServer(servers)
  475. except:
  476. best = servers[0]
  477. else:
  478. if not args.simple:
  479. print_('Selecting best server based on ping...')
  480. best = getBestServer(servers)
  481. if not args.simple:
  482. # Python 2.7 and newer seem to be ok with the resultant encoding
  483. # from parsing the XML, but older versions have some issues.
  484. # This block should detect whether we need to encode or not
  485. try:
  486. unicode()
  487. print_(('Hosted by %(sponsor)s (%(name)s) [%(d)0.2f km]: '
  488. '%(latency)s ms' % best).encode('utf-8', 'ignore'))
  489. except NameError:
  490. print_('Hosted by %(sponsor)s (%(name)s) [%(d)0.2f km]: '
  491. '%(latency)s ms' % best)
  492. else:
  493. print_('Ping: %(latency)s ms' % best)
  494. sizes = [350, 500, 750, 1000, 1500, 2000, 2500, 3000, 3500, 4000]
  495. urls = []
  496. for size in sizes:
  497. for i in range(0, 4):
  498. urls.append('%s/random%sx%s.jpg' %
  499. (os.path.dirname(best['url']), size, size))
  500. if not args.simple:
  501. print_('Testing download speed', end='')
  502. dlspeed = downloadSpeed(urls, args.simple)
  503. if not args.simple:
  504. print_()
  505. print_('Download: %0.2f Mbit/s' % ((dlspeed / 1000 / 1000) * 8))
  506. sizesizes = [int(.25 * 1000 * 1000), int(.5 * 1000 * 1000)]
  507. sizes = []
  508. for size in sizesizes:
  509. for i in range(0, 25):
  510. sizes.append(size)
  511. if not args.simple:
  512. print_('Testing upload speed', end='')
  513. ulspeed = uploadSpeed(best['url'], sizes, args.simple)
  514. if not args.simple:
  515. print_()
  516. print_('Upload: %0.2f Mbit/s' % ((ulspeed / 1000 / 1000) * 8))
  517. if args.share and args.mini:
  518. print_('Cannot generate a speedtest.net share results image while '
  519. 'testing against a Speedtest Mini server')
  520. elif args.share:
  521. dlspeedk = int(round((dlspeed / 1000) * 8, 0))
  522. ping = int(round(best['latency'], 0))
  523. ulspeedk = int(round((ulspeed / 1000) * 8, 0))
  524. # Build the request to send results back to speedtest.net
  525. # We use a list instead of a dict because the API expects parameters
  526. # in a certain order
  527. apiData = [
  528. 'download=%s' % dlspeedk,
  529. 'ping=%s' % ping,
  530. 'upload=%s' % ulspeedk,
  531. 'promo=',
  532. 'startmode=%s' % 'pingselect',
  533. 'recommendedserverid=%s' % best['id'],
  534. 'accuracy=%s' % 1,
  535. 'serverid=%s' % best['id'],
  536. 'hash=%s' % md5(('%s-%s-%s-%s' %
  537. (ping, ulspeedk, dlspeedk, '297aae72'))
  538. .encode()).hexdigest()]
  539. req = Request('http://www.speedtest.net/api/api.php',
  540. data='&'.join(apiData).encode())
  541. req.add_header('Referer', 'http://c.speedtest.net/flash/speedtest.swf')
  542. f = urlopen(req)
  543. response = f.read()
  544. code = f.code
  545. f.close()
  546. if int(code) != 200:
  547. print_('Could not submit results to speedtest.net')
  548. sys.exit(1)
  549. qsargs = parse_qs(response.decode())
  550. resultid = qsargs.get('resultid')
  551. if not resultid or len(resultid) != 1:
  552. print_('Could not submit results to speedtest.net')
  553. sys.exit(1)
  554. print_('Share results: http://www.speedtest.net/result/%s.png' %
  555. resultid[0])
  556. def main():
  557. try:
  558. speedtest()
  559. except KeyboardInterrupt:
  560. print_('\nCancelling...')
  561. if __name__ == '__main__':
  562. main()
  563. # vim:ts=4:sw=4:expandtab