Profile picture

[Python] Tor browser(proxy)로 ip 변경

JaehyoJJAng2023년 06월 06일

구동 환경

  • Ubuntu 18.04

Tor 설치

1. 레포지토리 업데이트

sudo apt-get update -y

2. Tor 패키지 설치

sudo apt-get install tor

3. Tor가 백그라운드에서 실행되도록 서비스 활성화

sudo service tor start

4. 서비스 동작하는지 확인

sudo systemctl status tor | grep 'Active'

Active: active (exited) since Wed 2023-08-09 16:24:46 KST; 2min 17s ago

tor 작동확인

1. 토르가 잘 작동하는지 확인하기 위해 torsocks 설치

sudo apt-get install -y torsocks

2. ip 체크

torsocks wget -qO- http://icanhazip.com/; echo

185.220.101.80
1691566094 ERROR torsocks[8175]: Unable to resolve. Status reply: 4 (in socks5_recv_resolve_reply() at socks5.c:677)

본인 IP와 달라진 것이 확인 되었다면 성공적으로 완료된 것.


Tor IP 재설정

sudo killall -HUP tor

운영 체제에서 실행 중인 Tor 프로세스에 HUP(HangUP) 신호를 보내 해당 프로세스를 다시 시작하도록 하는 명령.


Chrome 설치

리눅스에서 Selenium을 사용하려면 크롬 설치가 필요하다.

해당 포스팅을 참고하여 크롬 설치를 완료해보도록 해라 -> [Linux] Ubuntu 18.04 LTS - 크롬 설치하기


Requests 라이브러리

requests 라이브러리를 사용하여 크롤링할 때 IP를 바꿔보도록 하자


1. pip를 이용해 pysocks 설치

pip install pysocks requests

2. 아래 코드 작성

import requests as rq

def main() -> None:
    url: str = 'http://icanhazip.com/'

    proxies: dict[str,str] = {
        'http': 'socks5://127.0.0.1:9050',
        'https': 'socks5://127.0.0.1:9050'
    }

    response : rq.Response = rq.get(url=url,proxies=proxies)
    print(response.text)

실행 결과

$ python3 main.py

<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">10.44.100.90
</pre></body></html>

Loading script...