Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
TOR con Python y cambiar circuito programáticamente
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
import socks
# pip install pysocks
import socket
import requests
# pip install requests
import traceback
socketNoProxy = None
def changeTorCircuit():
# /etc/tor/torrc
# ControlPort 9051
# CookieAuthentication 0
result = False
try:
socket.socket = socketNoProxy
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("127.0.0.1", 9051))
s.send("AUTHENTICATE\n")
if "250 OK" in s.recv(128):
s.send("SIGNAL NEWNYM\n")
if "250 OK" in s.recv(128):
s.send("quit\n")
result = True
time.sleep(10)
except Exception as e:
print "Exception: " + str(e) + "\n" + str(traceback.format_exc())
finally:
s.close()
return result
def setTor():
socks.setdefaultproxy(proxy_type=socks.PROXY_TYPE_SOCKS5, addr="127.0.0.1", port=9050)
socket.socket = socks.socksocket
def checkIP():
r = requests.get('http://myexternalip.com/raw')
return r.text
def main():
# Establecemos proxy para que todo el tráfico pase TOR
setTor()
# Obtenemos ip de salida
print checkIP()
# Cambiamos circuito TOR para salir por otra IP
changeTorCircuit()
# ...
setTor()
print checkIP()
changeTorCircuit()
setTor()
print checkIP()
changeTorCircuit()
setTor()
print checkIP()
changeTorCircuit()
setTor()
print checkIP()
# Guardamos socket por defecto sin proxy
socketNoProxy = socket.socket
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.