Good day. I already broke my head with the question "restart the tor service" using python. I tried to do this like this:

subprocess.Popen('/etc/init.d/tor restart', shell=True, stdout=subprocess.PIPE) 

and so

 subprocess.Popen('service tor restart', shell=True) 

It seems like the reboot process is going on, but the hostname and private_key files do not appear in the tor domain settings directory. If I produce the service tor restart command itself through the console, files appear. What could be the problem? Thank you in advance.

  • Python from the root run though? Is python waiting for the command to complete? - andreymal
  • From the root. Yes, it is worth the wait () - Corle
  • Which is very interesting, if you run python and enter commands there, it works. How it happens at all - Corle

1 answer 1

I use such code (I was pulled from somewhere with github, but I don’t remember where it came from).

 from commands import getoutput from subprocess import call, check_call, CalledProcessError from json import load from urllib2 import urlopen, URLError from os import devnull from time import sleep from sys import stdout, stderr def restart_tor(): fnull = open(devnull, 'w') try: tor_restart = check_call( ["service", "tor", "restart"], stdout=fnull, stderr=fnull) if tor_restart is 0: print(" {0}".format( "[\033[92m+\033[0m] Anonymizer status \033[92m[ON]\033[0m")) print(" {0}".format( "[\033[92m*\033[0m] Getting public IP, please wait...")) retries = 0 my_public_ip = None while retries < 12 and not my_public_ip: retries += 1 try: my_public_ip = load(urlopen('http://jsonip.com/'))['ip'] except URLError: sleep(5) print(" [\033[93m?\033[0m] Still waiting for IP address...") print if not my_public_ip: my_public_ip = getoutput('wget -qO - v4.ifconfig.co') if not my_public_ip: exit(" \033[91m[!]\033[0m Can't get public ip address!") print(" {0}".format("[\033[92m+\033[0m] Your IP is \033[92m%s\033[0m" % my_public_ip)) except CalledProcessError as err: print("\033[91m[!] Command failed: %s\033[0m" % ' '.join(err.cmd)) if __name__ == '__main__': restart_tor()