Can I change SOCKS proxies within a function using SocksiPy?

I am trying to write a function that will take a url and return the contents of that url. There is another argument (useTor), which when configured to Trueuse SocksiPy to route the request through the SOCKS 5 proxy server (in this case Tor).

I can set the proxy globally for all connections just fine, but I can’t solve two things:

  • How to transfer this parameter to a function so that a variable can be defined useTor? I can’t access the socksfunction inside and don’t know how to do it.

  • I assume that if I do not install the proxy, then the next time the request is made, it will go straight. The SocksiPy documentation does not seem to give any guidance on how the proxy reset.

Can anyone advise? My (beginner) code is below:

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)
+4
source share
1 answer

Example

Just call socksocket.set_proxywithout arguments, it will effectively remove all previously set proxy settings.

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

More details

By looking at the source socks.pyand digging out the contents socksocket.setproxy, we quickly realize that in order to discard any previous proxy attributes, we simply call the function without additional arguments (except 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 ( ).

0

Source: https://habr.com/ru/post/1608224/


All Articles