Transfusion

vpngate.py

Mar 29th, 2019
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.33 KB | None | 0 0
  1. import urllib2, sys, base64, tempfile, subprocess, time
  2.  
  3. __author__ = "Heewon Lee and Andrea Lazzarotto"
  4. __copyright__ = "Copyright 2014+, Heewon Lee and Andrea Lazzarotto"
  5. __license__ = "GPLv3"
  6. __version__ = "1.0"
  7. __maintainer__ = "Heewon Lee"
  8. __email__ = "[email protected]"
  9.  
  10. #OPENVPN_PATH = "/Applications/Tunnelblick.app/Contents/Resources/openvpn/default"
  11. OPENVPN_PATH = "./vpngate.ovpn"
  12. VPNGATE_API_URL = "http://www.vpngate.net/api/iphone/"
  13. DEFAULT_COUNTRY = "JP"
  14. DEFAULT_SERVER = 0
  15. YES = False
  16.  
  17. def getServers():
  18.     servers = []
  19.     server_strings = urllib2.urlopen(VPNGATE_API_URL).read()
  20.     for server_string in server_strings.replace("\r", "").split('\n')[2:-2]:
  21.         (HostName, IP, Score, Ping, Speed, CountryLong, CountryShort, NumVpnSessions, Uptime, TotalUsers, TotalTraffic, LogType, Operator, Message, OpenVPN_ConfigData_Base64) = server_string.split(',')
  22.         server = {
  23.             'HostName': HostName,
  24.             'IP': IP,
  25.             'Score': Score,
  26.             'Ping': Ping,
  27.             'Speed': Speed,
  28.             'CountryLong': CountryLong,
  29.             'CountryShort': CountryShort,
  30.             'NumVpnSessions': NumVpnSessions,
  31.             'Uptime': Uptime,
  32.             'TotalUsers': TotalUsers,
  33.             'TotalTraffic': TotalTraffic,
  34.             'LogType': LogType,
  35.             'Operator': Operator,
  36.             'Message': Message,
  37.             'OpenVPN_ConfigData_Base64': OpenVPN_ConfigData_Base64
  38.         }
  39.         servers.append(server)
  40.     return servers
  41.  
  42. def getCountries(server):
  43.     return set((server['CountryShort'], server['CountryLong']) for server in servers)
  44.  
  45. def printCountries(countries):
  46.     print("    Connectable countries:")
  47.     newline = False
  48.     for country in countries:
  49.         print("    %-2s) %-25s" % (country[0], country[1])),
  50.         if newline:
  51.             print('\n'),
  52.         newline = not newline
  53.     if newline:
  54.         print('\n'),
  55.  
  56. def printServers(servers):
  57.     print("  Connectable Servers:")
  58.     for i in xrange(len(servers)):
  59.         server = servers[i]
  60.         print("    %2d) %-15s [%6.2f Mbps, ping:%3s ms]" % (i, server['IP'], float(server['Speed'])/10**6, server['Ping']))
  61.  
  62. def selectCountry(countries):
  63.     selected = ""
  64.     default_country = DEFAULT_COUNTRY
  65.     short_countries = list(country[0] for country in countries)
  66.     if not default_country in short_countries:
  67.         default_country = short_countries[0]
  68.     if YES:
  69.         selected = default_country
  70.     while not selected:
  71.         try:
  72.             selected = raw_input("[?] Select server's country to connect [%s]: " % (default_country, )).strip().upper()
  73.         except:
  74.             print("[!] Please enter short name of the country.")
  75.             selected = ""
  76.         if selected == "":
  77.             selected = default_country
  78.         elif not selected in short_countries:
  79.             print("[!] Please enter short name of the country.")
  80.             selected = ""
  81.     return selected
  82.  
  83. def selectServer(servers):
  84.     selected = -1
  85.     default_server = DEFAULT_SERVER
  86.     if YES:
  87.         selected = default_server
  88.     while selected == -1:
  89.         try:
  90.             selected = raw_input("[?] Select server's number to connect [%d]: " % (default_server, )).strip()
  91.         except:
  92.             print("[!] Please enter vaild server's number.")
  93.             selected = -1
  94.         if selected == "":
  95.             selected = default_server
  96.         elif not selected.isdigit() or int(selected) >= len(servers):
  97.             print("[!] Please enter vaild server's number.")
  98.             selected = -1
  99.     return servers[int(selected)]
  100.  
  101. def saveOvpn(server):
  102.     _, ovpn_path = tempfile.mkstemp()
  103.     ovpn = open(ovpn_path, 'w')
  104.     ovpn.write(base64.b64decode(server["OpenVPN_ConfigData_Base64"]))
  105.     ovpn.close()
  106.     return ovpn_path
  107.  
  108. def connect(ovpn_path):
  109.     openvpn_process = subprocess.Popen(['sudo', OPENVPN_PATH, '--config', ovpn_path])
  110.     try:
  111.         while True:
  112.             time.sleep(600)
  113.     # termination with Ctrl+C
  114.     except:
  115.         try:
  116.             openvpn_process.kill()
  117.         except:
  118.             pass
  119.         while openvpn_process.poll() != 0:
  120.             time.sleep(1)
  121.         print("[=] Disconnected OpenVPN.")
  122.  
  123. if __name__ == "__main__":
  124.     if len(sys.argv) > 1 and sys.argv[1] == "-y":
  125.         YES = True
  126.  
  127.     servers = []
  128.     try:
  129.         print("[-] Trying to get server's informations...")
  130.         servers = sorted(getServers(), key=lambda server: int(server["Score"]), reverse=True)
  131.     except:
  132.         print("[!] Failed to get server's informations from vpngate.")
  133.         sys.exit(1)
  134.  
  135.     if not servers:
  136.         print("[!] There is no running server on vpngate.")
  137.         sys.exit(1)
  138.  
  139.     print("[-] Got server's informations.")
  140.  
  141.     countries = sorted(getCountries(servers))
  142.     printCountries(countries)
  143.     selected_country = selectCountry(countries)
  144.  
  145.     print("[-] Gethering %s servers..." % (selected_country, ))
  146.  
  147.     selected_servers = [server for server in servers if server['CountryShort'] == selected_country]
  148.     printServers(selected_servers)
  149.     selected_server = selectServer(selected_servers)
  150.  
  151.     print("[-] Generating .ovpn file of %s..." % (selected_server["IP"], ))
  152.    
  153.     ovpn_path = saveOvpn(selected_server)
  154.  
  155.     print("[-] Connecting to %s..." % (selected_server["IP"], ))
  156.  
  157. #    connect(ovpn_path)
Add Comment
Please, Sign In to add comment