ricleal

Untitled

Jul 16th, 2015
230
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.59 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3.  
  4. import urllib2
  5. import json
  6. from pprint import pprint
  7. import sys
  8. import re
  9.  
  10.  
  11. def get_urls_for_pac_files():
  12. """
  13. Return a list of possible auto proxy .pac files being used,
  14. based on the system registry (win32) or system preferences (OSX).
  15. @return: list of urls
  16. """
  17. pacFiles = []
  18. if sys.platform == 'win32':
  19. try:
  20. import _winreg as winreg # used from python 2.0-2.6
  21. except:
  22. import winreg # used from python 2.7 onwards
  23. net = winreg.OpenKey(
  24. winreg.HKEY_CURRENT_USER,
  25. "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"
  26. )
  27. nSubs, nVals, lastMod = winreg.QueryInfoKey(net)
  28. subkeys = {}
  29. for i in range(nVals):
  30. thisName, thisVal, thisType = winreg.EnumValue(net, i)
  31. subkeys[thisName] = thisVal
  32. if 'AutoConfigURL' in subkeys.keys() and len(subkeys['AutoConfigURL']) > 0:
  33. pacFiles.append(subkeys['AutoConfigURL'])
  34. elif sys.platform == 'darwin':
  35. import plistlib
  36. sysPrefs = plistlib.readPlist(
  37. '/Library/Preferences/SystemConfiguration/preferences.plist')
  38. networks = sysPrefs['NetworkServices']
  39. # loop through each possible network (e.g. Ethernet, Airport...)
  40. for network in networks.items():
  41. netKey, network = network # the first part is a long identifier
  42. if 'ProxyAutoConfigURLString' in network['Proxies'].keys():
  43. pacFiles.append(network['Proxies']['ProxyAutoConfigURLString'])
  44. return list(set(pacFiles)) # remove redundant ones
  45.  
  46.  
  47. def get_proxy_urls_from_pac_files(pac_urls_list):
  48. '''
  49. Parsed the pac files and find all the possible
  50. proxies addresses
  51. '''
  52. proxy_url_list = []
  53. for thisPacURL in pac_urls_list:
  54. print 'Connecting to the PAC URL:\n %s' % thisPacURL
  55. try:
  56. response = urllib2.urlopen(thisPacURL, timeout=2)
  57. except urllib2.URLError:
  58. print("Failed to find PAC URL '%s' " % thisPacURL)
  59. continue
  60. pacStr = response.read()
  61. possProxies = re.findall(
  62. r"PROXY\s([^\s;,:]+:[0-9]{1,5})[^0-9]", pacStr + '\n')
  63. for thisPoss in possProxies:
  64. proxUrl = 'http://' + thisPoss
  65. proxy_dic = {'http': proxUrl}
  66. proxy_url_list.append(proxy_dic)
  67. return proxy_url_list
  68.  
  69.  
  70. def set_proxy(proxy_dic=None):
  71. '''
  72. proxy format: {'http': 'http://www.example.com:3128/'}
  73. To disable autodetected proxy pass an empty dictionary: {}
  74. '''
  75. if proxy_dic is None:
  76. # The default is to read the list of proxies from the environment variables <protocol>_proxy.
  77. # If no proxy environment variables are set, then in a Windows environment proxy settings are
  78. # obtained from the registry's Internet Settings section, and in a Mac OS X environment proxy
  79. # information is retrieved from the OS X System Configuration
  80. # Framework.
  81. proxy = urllib2.ProxyHandler()
  82. else:
  83. # If proxies is given, it must be a dictionary mapping protocol names to
  84. # URLs of proxies.
  85. proxy = urllib2.ProxyHandler(proxy_dic)
  86. opener = urllib2.build_opener(proxy)
  87. urllib2.install_opener(opener)
  88. print "Proxies returned by urllib2.getproxies:",
  89. pprint(urllib2.getproxies())
  90.  
  91.  
  92. def check_update(url='http://www.sasview.org/latestversion.json', timeout=1):
  93. res = None
  94. req = urllib2.Request(url)
  95. try:
  96. print "* Direct connection..."
  97. res = urllib2.urlopen(req, timeout=timeout)
  98. except:
  99. try:
  100. print "** Proxy connection..."
  101. set_proxy()
  102. res = urllib2.urlopen(req, timeout=timeout)
  103. except:
  104. print "*** Pac Proxy connection..."
  105. pac_urls = get_urls_for_pac_files()
  106. proxy_urls = get_proxy_urls_from_pac_files(pac_urls)
  107. for proxy in proxy_urls:
  108. print "**** Trying proxy:", proxy
  109. try:
  110. set_proxy(proxy)
  111. res = urllib2.urlopen(req, timeout=timeout)
  112. break # suceeded!
  113. except Exception, e:
  114. print "**** This proxy doesn't work...", proxy
  115. pprint(e)
  116. if res is not None:
  117. print 50*'-'
  118. print 'Got it!! ::', url
  119. print 50*'-'
  120. content = json.loads(res.read().strip())
  121. pprint(content)
  122. print 50*'-'
  123.  
  124. if __name__ == "__main__":
  125. check_update()
Advertisement
Add Comment
Please, Sign In to add comment