getNTPserversNew.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536
  1. # getNTPserversNew.py
  2. #
  3. # Demonstration of the parsing module, implementing a HTML page scanner,
  4. # to extract a list of NTP time servers from the NIST web site.
  5. #
  6. # Copyright 2004-2010, by Paul McGuire
  7. # September, 2010 - updated to more current use of setResultsName, new NIST URL
  8. #
  9. import pyparsing as pp
  10. ppc = pp.pyparsing_common
  11. from contextlib import closing
  12. try:
  13. import urllib.request
  14. urlopen = urllib.request.urlopen
  15. except ImportError:
  16. import urllib
  17. urlopen = urllib.urlopen
  18. integer = pp.Word(pp.nums)
  19. ipAddress = ppc.ipv4_address()
  20. hostname = pp.delimitedList(pp.Word(pp.alphas, pp.alphanums+"-_"), ".", combine=True)
  21. tdStart, tdEnd = pp.makeHTMLTags("td")
  22. timeServerPattern = (tdStart + hostname("hostname") + tdEnd
  23. + tdStart + ipAddress("ipAddr") + tdEnd
  24. + tdStart + tdStart.tag_body("loc") + tdEnd)
  25. # get list of time servers
  26. nistTimeServerURL = "https://tf.nist.gov/tf-cgi/servers.cgi#"
  27. with closing(urlopen(nistTimeServerURL)) as serverListPage:
  28. serverListHTML = serverListPage.read().decode("UTF-8")
  29. addrs = {}
  30. for srvr, startloc, endloc in timeServerPattern.scanString(serverListHTML):
  31. print("{0} ({1}) - {2}".format(srvr.ipAddr, srvr.hostname.strip(), srvr.loc.strip()))
  32. addrs[srvr.ipAddr] = srvr.loc