Skip to content

Instantly share code, notes, and snippets.

@rgov
Created January 17, 2013 20:00
Show Gist options
  • Select an option

  • Save rgov/4559174 to your computer and use it in GitHub Desktop.

Select an option

Save rgov/4559174 to your computer and use it in GitHub Desktop.
import subprocess, tempfile
def which(name):
w = subprocess.Popen([ '/usr/bin/which', name ], stdout=subprocess.PIPE)
stdout, _ = w.communicate()
return stdout.rstrip()
class Tor(object):
'''
Spawns an instance of Tor.
'''
def __init__(self, socksport=9050, controlport=9051):
self.socksport, self.controlport = socksport, controlport
# Write out a temporary Tor configuration script
self.torconf = tempfile.NamedTemporaryFile()
self.torconf.write('ControlPort %i\n' % controlport)
self.torconf.write('SocksPort %i\n' % socksport)
self.torconf.write('DirReqStatistics 0\n')
self.torconf.write('AvoidDiskWrites 1\n')
self.torconf.write('RunAsDaemon 0\n')
self.tor = subprocess.Popen([
which('tor'),
'-f', self.torconf.name ])
def kill(self):
self.tor.kill()
class ProxyProxy(object):
'''
Spawns an instance of polipo that provides an HTTP proxy for our Tor instance.
'''
def __init__(self, httpport=8123, socksport=9050):
self.httpport, self.socksport = httpport, socksport
# We don't want polipo to cache anything at all
self.uncachable = tempfile.NamedTemporaryFile()
self.uncachable.write('.*\n')
self.polipo = subprocess.Popen([
which('polipo'),
'socksParentProxy=localhost:%i' % socksport,
'proxyPort=%i' % httpport,
'allowedClients=127.0.0.1',
'uncachableFile=%s' % self.uncachable.name,
'daemonise=false' ])
def kill(self):
self.polipo.kill()
if __name__ == '__main__':
import time
t = Tor()
p = ProxyProxy()
try:
while True:
time.sleep(60)
except KeyboardInterrupt:
t.kill()
p.kill()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment