Tor 的 Python 脚本异常 [英] Python script Exception with Tor

查看:29
本文介绍了Tor 的 Python 脚本异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下使用 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 身份,但会等待一段时间并出现以下错误:

This code should change Tor identity but it waits for some time and gives the following error:

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)

但是上面的脚本被分成了2个单独的脚本:

But above script is divided into 2 separate scripts:

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()

当第二个脚本被调用时,第一个被调用就可以了.谁能解释一下是什么问题以及如何解决?

When second script is called then first is called it is ok. Can anyone explain what is the problem and how to fix?

推荐答案

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

Anonymous explained very well this socket overwrite, answer is almost perfect except you have to close the control socket. It is safer because of the TorCtl event loop, but I have to look deeper in the TorCtl code to understand this event loop.

总结你的代码变成:

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())

这篇关于Tor 的 Python 脚本异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆