Search code examples
pythonproxyiptor

IP remains unchanged


I am trying to connect to Tor by code and change my identity. The results that I have gotten so far are that I connect successfully but can't change my identity. Here is my code :

import socket
import socks
import httplib

def connectTor():
    socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5,"127.0.0.1",9150,True)
    socket.socket = socks.socksocket

def newIdentity():
    socks.setdefaultproxy()

    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    s.connect(("127.0.0.1",9151))   
    s.send("AUTHENTICATE\r\n")

    response = s.recv(128)

    if response.startswith("250"):
        s.send("SIGNAL NEWNYM\r\n")

    s.close()    
    connectTor()

def showIP():
    conn = httplib.HTTPConnection("my-ip.herokuapp.com")
    conn.request("GET","/")
    response = conn.getresponse()
    print (response.read())

def main():
    connectTor()    
    print("Connected to Tor")    
    showIP()    

    print("Hew Id is")
    newIdentity()
    showIP()

main() 

Any help or advice is appreciated.


Solution

  • If you are using a unix based OS you can use subprocess and killall with HUP to create a new identity:

    url = 'http://my-ip.heroku.com'
    import socks
    import socket
    socks.set_default_proxy(socks.SOCKS5, "localhost", 9050)
    socket.socket = socks.socksocket
    import requests
    res = requests.get(url)
    response = res.content
    print(response)
    
    from subprocess import check_call
    
    check_call(["killall","-HUP", "tor"])
    
    res = requests.get(url)
    response = res.content
    print(response)
    
    In [2]: paste
    url = 'http://my-ip.heroku.com'
    import socks
    import socket
    socks.set_default_proxy(socks.SOCKS5, "localhost", 9050)
    socket.socket = socks.socksocket
    import requests
    res = requests.get(url)
    response = res.content
    print(response)
    
    from subprocess import check_call
    
    check_call(["killall","-HUP", "tor"])
    
    res = requests.get(url)
    response = res.content
    print(response)
    
    ## -- End pasted text --
    94.242....
    
    95.130....