2

I'm writing a script in python.
My script uses urllib2 to read web pages.
I'm using Socksipy to force urllib2 to use socks proxy (TOR).
My problem is after setting socket.socket TorCtl doesn't work and raises exception.
the code that doesn't work is (first newTorId() works and second fails!):

  newTorId()      #This works
  import socks
  import socket
  socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "localhost", 9050)
  socket.socket = socks.socksocket
  newTorId()     #this Fails!

newTorId is defined as this:

from TorCtl import TorCtl
def newTorId():
    conn = TorCtl.connect(passphrase="test")
    conn.send_signal("NEWNYM")

The exception is:

__init__() takes exactly 2 arguments (3 given)
Traceback (most recent call last):
  File "script.py", line 97, in <module>
    newTorId()
  File "script.py", line 27, in newTorId
    conn.send_signal("NEWNYM")
AttributeError: 'NoneType' object has no attribute 'send_signal'

What is the problem?

4

2 回答 2

1

It's your own code raising the exception, not the library. Particularly,

TorCtl.connect(passphrase="test")

is returning None the second time, resulting in an error when you call .send_signal on the result.

I assume newTorId() is intended to request a new Tor identity. You should probably just call TorCtl.Connection.send_signal(conn, "NEWNYM") to get a new identity, rather than trying to create a new connection each time. See Python - Controlling Tor.

于 2012-06-05T08:13:02.007 回答
0

As previously mentioned TorCtl's connect() method provides None if it fails to connect.

That aside, this question seems to come up pretty frequently (1, 2) so I just added a FAQ entry for it. TorCtl is deprecated, so here's an example using stem...

from stem import Signal
from stem.control import Controller

with Controller.from_port(port = 9051) as controller:
  controller.authenticate()
  controller.signal(Signal.NEWNYM)
于 2013-06-16T10:43:49.667 回答