2

Hello Guys! At first I want to assure that there is similar topics but there is no accepted answer or clear response. So I want to combine them and ask again. I have following script:

import urllib2

proxy = urllib2.ProxyHandler({"http":"127.0.0.1:9050"})
opener = urllib2.build_opener(proxy)
print(opener.open("http://www.ifconfig.me/ip").read())

I want to run it anonymously, using with tor for example. But it gives this error:

Traceback (most recent call last):
  File "python_tor.py", line 5, in <module>
    print(opener.open("http://www.ifconfig.me/ip").read())
  File "/usr/lib/python2.7/urllib2.py", line 400, in open
    response = meth(req, response)
  File "/usr/lib/python2.7/urllib2.py", line 513, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib/python2.7/urllib2.py", line 438, in error
    return self._call_chain(*args)
  File "/usr/lib/python2.7/urllib2.py", line 372, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.7/urllib2.py", line 521, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 501: Tor is not an HTTP Proxy

I have found following answers in stackoverflow:

 proxy_support = urllib2.ProxyHandler({"http" : "127.0.0.1:8118"})
    opener = urllib2.build_opener(proxy_support) 
    opener.addheaders = [('User-agent', 'Mozilla/5.0')]
    print opener.open('http://www.google.com').read()

And also this comment to this topic:

It may be worthwhile for people reading this thread to know that port 8118 is actually Privoxy's port, not Tor. Tor is a strictly SOCKS-only proxy (port 9050) so it rejects all non-SOCKS traffic (e.g. HTTP). To handle non-SOCKS traffic, you would need to use Privoxy (port 8118) or Polipo (port 8123) to translate the traffic into SOCKS so Tor would accept.

Privoxy is better for privacy and Polipo is better for performance because it does caching.

Can anyone explain how to execute my script anonymously?

user873286
  • 7,799
  • 7
  • 30
  • 38
  • possible duplicate of [Tor with Python?](http://stackoverflow.com/questions/1096379/tor-with-python) – Thilo Mar 26 '12 at 10:07

2 Answers2

4

It was possible with this using given answers:

import socks
import socket
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
socket.socket = socks.socksocket
import urllib2

print(urllib2.urlopen("http://www.ifconfig.me/ip").read())

But I am surprised is it possible to change tor's ip address with each new request???

user873286
  • 7,799
  • 7
  • 30
  • 38
  • you should open a new question. This need the tor control protocol. Send "signal NEWNYM" to 127.0.0.1:9051. xt – J-16 SDiZ Mar 27 '12 at 01:53
3

Have you read the error message? It say "501 Tor is not an HTTP Proxy".

It is a SOCKS proxy, not a HTTP proxy. Try use it like so: How can I use a SOCKS 4/5 proxy with urllib2? and Python urllib over TOR?

Community
  • 1
  • 1
J-16 SDiZ
  • 26,473
  • 4
  • 65
  • 84