Stem Docs

Control Socket

Control Socket

Supports communication with sockets speaking Tor protocols. This allows us to send messages as basic strings, and receive responses as ControlMessage instances.

This module only consists of low level components, and is not intended for users. See our tutorials and Control Module if you’re new to Stem and looking to get started.

With that aside, these can still be used for raw socket communication with Tor…

import stem
import stem.connection
import stem.socket

if __name__ == '__main__':
  try:
    control_socket = stem.socket.ControlPort(port = 9051)
    stem.connection.authenticate(control_socket)
  except stem.SocketError as exc:
    print 'Unable to connect to tor on port 9051: %s' % exc
    sys.exit(1)
  except stem.connection.AuthenticationFailure as exc:
    print 'Unable to authenticate: %s' % exc
    sys.exit(1)

  print "Issuing 'GETINFO version' query...\n"
  control_socket.send('GETINFO version')
  print control_socket.recv()
% python example.py
Issuing 'GETINFO version' query...

version=0.2.4.10-alpha-dev (git-8be6058d8f31e578)
OK

Module Overview:

BaseSocket - Thread safe socket.
  |- RelaySocket - Socket for a relay's ORPort.
  |  |- send - sends a message to the socket
  |  +- recv - receives a response from the socket
  |
  |- ControlSocket - Socket wrapper that speaks the tor control protocol.
  |  |- ControlPort - Control connection via a port.
  |  |- ControlSocketFile - Control connection via a local file socket.
  |  |
  |  |- send - sends a message to the socket
  |  +- recv - receives a ControlMessage from the socket
  |
  |- is_alive - reports if the socket is known to be closed
  |- is_localhost - returns if the socket is for the local system or not
  |- connection_time - timestamp when socket last connected or disconnected
  |- connect - connects a new socket
  |- close - shuts down the socket
  +- __enter__ / __exit__ - manages socket connection

send_message - Writes a message to a control socket.
recv_message - Reads a ControlMessage from a control socket.
send_formatting - Performs the formatting expected from sent messages.