Connect VPN via Python

Here we are going to connect the VPN services through the python. After connect the VPN we can crawl the blocked website and so on.

The script going to use the free VPN services provided by VPNGate. The VPN based on the user input countries.

Prerequired

Open vpn must be available in your system. Use the below command to install open vpn in your linux machine,

1
apt-get install openvpn easy-rsa

further more details for the installation , Please follow the link install openvpn

Usage

Run the script by providing the desired output country like given below,

1
python script.py IN

Instead of giving country short name we can use the full name like given below,


1
python script.py India

further supported country information list available in that link. Please click me to see the details

The connection script is given below, Here we are checked the ip address instance after connected through the vpn.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#!/usr/bin/env python

"""
Pick server and start connection with VPNGate (http://www.vpngate.net/en/)

@author Ramachandran K <ramakavanan@gmail.com>
"""

import requests, os, sys, tempfile, subprocess, base64, time, json

if len(sys.argv) != 2:
    print 'usage: ' + sys.argv[0] + ' [country name | country code]'
    exit(1)
country = sys.argv[1]

if len(country) == 2:
    i = 6 # short name for country
elif len(country) > 2:
    i = 5 # long name for country
else:
    print 'Country is too short!'
    exit(1)

try:
    # Here we getting the free vpn server list  
    vpn_data = requests.get('http://www.vpngate.net/api/iphone/').text.replace('\r','')
    servers = [line.split(',') for line in vpn_data.split('\n')]
    labels = servers[1]
    labels[0] = labels[0][1:]
    servers = [s for s in servers[2:] if len(s) > 1]
except:
    print 'Cannot get VPN servers data'
    exit(1)

desired = [s for s in servers if country.lower() in s[i].lower()]
found = len(desired)
print 'Found ' + str(found) + ' servers for country ' + country
if found == 0:
    exit(1)

supported = [s for s in desired if len(s[-1]) > 0]
print str(len(supported)) + ' of these servers support OpenVPN'
# We pick the best servers by score
winner = sorted(supported, key=lambda s: float(s[2].replace(',','.')), reverse=True)[0]

print "\n== Best server =="
pairs = zip(labels, winner)[:-1]
for (l, d) in pairs[:4]:
    print l + ': ' + d

print pairs[4][0] + ': ' + str(float(pairs[4][1]) / 10**6) + ' MBps'
print "Country: " + pairs[5][1]

print "\nLaunching VPN..."
_, path = tempfile.mkstemp()

f = open(path, 'w')
f.write(base64.b64decode(winner[-1]))
f.write('\nscript-security 2\nup /etc/openvpn/update-resolv-conf\ndown /etc/openvpn/update-resolv-conf')
f.close()

# launching openvpn server with the config of vpngate server information
x = subprocess.Popen(['sudo', 'openvpn', '--config', path])

try:
     #time required to connect the openvpn to connect vpn server
 time.sleep(60)
 start_time = time.time()
 url = "http://bot.whatismyipaddress.com/"
 ret = requests.get(url)
 if ret.status_code == 200:
  with open('resp', "wb") as text_file:
   text_file.write(ret.text)
 print 'Time took to check Ip address  ',(time.time() - start_time)
 x.kill()
# termination with Ctrl+C
except Exception as ex:
    try:
        x.kill()
    except:
        pass
    while x.poll() != 0:
        time.sleep(1)
    print '\nVPN terminated'


After run the script to check the connected device public ip address from the resp.txt file in the script ran file path.




Comments

  1. Does it need the administrative privileges to run this stuff

    ReplyDelete
  2. This article is a great article that I have seen in my blog career so far. Thank you to share with this important information.

    website development company in Surat Gujarat

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. Nice post. I was checking constantly this blog and I am impressed! Extremely helpful information specially software development I care for such info a lot.
    Android App Development Company, New York USA
    Custom Software Development Company, New York USA

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete

Post a Comment

Popular posts from this blog

Pyhton auto post to blogger using Google blogger API

Website crawl or scraping with selenium and python