tor-control.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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_SETEVENTS = 0x0005
  9. MSG_TYPE_AUTH = 0x0007
  10. EVENT_TYPE_BANDWIDTH = 0x0004
  11. EVENT_TYPE_WARN = 0x0005
  12. def parseHostAndPort(h):
  13. host, port = "localhost", 9051
  14. if ":" in h:
  15. i = h.index(":")
  16. host = h[:i]
  17. try:
  18. port = int(h[i+1:])
  19. except ValueError:
  20. print "Bad hostname %r"%h
  21. sys.exit(1)
  22. elif h:
  23. try:
  24. port = int(h)
  25. except ValueError:
  26. host = h
  27. return host, port
  28. def receive_message(s):
  29. body = ""
  30. header = s.recv(4)
  31. length,type = struct.unpack("!HH",header)
  32. print "Got response length %d, type %d"%(length,type)
  33. if length:
  34. body = s.recv(length)
  35. print "Got response length %d, type %d, body %s"%(length,type,body)
  36. return length,type,body
  37. def pack_message(type, body=""):
  38. length = len(body)
  39. reqheader = struct.pack("!HH", length, type)
  40. return "%s%s"%(reqheader,body)
  41. def authenticate(s):
  42. s.sendall(pack_message(MSG_TYPE_AUTH))
  43. length,type,body = receive_message(s)
  44. return
  45. def get_option(s,name):
  46. s.sendall(pack_message(MSG_TYPE_GETCONF,name))
  47. length,type,body = receive_message(s)
  48. return
  49. def set_option(s,msg):
  50. s.sendall(pack_message(MSG_TYPE_SETCONF,msg))
  51. length,type,body = receive_message(s)
  52. return
  53. def get_event(s,events):
  54. eventbody = struct.pack("!H", events)
  55. s.sendall(pack_message(MSG_TYPE_SETEVENTS,eventbody))
  56. length,type,body = receive_message(s)
  57. return
  58. def listen_for_events(s):
  59. while(1):
  60. length,type,body = receive_message(s)
  61. return
  62. def do_main_loop(host,port):
  63. print "host is %s:%d"%(host,port)
  64. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  65. s.connect((host,port))
  66. authenticate(s)
  67. get_option(s,"nickname")
  68. get_option(s,"DirFetchPostPeriod\n")
  69. set_option(s,"1")
  70. set_option(s,"bandwidthburstbytes 100000")
  71. # set_option(s,"runasdaemon 1")
  72. # get_event(s,EVENT_TYPE_WARN)
  73. get_event(s,EVENT_TYPE_BANDWIDTH)
  74. listen_for_events(s)
  75. return
  76. if __name__ == '__main__':
  77. if len(sys.argv) != 2:
  78. print "Syntax: tor-control.py torhost:torport"
  79. sys.exit(0)
  80. sh,sp = parseHostAndPort(sys.argv[1])
  81. do_main_loop(sh,sp)