Table of Contents

About

There are times when you may need to issue a command to various tor servers you have set-up in order to renew the identity such that the tor servers build a new circuit. The following takes as input various configured servers at the top and then batch-issues a renew request.

Setup

For each server, you will have to edit tor's configuration (usually found at /etc/tor/torrc) in order to open up the control port and specify a password that can be used to control tor. For example, the configuration:

ControlPort 9151
ControlListenAddress 192.168.1.1:9151
HashedControlPassword 16:46E8910318E774FE60093EBECD3579F35CA66435F1C8946C242E7B4F2A

will:

In order to generate a password hash to replace 16:46E8910318E774FE60093EBECD3579F35CA66435F1C8946C242E7B4F2A with your password, you can issue:

tor --hash-password password

where password is a plain-text password that can then be entered in the script below.

Code

tor-renew.py
#!/usr/bin/python
###########################################################################
##  Copyright (C) Wizardry and Steamworks 2015 - License: GNU GPLv3      ##
##  Please see: http://www.gnu.org/licenses/gpl.html for legal details,  ##
##  rights of fair usage, the disclaimer and warranty conditions.        ##
###########################################################################
 
########################### Configuration #################################
 
# Add servers to this following the format in-sequence:
# server name, server port, password
TOR_SERVERS = [ 
    [ 'tor1.server', 9151, 'password' ],
    [ 'tor2.server', 9151, 'password' ]
]
 
###########################################################################
 
import os
import socket
 
def renewTorIdentity(host, port, password):
    try: 
        s = socket.socket() 
        s.connect((host, port)) 
 
        s.send('AUTHENTICATE "' + password + '"' + os.linesep) 
        resp = s.recv(1024) 
 
        if not resp.startswith('250'):
            raise Exception(resp)
 
        s.send("SIGNAL NEWNYM" + os.linesep) 
 
        resp = s.recv(1024) 
 
        if not resp.startswith('250'): 
            raise Exception(resp); 
 
        s.send("QUIT" + os.linesep)
 
        if not resp.startswith('250'): 
            raise Exception(resp);
 
    except: 
        raise
 
for server in TOR_SERVERS:
    try:
        renewTorIdentity(server[0], server[1], server[2]);
    except Exception as e:
        print "Unable to renew identity of", server[0], "due to:", e