簡體   English   中英

我可以使用SocksiPy在函數內更改SOCKS代理嗎?

[英]Can I change SOCKS proxy within a function using SocksiPy?

我正在嘗試編寫一個函數,它將獲取一個URL並返回該URL的內容。 還有一個參數(useTor),當設置為True ,將使用SocksiPy通過SOCKS 5代理服務器(在本例中為Tor)路由請求。

我可以為所有連接全局設置代理,但我無法解決兩件事:

  1. 如何將此設置移動到一個函數中,以便可以在useTor變量上決定它? 我無法在函數中訪問socks並且不知道如何執行此操作。

  2. 我假設如果我沒有設置代理,那么下次請求時它將直接進行。 SocksiPy文檔似乎沒有給出關於如何重置代理的任何指示。

任何人都可以建議嗎? 我的(初學者)代碼如下:

import gzip
import socks
import socket

def create_connection(address, timeout=None, source_address=None):
    sock = socks.socksocket()
    sock.connect(address)
    return sock

# next line works just fine if I want to set the proxy globally
# socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
socket.socket = socks.socksocket
socket.create_connection = create_connection

import urllib2
import sys

def getURL(url, useTor=False):

    if useTor:
        print "Using tor..."
        # Throws- AttributeError: 'module' object has no attribute 'setproxy'
        socks.setproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
    else:
        print "Not using tor..."
        # Not sure how to cancel the proxy, assuming it persists

    opener = urllib2.build_opener()
    usock = opener.open(url)
    url = usock.geturl()

    encoding = usock.info().get("Content-Encoding")

    if encoding in ('gzip', 'x-gzip', 'deflate'):
        content = usock.read()
        if encoding == 'deflate':
            data = StringIO.StringIO(zlib.decompress(content))
        else:
            data = gzip.GzipFile('', 'rb', 9, StringIO.StringIO(content))
        result = data.read()
    else:
        result = usock.read()

    usock.close()

    return result

# Connect to the same site both with and without using Tor    

print getURL('https://check.torproject.org', False)
print getURL('https://check.torproject.org', True)

只需調用socksocket.set_proxy帶參數的socksocket.set_proxy ,這將有效地刪除任何以前設置的代理設置。

import socks
sck = socks.socksocket ()
# use TOR
sck.setproxy (socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
# reset to normal use
sck.setproxy ()

細節

通過查看socks.py的源代碼並深入研究socksocket.setproxy的內容,我們很快意識到,為了丟棄任何以前的代理屬性,我們只需調用該函數而不需要額外的參數(除了self )。

class socksocket(socket.socket):
    ... # additional functionality ignored

    def setproxy(self,proxytype=None,addr=None,port=None,rdns=True,username=None,password=None):
        """setproxy(proxytype, addr[, port[, rdns[, username[, password]]]])
        Sets the proxy to be used.
        proxytype - The type of the proxy to be used. Three types
                are supported: PROXY_TYPE_SOCKS4 (including socks4a),
                PROXY_TYPE_SOCKS5 and PROXY_TYPE_HTTP
        addr -      The address of the server (IP or DNS).
        port -      The port of the server. Defaults to 1080 for SOCKS
                servers and 8080 for HTTP proxy servers.
        rdns -      Should DNS queries be preformed on the remote side
                (rather than the local side). The default is True.
                Note: This has no effect with SOCKS4 servers.
        username -  Username to authenticate with to the server.
                The default is no authentication.
        password -  Password to authenticate with to the server.
                Only relevant when username is also provided.
        """
        self.__proxy = (proxytype,addr,port,rdns,username,password)

    ... # additional functionality ignored

注意 :當即將協商新連接時,實現將使用self.__proxy的內容,除非可能需要的元素為None (在這種情況下,設置被簡單地忽略)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM