Search code examples
pythonmoduleproxyurllib2socks

How can I unwrap a module with SocksiPy?


I use the SocksiPy module to proxy my urllib2 requests through a SOCKS proxy:

import socks

# Set the proxy information
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, 'x.x.x.x', 9050)

# Route an HTTP request through the SOCKS proxy 
socks.wrapmodule(urllib2)

print urllib2.urlopen('http://www.google.com').read()

# other urllib2 requests to follow here..

Maybe my question is very simple: How can I unwrap the urllib2 module from the socks one, so as the following urllib2 requests to be made from localhost (without the proxy support) and maybe without set call the setdefaultproxy without arguments?

I tried to import the urllib2 lib again but nothing happened..

I see that it works fine after I call this:

setdefaultproxy()

But is this the right way?


Solution

  • Use my Socksipy branch with the urllib2 helper library here: https://github.com/Anorov/PySocks

    Example code, for your case:

    import socks, urllib2
    from sockshandler import SocksiPyHandler
    proxy_opener = urllib2.build_opener(SocksiPyHandler(socks.PROXY_TYPE_SOCKS5, "IP", 9050))
    print proxy_opener.open("http://whatismyip.org/").read()
    

    You can set different openers to use different proxies, or in your case, you can simply use a default urllib2 handler or urllib2.urlopen and it won't connect through the proxy.