We use PySocks to communicate via the urllib2 module via Tor to provide anonymity.
However, what should I do if I only want to run a function (using urllib2) through Tor?
Is it possible to initialize urllib2.socket.socket and return it to communication without going through the original Tor?
Thank you for your guidance.
socks.setdefaultproxy (socks.PROXY_TYPE_SOCKS5, '127.0.0.1', 9050)
urllib2.socket.socket=socks.socksocket
import socket
original_socket=socket.socket
...
socks.setdefaultproxy(...)
socket.socket=socks.socksocket
...
socket.socket=original_socket
urllib2.a_function()
socket.socket=socks.socksocket
All you have to do is save the original socket.socket
and reset it as needed.Depending on how you create your program, you might want to surround it with try
through finally
to ensure that any exceptions occur.
© 2024 OneMinuteCode. All rights reserved.