Last active
December 15, 2017 15:22
-
-
Save coconut49/97c2914f41811cde03c663f95fa7e47b to your computer and use it in GitHub Desktop.
a python function, ask Tor change to a new IP. Usually use for small spider.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
import socket | |
def updateTorIP(host="127.0.0.1", port=9051, passwd="mypassword", torProxy="socks5://127.0.0.1:9050"): | |
if torProxy: | |
proxies = { | |
"http": torProxy, | |
"https": torProxy, | |
} | |
else: | |
proxies = {} | |
if not hasattr(updateTorIP, "iplists"): | |
updateTorIP.iplists = set() | |
def updateIP(): | |
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
s.connect((host, port)) | |
data = "authenticate \"{}\"\nsignal newnym\nquit\n".format(passwd) | |
resp = "250 OK\r\n250 OK\r\n250 closing connection\r\n" | |
s.send(data.encode()) | |
recv = s.recv(4096).decode() | |
# time.sleep(3) | |
if resp == recv: | |
return True | |
else: | |
print("Tor Error:"+recv) | |
return False | |
def getIP(): | |
try: | |
while True: | |
if not updateTorIP.iplists: # while the iplists is empty, process the First Address | |
print("[+] Testing proxy IP") | |
r = requests.get("https://api.ipify.org?format=json", proxies=proxies, verify=False) | |
print("[+] " + r.json()["ip"]) | |
updateTorIP.iplists.add(r.json()["ip"]) | |
updateIP() | |
print("[+] Testing proxy IP") | |
r = requests.get("https://api.ipify.org?format=json", proxies=proxies, verify=False) | |
print("[+] " + r.json()["ip"]) | |
if r.json()["ip"] not in updateTorIP.iplists: | |
updateTorIP.iplists.add(r.json()["ip"]) | |
print("[+] IP got") | |
break | |
except Exception as e: | |
updateIP() | |
print("[x] GetIP Error " + str(e)) | |
getIP() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment