本文整理汇总了Python中stem.control方法的典型用法代码示例。如果您正苦于以下问题:Python stem.control方法的具体用法?Python stem.control怎么用?Python stem.control使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类stem
的用法示例。
在下文中一共展示了stem.control方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _parse
# 需要导入模块: import stem [as 别名]
# 或者: from stem import control [as 别名]
def _parse(self):
self.path = tuple(stem.control._parse_circ_path(self.path))
if self.build_flags is not None:
self.build_flags = tuple(self.build_flags.split(','))
if self.created is not None:
try:
self.created = str_tools._parse_iso_timestamp(self.created)
except ValueError as exc:
raise stem.ProtocolError('Unable to parse create date (%s): %s' % (exc, self))
if not tor_tools.is_valid_circuit_id(self.id):
raise stem.ProtocolError("Circuit IDs must be one to sixteen alphanumeric characters, got '%s': %s" % (self.id, self))
self._log_if_unrecognized('status', stem.CircStatus)
self._log_if_unrecognized('build_flags', stem.CircBuildFlag)
self._log_if_unrecognized('purpose', stem.CircPurpose)
self._log_if_unrecognized('hs_state', stem.HiddenServiceState)
self._log_if_unrecognized('reason', stem.CircClosureReason)
self._log_if_unrecognized('remote_reason', stem.CircClosureReason)
示例2: from_port
# 需要导入模块: import stem [as 别名]
# 或者: from stem import control [as 别名]
def from_port(address = '127.0.0.1', port = 9051):
"""
Constructs a :class:`~stem.socket.ControlPort` based Controller.
:param str address: ip address of the controller
:param int port: port number of the controller
:returns: :class:`~stem.control.Controller` attached to the given port
:raises: :class:`stem.SocketError` if we're unable to establish a connection
"""
if not stem.util.connection.is_valid_ipv4_address(address):
raise ValueError('Invalid IP address: %s' % address)
elif not stem.util.connection.is_valid_port(port):
raise ValueError('Invalid port: %s' % port)
control_port = stem.socket.ControlPort(address, port)
return Controller(control_port)
示例3: get_ports
# 需要导入模块: import stem [as 别名]
# 或者: from stem import control [as 别名]
def get_ports(self, listener_type, default = UNDEFINED):
"""
get_ports(listener_type, default = UNDEFINED)
Provides the local ports where tor is listening for the given type of
connections. This is similar to
:func:`~stem.control.Controller.get_listeners`, but doesn't provide
addresses nor include non-local endpoints.
.. versionadded:: 1.2.0
:param stem.control.Listener listener_type: connection type being handled
by the ports we return
:param object default: response if the query fails
:returns: **list** of **ints** for the local ports where tor handles
connections of the given type
:raises: :class:`stem.ControllerError` if unable to determine the ports
and no default was provided
"""
return [port for (addr, port) in self.get_listeners(listener_type) if addr == '127.0.0.1']
示例4: get_socks_listeners
# 需要导入模块: import stem [as 别名]
# 或者: from stem import control [as 别名]
def get_socks_listeners(self, default = UNDEFINED):
"""
Provides the SOCKS **(address, port)** tuples that tor has open.
.. deprecated:: 1.2.0
Use :func:`~stem.control.Controller.get_listeners` with
**Listener.SOCKS** instead.
:param object default: response if the query fails
:returns: list of **(address, port)** tuples for the available SOCKS
listeners
:raises: :class:`stem.ControllerError` if unable to determine the listeners
and no default was provided
"""
return self.get_listeners(Listener.SOCKS, default)
示例5: _get_conf_dict_to_response
# 需要导入模块: import stem [as 别名]
# 或者: from stem import control [as 别名]
def _get_conf_dict_to_response(self, config_dict, default, multiple):
"""
Translates a dictionary of 'config key => [value1, value2...]' into the
return value of :func:`~stem.control.Controller.get_conf_map`, taking into
account what the caller requested.
"""
return_dict = {}
for key, values in list(config_dict.items()):
if values == []:
# config option was unset
if default != UNDEFINED:
return_dict[key] = default
else:
return_dict[key] = [] if multiple else None
else:
return_dict[key] = values if multiple else values[0]
return return_dict
示例6: get_control_data
# 需要导入模块: import stem [as 别名]
# 或者: from stem import control [as 别名]
def get_control_data(self, page_load_timeout, wait_on_page,
wait_after_closing_circuits,
additional_control_fields):
"""Gather metadata about the crawler instance."""
control_data = {}
# Configuration settings
control_data["page_load_timeout"] = page_load_timeout
control_data["wait_on_page"] = wait_on_page
control_data["wait_after_closing_circuits"] = \
wait_after_closing_circuits
if additional_control_fields:
control_data.update(additional_control_fields)
# System facts
control_data["kernel"] = platform.system()
control_data["kernel_version"] = platform.release()
control_data["os"] = platform.version()
control_data["python_version"] = platform.python_version()
ip = urlopen("https://api.ipify.org").read().decode()
control_data["ip"] = ip
# This API seems to be unstable and we haven't found a suitable
# alternative :(
try:
asn_geoip = urlopen("http://api.moocher.io/ip/{}".format(ip))
asn_geoip = literal_eval(asn_geoip.read().decode())
control_data["asn"] = asn_geoip.get("ip").get("as").get("asn")
control_data["city"] = asn_geoip.get("ip").get("city")
control_data["country"] = asn_geoip.get("ip").get("country")
except urllib.error.HTTPError:
self.logger.warning("Unable to query ASN API and thus some "
"control data may be missing from this run.")
control_data["tor_version"] = self.controller.get_version().version_str
control_data["tb_version"] = self.tb_driver.tb_version
# Tor will have multiple entry nodes in its state file, but will
# choose the first sequential one that is up as its entry guard.
entry_nodes = self.controller.get_info("entry-guards").split('\n')
control_data["entry_node"] = next(re.search("[0-9A-F]{40}", g).group(0)
for g in entry_nodes
if re.search("up", g))
control_data["crawler_version"] = _version
return control_data
示例7: make_ts_dir
# 需要导入模块: import stem [as 别名]
# 或者: from stem import control [as 别名]
def make_ts_dir(self, parent_dir=_log_dir, raw_dir_name="batch"):
"""Creates a timestamped folder to hold a group of traces."""
raw_dirpath = join(parent_dir, raw_dir_name)
ts = get_timestamp("log")
ts_dir = timestamp_file(raw_dirpath, ts, is_dir=True)
symlink_cur_to_latest(raw_dirpath, ts)
with open(join(ts_dir, "control.pickle"), "wb") as fh:
pickle.dump(self.control_data, fh)
return ts_dir
示例8: connect_port
# 需要导入模块: import stem [as 别名]
# 或者: from stem import control [as 别名]
def connect_port(address = '127.0.0.1', port = 9051, password = None, chroot_path = None, controller = stem.control.Controller):
"""
Convenience function for quickly getting a control connection. This is very
handy for debugging or CLI setup, handling setup and prompting for a password
if necessary (and none is provided). If any issues arise this prints a
description of the problem and returns **None**.
.. deprecated:: 1.2.0
Use :func:`~stem.connection.connect` instead.
:param str address: ip address of the controller
:param int port: port number of the controller
:param str password: passphrase to authenticate to the socket
:param str chroot_path: path prefix if in a chroot environment
:param Class controller: :class:`~stem.control.BaseController` subclass to be
returned, this provides a :class:`~stem.socket.ControlSocket` if **None**
:returns: authenticated control connection, the type based on the controller argument
"""
try:
control_port = stem.socket.ControlPort(address, port)
except stem.SocketError as exc:
print(exc)
return None
return _connect_auth(control_port, password, True, chroot_path, controller)
示例9: connect_socket_file
# 需要导入模块: import stem [as 别名]
# 或者: from stem import control [as 别名]
def connect_socket_file(path = '/var/run/tor/control', password = None, chroot_path = None, controller = stem.control.Controller):
"""
Convenience function for quickly getting a control connection. For more
information see the :func:`~stem.connection.connect_port` function.
In much the same vein as git porcelain commands, users should not rely on
details of how this works. Messages or details of this function's behavior
might change in the future.
.. deprecated:: 1.2.0
Use :func:`~stem.connection.connect` instead.
:param str path: path where the control socket is located
:param str password: passphrase to authenticate to the socket
:param str chroot_path: path prefix if in a chroot environment
:param Class controller: :class:`~stem.control.BaseController` subclass to be
returned, this provides a :class:`~stem.socket.ControlSocket` if **None**
:returns: authenticated control connection, the type based on the controller argument
"""
try:
control_socket = stem.socket.ControlSocketFile(path)
except stem.SocketError as exc:
print(exc)
return None
return _connect_auth(control_socket, password, True, chroot_path, controller)
示例10: _msg
# 需要导入模块: import stem [as 别名]
# 或者: from stem import control [as 别名]
def _msg(controller, message):
"""
Sends and receives a message with either a
:class:`~stem.socket.ControlSocket` or :class:`~stem.control.BaseController`.
"""
if isinstance(controller, stem.socket.ControlSocket):
controller.send(message)
return controller.recv()
else:
return controller.msg(message)
示例11: __init__
# 需要导入模块: import stem [as 别名]
# 或者: from stem import control [as 别名]
def __init__(self, controller):
self._received_events = []
code.InteractiveConsole.__init__(self, {
'stem': stem,
'stem.control': stem.control,
'controller': controller,
'events': self.get_events,
})
self._controller = controller
self._run_python_commands = True
# Indicates if we're processing a multiline command, such as conditional
# block or loop.
self.is_multiline_context = False
# Intercept events our controller hears about at a pretty low level since
# the user will likely be requesting them by direct 'SETEVENTS' calls.
handle_event_real = self._controller._handle_event
def handle_event_wrapper(event_message):
handle_event_real(event_message)
self._received_events.append(event_message)
self._controller._handle_event = handle_event_wrapper
示例12: __init__
# 需要导入模块: import stem [as 别名]
# 或者: from stem import control [as 别名]
def __init__(self, control_socket, is_authenticated = False):
self._socket = control_socket
self._msg_lock = threading.RLock()
self._status_listeners = [] # tuples of the form (callback, spawn_thread)
self._status_listeners_lock = threading.RLock()
# queues where incoming messages are directed
self._reply_queue = queue.Queue()
self._event_queue = queue.Queue()
# thread to continually pull from the control socket
self._reader_thread = None
# thread to pull from the _event_queue and call handle_event
self._event_notice = threading.Event()
self._event_thread = None
# saves our socket's prior _connect() and _close() methods so they can be
# called along with ours
self._socket_connect = self._socket._connect
self._socket_close = self._socket._close
self._socket._connect = self._connect
self._socket._close = self._close
self._last_heartbeat = 0.0 # timestamp for when we last heard from tor
self._is_authenticated = False
self._state_change_threads = [] # threads we've spawned to notify of state changes
if self._socket.is_alive():
self._launch_threads()
if is_authenticated:
self._post_authentication()
示例13: connect
# 需要导入模块: import stem [as 别名]
# 或者: from stem import control [as 别名]
def connect(self):
"""
Reconnects our control socket. This is a pass-through for our socket's
:func:`~stem.socket.ControlSocket.connect` method.
:raises: :class:`stem.SocketError` if unable to make a socket
"""
self._socket.connect()
示例14: add_status_listener
# 需要导入模块: import stem [as 别名]
# 或者: from stem import control [as 别名]
def add_status_listener(self, callback, spawn = True):
"""
Notifies a given function when the state of our socket changes. Functions
are expected to be of the form...
::
my_function(controller, state, timestamp)
The state is a value from the :data:`stem.control.State` enum. Functions
**must** allow for new values. The timestamp is a float for the unix time
when the change occurred.
This class only provides **State.INIT** and **State.CLOSED** notifications.
Subclasses may provide others.
If spawn is **True** then the callback is notified via a new daemon thread.
If **False** then the notice is under our locks, within the thread where
the change occurred. In general this isn't advised, especially if your
callback could block for a while. If still outstanding these threads are
joined on as part of closing this controller.
:param function callback: function to be notified when our state changes
:param bool spawn: calls function via a new thread if **True**, otherwise
it's part of the connect/close method call
"""
with self._status_listeners_lock:
self._status_listeners.append((callback, spawn))
示例15: _handle_event
# 需要导入模块: import stem [as 别名]
# 或者: from stem import control [as 别名]
def _handle_event(self, event_message):
"""
Callback to be overwritten by subclasses for event listening. This is
notified whenever we receive an event from the control socket.
:param stem.response.ControlMessage event_message: message received from
the control socket
"""
pass