Make Requests Using Python Over Tor

Make requests using Python over Tor

Here is the code you want to use (download the stem package using pip install stem)

from stem import Signal
from stem.control import Controller

with Controller.from_port(port = 9051) as controller:
controller.authenticate(password='your password set for tor controller port in torrc')
print("Success!")
controller.signal(Signal.NEWNYM)
print("New Tor connection processed")

Good luck and hopefully that works.

Making a request using requests.get through tor proxies but the code is not responding

Tor runs proxy on port 9050, not 9051. Port 9051 is used only to control/change Tor.


I also need few seconds after sending singnal to get new IP.

And it works better when I don't use one session for all urls but normal requests

requests.get(..., proxies=proxies)

With one session it sometimes gives the same IP for https://httpbin.org/ip and https://api.ipify.org but not for https://icanhazip.com .

It works correctly if I create new session in every loop.


Version without session

from stem import Signal
from stem.control import Controller
import requests
import time

def change_ip():
with Controller.from_port(port=9051) as control:
control.authenticate(password='password')
control.signal(Signal.NEWNYM)

proxies = {
'http': 'socks5://127.0.0.1:9050',
'https': 'socks5://127.0.0.1:9050',
}

for i in range(5):

r = requests.get('https://httpbin.org/ip', proxies=proxies)
print(r.json()['origin'])

r = requests.get('https://api.ipify.org', proxies=proxies)
print(r.text)

r = requests.get('https://icanhazip.com', proxies=proxies)
print(r.text)

change_ip()
time.sleep(5)

Version with session - new session in every loop

from stem import Signal
from stem.control import Controller
import requests
import time

def change_ip():
with Controller.from_port(port=9051) as control:
control.authenticate(password='password')
control.signal(Signal.NEWNYM)

for i in range(5):

session = requests.Session()

session.proxies = {
'http': 'socks5://127.0.0.1:9050',
'https': 'socks5://127.0.0.1:9050',
}

r = session.get('https://httpbin.org/ip')
print(r.json()['origin'])

r = session.get('https://api.ipify.org')
print(r.text)

r = session.get('https://icanhazip.com')
print(r.text)

change_ip()
time.sleep(5)

Using tor to make requests python?

Here is code that works for me:

import requests
torport = 9050
proxies = {
'http': "socks5h://localhost:{}".format(torport),
'https': "socks5h://localhost:{}".format(torport)
}

print(requests.get('http://icanhazip.com', proxies=proxies).content)

Check to make sure Tor is running on your machine and that the firewall on Windows / Defender etc. are not blocking the port you are trying to access.



Related Topics



Leave a reply



Submit