tor-control.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #!/usr/bin/python2
  2. #$Id$
  3. import socket
  4. import struct
  5. import sys
  6. MSG_TYPE_SETCONF = 0x0002
  7. MSG_TYPE_GETCONF = 0x0003
  8. MSG_TYPE_AUTH = 0x0007
  9. def parseHostAndPort(h):
  10. host, port = "localhost", 9051
  11. if ":" in h:
  12. i = h.index(":")
  13. host = h[:i]
  14. try:
  15. port = int(h[i+1:])
  16. except ValueError:
  17. print "Bad hostname %r"%h
  18. sys.exit(1)
  19. elif h:
  20. try:
  21. port = int(h)
  22. except ValueError:
  23. host = h
  24. return host, port
  25. def receive_message(s):
  26. body = ""
  27. header = s.recv(4)
  28. length,type = struct.unpack("!HH",header)
  29. print "Got response length %d, type %d"%(length,type)
  30. if length:
  31. body = s.recv(length)
  32. print "Got response length %d, type %d, body %s"%(length,type,body)
  33. return length,type,body
  34. def pack_message(type, body=""):
  35. length = len(body)
  36. reqheader = struct.pack("!HH", length, type)
  37. return "%s%s"%(reqheader,body)
  38. def authenticate(s):
  39. s.sendall(pack_message(MSG_TYPE_AUTH))
  40. length,type,body = receive_message(s)
  41. return
  42. def get_option(s,name):
  43. s.sendall(pack_message(MSG_TYPE_GETCONF,name))
  44. length,type,body = receive_message(s)
  45. return
  46. def do_main_loop(host,port):
  47. print "host is %s:%d"%(host,port)
  48. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  49. s.connect((host,port))
  50. authenticate(s)
  51. get_option(s,"nickname")
  52. # get_option(s,"DirFetchPostPeriod\n")
  53. return
  54. if __name__ == '__main__':
  55. if len(sys.argv) != 2:
  56. print "Syntax: tor-control.py torhost:torport"
  57. sys.exit(0)
  58. sh,sp = parseHostAndPort(sys.argv[1])
  59. do_main_loop(sh,sp)