本文整理汇总了Python中stem.control.Controller.from_socket_file方法的典型用法代码示例。如果您正苦于以下问题:Python Controller.from_socket_file方法的具体用法?Python Controller.from_socket_file怎么用?Python Controller.from_socket_file使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类stem.control.Controller
的用法示例。
在下文中一共展示了Controller.from_socket_file方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: gen_controller
# 需要导入模块: from stem.control import Controller [as 别名]
# 或者: from stem.control.Controller import from_socket_file [as 别名]
def gen_controller():
connect_method = os.environ.get('connectmethod', 'port')
if connect_method == 'port':
return Controller.from_port(port=os.environ.get('port', 9051))
elif connect_method == 'socket':
return Controller.from_socket_file(path=os.environ.get('socket', '/var/run/tor/control'))
else:
print("env.connectmethod contains an invalid value. Please specify either 'port' or 'socket'.", file=sys.stderr)
sys.exit(-1)
示例2: _on_connect
# 需要导入模块: from stem.control import Controller [as 别名]
# 或者: from stem.control.Controller import from_socket_file [as 别名]
def _on_connect(self):
try:
self._control = Controller.from_port()
except SocketError:
try:
self._control = Controller.from_socket_file()
except SocketError:
self._status_icon.set_tooltip_text('Failed to initialize stem')
return True
self._control.add_status_listener(self._on_status)
self._status_icon.set_tooltip_text('Stem: Authenticating')
GLib.timeout_add_seconds(1, self._on_auth)
return False
示例3: handleKey
# 需要导入模块: from stem.control import Controller [as 别名]
# 或者: from stem.control.Controller import from_socket_file [as 别名]
def handleKey(self, key):
isKeystrokeConsumed = True
if key in (ord('n'), ord('N')) and torTools.getConn().isNewnymAvailable():
self.sendNewnym()
elif key in (ord('r'), ord('R')) and not self._isTorConnected:
controller = None
allowPortConnection, allowSocketConnection, _ = starter.allowConnectionTypes()
if os.path.exists(self._config["startup.interface.socket"]) and allowSocketConnection:
try:
# TODO: um... what about passwords?
controller = Controller.from_socket_file(self._config["startup.interface.socket"])
controller.authenticate()
except (IOError, stem.SocketError), exc:
controller = None
if not allowPortConnection:
cli.popups.showMsg("Unable to reconnect (%s)" % exc, 3)
elif not allowPortConnection:
cli.popups.showMsg("Unable to reconnect (socket '%s' doesn't exist)" % self._config["startup.interface.socket"], 3)
if not controller and allowPortConnection:
# TODO: This has diverged from starter.py's connection, for instance it
# doesn't account for relative cookie paths or multiple authentication
# methods. We can't use the starter.py's connection function directly
# due to password prompts, but we could certainly make this mess more
# manageable.
try:
ctlAddr, ctlPort = self._config["startup.interface.ipAddress"], self._config["startup.interface.port"]
controller = Controller.from_port(ctlAddr, ctlPort)
try:
controller.authenticate()
except stem.connection.MissingPassword:
controller.authenticate(authValue) # already got the password above
except Exception, exc:
controller = None
示例4: allowConnectionTypes
# 需要导入模块: from stem.control import Controller [as 别名]
# 或者: from stem.control.Controller import from_socket_file [as 别名]
sys.exit()
# By default attempts to connect using the control socket if it exists. This
# skips attempting to connect by socket or port if the user has given
# arguments for connecting to the other.
controller = None
allowPortConnection, allowSocketConnection, allowDetachedStart = allowConnectionTypes()
socketPath = param["startup.interface.socket"]
if os.path.exists(socketPath) and allowSocketConnection:
try:
# TODO: um... what about passwords?
# https://trac.torproject.org/6881
controller = Controller.from_socket_file(socketPath)
controller.authenticate()
except IOError, exc:
if not allowPortConnection:
print "Unable to use socket '%s': %s" % (socketPath, exc)
elif not allowPortConnection:
print "Socket '%s' doesn't exist" % socketPath
if not controller and allowPortConnection:
# sets up stem connection, prompting for the passphrase if necessary and
# sending problems to stdout if they arise
authPassword = config.get("startup.controlPassword", CONFIG["startup.controlPassword"])
incorrectPasswordMsg = "Password found in '%s' was incorrect" % configPath
controller = _getController(controlAddr, controlPort, authPassword, incorrectPasswordMsg, not allowDetachedStart)
# removing references to the controller password so the memory can be freed
示例5: connect
# 需要导入模块: from stem.control import Controller [as 别名]
# 或者: from stem.control.Controller import from_socket_file [as 别名]
#.........这里部分代码省略.........
elif self.settings.get('tor_bridges_use_meek_lite_azure'):
f.write('ClientTransportPlugin meek_lite exec {}\n'.format(self.obfs4proxy_file_path))
with open(common.get_resource_path('torrc_template-meek_lite_azure')) as o:
for line in o:
f.write(line)
if self.settings.get('tor_bridges_use_custom_bridges'):
if 'obfs4' in self.settings.get('tor_bridges_use_custom_bridges'):
f.write('ClientTransportPlugin obfs4 exec {}\n'.format(self.obfs4proxy_file_path))
elif 'meek_lite' in self.settings.get('tor_bridges_use_custom_bridges'):
f.write('ClientTransportPlugin meek_lite exec {}\n'.format(self.obfs4proxy_file_path))
f.write(self.settings.get('tor_bridges_use_custom_bridges'))
f.write('\nUseBridges 1')
# Execute a tor subprocess
start_ts = time.time()
if self.system == 'Windows':
# In Windows, hide console window when opening tor.exe subprocess
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
self.tor_proc = subprocess.Popen([self.tor_path, '-f', self.tor_torrc], stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo)
else:
self.tor_proc = subprocess.Popen([self.tor_path, '-f', self.tor_torrc], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# Wait for the tor controller to start
time.sleep(2)
# Connect to the controller
try:
if self.system == 'Windows':
self.c = Controller.from_port(port=self.tor_control_port)
self.c.authenticate()
else:
self.c = Controller.from_socket_file(path=self.tor_control_socket)
self.c.authenticate()
except Exception as e:
raise BundledTorBroken(strings._('settings_error_bundled_tor_broken', True).format(e.args[0]))
while True:
try:
res = self.c.get_info("status/bootstrap-phase")
except SocketClosed:
raise BundledTorCanceled()
res_parts = shlex.split(res)
progress = res_parts[2].split('=')[1]
summary = res_parts[4].split('=')[1]
# "\033[K" clears the rest of the line
print("{}: {}% - {}{}".format(strings._('connecting_to_tor'), progress, summary, "\033[K"), end="\r")
if callable(tor_status_update_func):
if not tor_status_update_func(progress, summary):
# If the dialog was canceled, stop connecting to Tor
common.log('Onion', 'connect', 'tor_status_update_func returned false, canceling connecting to Tor')
print()
return False
if summary == 'Done':
print("")
break
time.sleep(0.2)
# If using bridges, it might take a bit longer to connect to Tor
if self.settings.get('tor_bridges_use_custom_bridges') or \
self.settings.get('tor_bridges_use_obfs4') or \
示例6: in
# 需要导入模块: from stem.control import Controller [as 别名]
# 或者: from stem.control.Controller import from_socket_file [as 别名]
#import re
import platform
from influxdb import InfluxDBClient
from stem.control import EventType, Controller
INFLUXDB_HOST = "influxdb1"
INFLUXDB_PORT = 8086
INFLUXDB_USER = "user"
INFLUXDB_PASSWORD = "password"
INFLUXDB_DATABASE = "tor"
with Controller.from_socket_file() as controller:
controller.authenticate()
# p = re.compile('(?P<read>\d+)\,(?P<write>\d+)$')
bytes_read = controller.get_info("traffic/read")
bytes_written = controller.get_info("traffic/written")
bandwidth = controller.get_info("bw-event-cache")
#m = p.search(bandwidth)
tx = 0
rx = 0
i = 0
for value in (bandwidth.split(' '))[-60:]:
value_split = value.split(',')
rx += int(value_split[0])
tx += int(value_split[1])
i += 1
rx /= i
tx /= i
示例7: getenv
# 需要导入模块: from stem.control import Controller [as 别名]
# 或者: from stem.control.Controller import from_socket_file [as 别名]
#!/usr/bin/python
from stem.control import Controller
from os import getenv
from re import match
PORT = getenv('TORCONTROL')
try:
controller = Controller.from_socket_file(path=PORT)
except:
try:
controller = Controller.from_port(port=int(PORT))
except:
try:
controller = Controller.from_port(address=PORT)
except:
if not PORT:
print 'Failed to connect to TORCONTROL=%s' % PORT
raise SystemExit(1)
res = match('([^/:]*):([0-9]*)$', PORT).groups()
if res[0]:
if res[1]:
controller = Controller.from_port(address=res[0],port=int(res[1]))
else:
controller = Controller.from_port(address=res[0])
else:
controller = Controller.from_port(port=int(res[1]))
controller.authenticate()
if __name__ == '__main__':
示例8: main
# 需要导入模块: from stem.control import Controller [as 别名]
# 或者: from stem.control.Controller import from_socket_file [as 别名]
def main():
"""
Entry point when invoked over the command line.
"""
setproctitle('onionbalance')
args = parse_cmd_args().parse_args()
config_file_options = settings.parse_config_file(args.config)
# Update global configuration with options specified in the config file
for setting in dir(config):
if setting.isupper() and config_file_options.get(setting):
setattr(config, setting, config_file_options.get(setting))
# Override the log level if specified on the command line.
if args.verbosity:
config.LOG_LEVEL = args.verbosity.upper()
# Write log file if configured in environment variable or config file
if config.LOG_LOCATION:
log.setup_file_logger(config.LOG_LOCATION)
logger.setLevel(logging.__dict__[config.LOG_LEVEL.upper()])
# Create a connection to the Tor unix domain control socket or control port
try:
tor_socket = (args.socket or config.TOR_CONTROL_SOCKET)
tor_address = (args.ip or config.TOR_ADDRESS)
tor_port = (args.port or config.TOR_PORT)
try:
controller = Controller.from_socket_file(path=tor_socket)
logger.debug("Successfully connected to the Tor control socket "
"%s.", tor_socket)
except stem.SocketError:
logger.debug("Unable to connect to the Tor control socket %s.",
tor_socket)
controller = Controller.from_port(address=tor_address,
port=tor_port)
logger.debug("Successfully connected to the Tor control port.")
except stem.SocketError as exc:
logger.error("Unable to connect to Tor control socket or port: %s",
exc)
sys.exit(1)
try:
controller.authenticate(password=config.TOR_CONTROL_PASSWORD)
except stem.connection.AuthenticationFailure as exc:
logger.error("Unable to authenticate on the Tor control connection: "
"%s", exc)
sys.exit(1)
else:
logger.debug("Successfully authenticated on the Tor control "
"connection.")
status_socket = status.StatusSocket(config.STATUS_SOCKET_LOCATION)
eventhandler.SignalHandler(controller, status_socket)
# Disable no-member due to bug with "Instance of 'Enum' has no * member"
# pylint: disable=no-member
# Check that the Tor client supports the HSPOST control port command
if not controller.get_version() >= stem.version.Requirement.HSPOST:
logger.error("A Tor version >= %s is required. You may need to "
"compile Tor from source or install a package from "
"the experimental Tor repository.",
stem.version.Requirement.HSPOST)
sys.exit(1)
# Load the keys and config for each onion service
settings.initialize_services(controller,
config_file_options.get('services'))
# Finished parsing all the config file.
handler = eventhandler.EventHandler()
controller.add_event_listener(handler.new_status,
EventType.STATUS_GENERAL)
controller.add_event_listener(handler.new_desc,
EventType.HS_DESC)
controller.add_event_listener(handler.new_desc_content,
EventType.HS_DESC_CONTENT)
# Schedule descriptor fetch and upload events
scheduler.add_job(config.REFRESH_INTERVAL, fetch_instance_descriptors,
controller)
scheduler.add_job(config.PUBLISH_CHECK_INTERVAL, publish_all_descriptors)
# Run initial fetch of HS instance descriptors
scheduler.run_all(delay_seconds=config.INITIAL_DELAY)
# Begin main loop to poll for HS descriptors
scheduler.run_forever()
return 0