使用Tor的Python脚本异常

时间:2012-03-29 12:31:25

标签: python tor

我有以下使用SocksiPY

的脚本

和Tor:

from TorCtl import TorCtl

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

import urllib2
import sqlite3
from BeautifulSoup import BeautifulSoup

def newId():
    conn = TorCtl.connect(controlAddr="127.0.0.1", controlPort=9051, passphrase="123")
    TorCtl.Connection.send_signal(conn, "NEWNYM")

newId()

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

此代码应更改Tor标识,但等待一段时间后会出现以下错误:

tuple index out of range
Traceback (most recent call last):
  File "template.py", line 16, in <module>
    newId()
  File "template.py", line 14, in newId
    TorCtl.Connection.send_signal(conn, "NEWNYM")
TypeError: unbound method send_signal() must be called with Connection instance as first argument (got NoneType instance instead)

但是上面的脚本分为两个独立的脚本:

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

import urllib2
import sqlite3
from BeautifulSoup import BeautifulSoup

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

from TorCtl import TorCtl
def newId():
    conn = TorCtl.connect(controlAddr="127.0.0.1", controlPort=9051, passphrase="123")
    TorCtl.Connection.send_signal(conn, "NEWNYM")

newId()

当第二个脚本被调用时,首先调用它就可以了。任何人都可以解释问题是什么以及如何解决?

2 个答案:

答案 0 :(得分:5)

Anonymous很好地解释了这个套接字覆盖,答案几乎是完美的,除非你必须关闭控制套接字。由于TorCtl事件循环,它更安全,但我必须深入研究TorCtl代码才能理解这个事件循环。

总结一下你的代码:

from TorCtl import TorCtl

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

import urllib2
import sqlite3
from BeautifulSoup import BeautifulSoup

__originalSocket = socket.socket

def newId():
    ''' Clean circuit switcher

    Restores socket to original system value.
    Calls TOR control socket and closes it
    Replaces system socket with socksified socket
    '''
    socket.socket = __originalSocket
    conn = TorCtl.connect(controlAddr="127.0.0.1", controlPort=9051, passphrase="123")
    TorCtl.Connection.send_signal(conn, "NEWNYM")
    conn.close()
    socket.socket = socks.socksocket

newId()

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

答案 1 :(得分:2)

与控制端口的连接失败,并为conn分配了Python套接字用于指示失败的值(显然类型为NoneType)。

原因是在语句socket.socket = socks.socksocket中,显然您正在用一个透明地代理所有通过Tor的代理来替换默认套接字对象或类,这使得程序尝试代理您的控制端口连接。 / p>

解决方案是仅在打开控制连接后执行socket.socket = socks.socksocket (并在以后需要时保持该连接)或保存原始socket.socket值,以便您可以根据需要在值之间切换。