python 무료 vpn을 통해 ip 바꾸기
크롤링을 한다거나, 한국 ip 차단 된 사이트를 접속하는 등 vpn이 필요한 경우가 종종있다.
프로그램을 짜면서 ip를 바꿔야만 하는일이 그렇게 많을거 같진 않지만 뭐.. 기록용으로 남겨둔다
코드 출처는 여기
VPNGate Python script
VPNGate Python script. GitHub Gist: instantly share code, notes, and snippets.
gist.github.com
실행해보고 ip가 바뀌었는지 확인은 요기서 해보면 된다
아이피 확인 - my ip address
IP 주소를 확인하는 가장 쉽고 빠른 방법 이 사이트(findip.kr)에 접속하는 것이 IP주소를 확인하는 가장 쉽고 빠른 방법이다. 210.220.70.4 가 현재 접속한 기기의 공인 IP(Internet Protocol) 주소다 IP주소는
www.findip.kr
리눅스에서 실행
vpngate의 무료 vpn를 받아서 openvpn이라는 프로그램으로 vpn을 연결한다
이 프로그램은 리눅스에서만 작동한다. 테스트 해본 환경은 Ubuntu 20LTS버전이다.
openvpn을 깔아주자
sudo apt-get install openvpn
vpngate.py
#!/usr/bin/env python3
"""Pick server and start connection with VPNGate (http://www.vpngate.net/en/)"""
import requests
import os
import sys
import tempfile
import subprocess
import base64
import time
__author__ = "Andrea Lazzarotto"
__copyright__ = "Copyright 2014+, Andrea Lazzarotto"
__license__ = "GPLv3"
__version__ = "1.0"
__maintainer__ = "Andrea Lazzarotto"
__email__ = "andrea.lazzarotto@gmail.com"
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:
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 BaseException:
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 = list(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]).decode())
f.write(
"\nscript-security 2\nup /etc/openvpn/update-resolv-conf\ndown /etc/openvpn/update-resolv-conf"
)
f.close()
x = subprocess.Popen(["sudo", "openvpn", "--config", path])
try:
while True:
time.sleep(600)
# termination with Ctrl+C
except BaseException:
try:
x.kill()
except BaseException:
pass
while x.poll() != 0:
time.sleep(1)
print("\nVPN terminated")
실행 방법은 간단하다. python3 vpngate.py korea
이렇게 vpngate.py [국가명 | 국가코드]를 적어주면 해당 국가에 대한 vpn 정보중 제일 환경이 좋은거로 연결해준다.
윈도우에서 실행
Community Downloads | OpenVPN
Visit this page to download the latest version of the open source VPN, OpenVPN.
openvpn.net
여기서 Windows 64-bit MSI installer 받아서 설치해준다
이제 환경변수를 설정해주자
윈도우키누르고 "환경" 검색 후 "시스템 환경 변수 편집" 클릭
해당 경로로 들어가서 openvpn이 설치된 경로에 bin폴더를 환경변수로 잡아줌
기존에 켜졌던 프로세스는 환경변수 적용안되니 껐다키고, 새로킨 cmd에서 openvpn이라고 쳤을때 반응이 있으면 설정 완료 된거임
vpngate.py
import requests
import os
import sys
import tempfile
import subprocess
import base64
import time
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:
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 BaseException:
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 = list(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]).decode())
x = subprocess.Popen(["openvpn", "--config", path])
try:
while True:
time.sleep(600)
# termination with Ctrl+C
except BaseException:
try:
x.kill()
except BaseException:
pass
while x.poll() != 0:
time.sleep(1)
print("\nVPN terminated")
실행방법은 python vpngate.py korea
주의! 이때 cmd를 관리자 권한으로 실행시켜야함!
실행전과 실행후 ip확인 사이트에서 ip가 달라졌는지 확인하면 된다.
이 코드를 응용해서 멀티프로세스같은것을 이용하든 약간의 수정을 하든해서
자신의 프로그램을 사용할때 ip를 변경하는 작업을 할 수 있을것이다.