I'm trying to route requests in a python script through tor. Here's the code:
#!/usr/bin/env python3
import socket
import socks
from urllib import request
socks.set_default_proxy(socks.SOCKS5, '127.0.0.1', 9050)
socket.socket = socks.socksocket
ip = request.urlopen('https://api.ipify.org/').read()
print(ip)
When I try to run it as a user (just "./script.py"), it crashes with the following error:
urllib.error.URLError: <urlopen error Socket error: 0x01: General SOCKS server failure>
But if I run the script with sudo ("sudo ./script.py"), it works as expected and prints a tor IP. How can I get it to work without sudo?
Edit 1: I think tor installation is ok, because it works fine with other languages (for example, I can perform requests from a Go script. Also, I can get my python script to work with tor when passing proxies dict to requests.get() (as suggested in a comment below). This solution is acceptable, but I am still wondering, what's wrong with my script.
Edit 2: I'm running Linux Mint 18.3 64-bit. Python and Python3 are pre-installed. Tor was installed via repository (sudo apt-get install tor). I tried installing PySocks globally (sudo pip3 install PySocks) and only for current user (pip3 install --user PySocks).