/weather/TorCtl/trunk/python/TorExample.py

https://github.com/mvitale/Tor-Weather-Django · Python · 160 lines · 139 code · 5 blank · 16 comment · 8 complexity · 8ae3a38b81e58d821b82a4250dfa3c20 MD5 · raw file

  1. #!/usr/bin/python
  2. # TorExample.py -- Python module to demonstrate tor controller functionality.
  3. # Copyright 2005 Nick Mathewson -- See LICENSE for licensing information.
  4. #$Id: TorExample.py 15746 2008-07-08 05:07:19Z mikeperry $
  5. """\
  6. Usage:
  7. TorExample.py <parameters> <command list>
  8. Parameters:
  9. --host <hostname>:<port#> defaults to "localhost:9100"
  10. --verbose | -v turn on verbose messages
  11. Commands:
  12. set_config <config key>=<config value> [<config key>=<config value> ...]
  13. get_config <config key> [<config key> ...]
  14. get_info <info key> [<info key> ...]
  15. listen <event name>
  16. signal <signal name>
  17. auth_demo <auth token>
  18. For example, to listen for any error messages do:
  19. python TorExample listen ERR"""
  20. import socket
  21. import sys
  22. from TorCtl import *
  23. def getConnection(daemon=1):
  24. """
  25. getConnection tries to open a socket to the tor server.
  26. If a socket is established, and the daemon paramter is True (the default),
  27. a thread is spawned to handle the communcation between us and the tor server.
  28. """
  29. hostport = "localhost:9051"
  30. verbose = 0
  31. while sys.argv[1][0] == '-':
  32. if sys.argv[1] == '--host':
  33. hostport = sys.argv[2]
  34. del sys.argv[1:3]
  35. elif sys.argv[1].startswith("--host="):
  36. hostport = sys.argv[1][7:]
  37. del sys.argv[1]
  38. elif sys.argv[1] in ('-v', '--verbose'):
  39. verbose = 1
  40. del sys.argv[1]
  41. host,port = TorCtl.parseHostAndPort(hostport)
  42. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  43. try:
  44. s.connect((host,port))
  45. except socket.error, e:
  46. print "Connection failed: %s. Is the ControlPort enabled?"%e
  47. sys.exit(1)
  48. conn = TorCtl.Connection(s)
  49. if verbose and hasattr(conn, "debug"):
  50. conn.debug(sys.stdout)
  51. th = conn.launch_thread(daemon)
  52. conn.authenticate("handsoffmytor")
  53. return conn
  54. def run():
  55. """
  56. Locate the member function named on the command line and call it.
  57. The function is located by pre-pending 'run_' to the parameter
  58. and looking for that named item in the python globals() list.
  59. """
  60. if len(sys.argv)<2:
  61. print "No command given."
  62. print __doc__
  63. return
  64. for idx in xrange(1, len(sys.argv)):
  65. arg = sys.argv[idx]
  66. cmd = arg.replace("-","_")
  67. fn = globals().get("run_"+cmd)
  68. if fn != None:
  69. del sys.argv[idx]
  70. break
  71. if fn is None:
  72. print "Unrecognized command:",sys.argv[1]
  73. print __doc__
  74. return
  75. try:
  76. fn()
  77. except TorCtl.ErrorReply, e:
  78. print "Request failed: %s"%e
  79. def run_set_config():
  80. """
  81. walk thru the config key=value pairs present on the command line
  82. and pass them to the tor server. If the --save option is present,
  83. tell the tor server to flush the config to disk
  84. """
  85. conn = getConnection()
  86. if sys.argv[1] == '--save':
  87. save = 1
  88. del sys.argv[1]
  89. else:
  90. save = 0
  91. kvList = []
  92. for i in xrange(1, len(sys.argv), 2):
  93. kvList.append((sys.argv[i], sys.argv[i+1]))
  94. conn.set_options(kvList)
  95. if save:
  96. conn.save_conf()
  97. def run_get_config():
  98. """
  99. pass the given configuration key names to the tor server and receive their current values
  100. """
  101. conn = getConnection()
  102. opts = conn.get_option(sys.argv[1:])
  103. for k,v in opts:
  104. print "KEY:",k
  105. print "VALUE:",v
  106. def run_get_info():
  107. """
  108. pass the given info key names to the tor server and receive their current values
  109. """
  110. conn = getConnection()
  111. opts = conn.get_info(sys.argv[1:])
  112. for k in sys.argv[1:]:
  113. print "KEY:",k
  114. print "VALUE:",opts.get(k)
  115. def run_listen():
  116. """
  117. pass to the tor server the given event name to listen for
  118. NOTE: after this command the example client will just loop
  119. and print any passed event items - you will have to kill it
  120. in order to stop it
  121. """
  122. conn = getConnection(daemon=0)
  123. print "listening!"
  124. conn.set_event_handler(TorCtl.DebugEventHandler())
  125. conn.set_events(sys.argv[1:])
  126. def run_signal():
  127. """
  128. pass to the tor server the given signal
  129. """
  130. conn = getConnection()
  131. if len(sys.argv)<2:
  132. print "Syntax: signal [signal]"
  133. return
  134. conn.send_signal(sys.argv[1])
  135. def run_authdemo():
  136. """
  137. connect to the tor server and authenticate
  138. """
  139. conn = getConnection()
  140. conn.close()
  141. #XXXX
  142. if __name__ == '__main__':
  143. run()