Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connect to .onion websites on tor using python?

Tags:

python

tor

Here is the code that i have till now

import socks
import socket
import requests
import json

socks.setdefaultproxy(proxy_type=socks.PROXY_TYPE_SOCKS5, addr="127.0.0.1", port=9050)
socket.socket = socks.socksocket

data = json.loads(requests.get("http://freegeoip.net/json/").text)

and it works fine. The problem is when i use a .onion url it shows error

Failed to establish a new connection: [Errno -2] Name or service not known

After researching a little i found that although the http request is made over tor the resolution still occours over clearnet. What is the proper way so i can also have the domain resolved over tor network to connect to .onion urls ?

like image 238
georoot Avatar asked Apr 28 '17 14:04

georoot


1 Answers

Try to avoid the monkey patching if possible. If you're using modern version of requests, then you should have this functionality already.

import requests
import json

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

data = requests.get("http://altaddresswcxlld.onion",proxies=proxies).text

print(data)

It's important to specify the proxies using the socks5h:// scheme so that DNS resolution is handled over SOCKS so Tor can resolve the .onion address properly.

like image 158
drew010 Avatar answered Nov 05 '22 08:11

drew010