本文整理汇总了Python中stem.control.Controller类的典型用法代码示例。如果您正苦于以下问题:Python Controller类的具体用法?Python Controller怎么用?Python Controller使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Controller类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: gen_controller
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
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: change_ipadress
def change_ipadress(passphrase="your_TORsoftware_password", sleep=1) :
with Controller.from_port(port = 9051) as controller:
controller.authenticate(passphrase)
controller.signal(Signal.NEWNYM)
#we wait here but you can eventually skip this part or set it in place to
#gain controle over time.
time.sleep(sleep)
示例4: renew
def renew(self):
'''Signal TOR for a new connection
thanks http://stackoverflow.com/questions/30286293/
make-requests-using-python-over-tor
and https://gist.github.com/
KhepryQuixote/46cf4f3b999d7f658853'''
SLEEPSECS = 1
SESSION = self.Session()
old_ip = check_ip(SESSION)
# we don't want a CCC because it closes tor process by default :)
with Controller.from_port(port=self.CONTROL_PORT) \
as controller:
controller.authenticate(password=self.PASSWORD)
controller.signal(Signal.NEWNYM)
new_ip = check_ip(SESSION)
seconds = 0
while old_ip == new_ip:
# sleep this thread for the specified duration
sleep(SLEEPSECS)
# track the elapsed seconds
seconds += SLEEPSECS
# obtain the current IP address
new_ip = check_ip(SESSION)
# signal that the program is still awaiting a different IP address
print("%d seconds elapsed awaiting a different IP address."
% seconds)
示例5: checkTor
def checkTor():
if not controller.isAlive():
print "tor controller was dead, now trying to restart it"
try:
controller = Controller.from_port()
controller.authenticate()
except Exception as e:
print e
print "tor is not letting us authenticate, is it configured correctly and running?"
exit()
print "successfully opened control connection to tor"
#TODO here and elsewhere we should change from the get_conf/set_options
#interface to the create_ephemeral_hidden_service/
#remove_ephemeral_hidden_service/list_ephemeral_hidden_services
#that way we can also put the key and hostname in config and not have to
#worry about setting up /var/lib/tor/hidden_service
if controller.get_conf("HiddenServiceDir") is None:
print "tor was not configure to provide a hidden service, now configuring"
try:
controller.set_options([
("HiddenServiceDir", get_hidden_svc_dir()),
("HiddenServicePort", "80 %s:%s" % (host, str(port)))
])
except Exception as e:
print "unable to create hidden service"
print e
quit()
示例6: main
def main():
"""
The scanner's entry point.
"""
stats = Statistics()
args = parseCmdArgs()
logger.debug("Command line arguments: %s" % str(args))
torProc = bootstrapTor()
torCtrl = Controller.from_port(port = const.TOR_CONTROL_PORT)
stem.connection.authenticate_none(torCtrl)
# Redirect Tor's logging to work around the following problem:
# https://bugs.torproject.org/9862
logger.debug("Redirecting Tor's logging to /dev/null.")
torCtrl.set_conf("Log", "err file /dev/null")
# We already have the current consensus, so we don't need additional
# descriptors or the streams fetching them.
torCtrl.set_conf("FetchServerDescriptors", "0")
for moduleName in args.module:
runModule(moduleName, args, torCtrl, stats)
return 0
示例7: restartTor
def restartTor(self):
"""Get new tor session"""
with Controller.from_port(port=9051) as controller:
controller.authenticate("Den135790")
controller.signal(Signal.NEWNYM)
self.clean()
self.logger.debug("success restart tor")
示例8: main
def main():
print 'Opening log file, further output will be there.'
# redirect output to file, https://stackoverflow.com/questions/7152762
f = file('TorBrowser/OnioNS/stem.log', 'w')
sys.stdout = f
# get current time of day
now = datetime.datetime.now()
try:
# open main controller
controller = Controller.from_port(port = 9151)
except stem.SocketError:
sys.exit("[err] The Tor Browser is not running. Cannot continue")
controller.authenticate()
controller.set_options({
'__LeaveStreamsUnattached': '1'
})
print '[%d:%d | notice] Successfully connected to the Tor Browser.' % (now.minute, now.second)
sys.stdout.flush()
event_handler = functools.partial(handle_event, controller)
controller.add_event_listener(event_handler, EventType.STREAM)
print '[%d:%d | debug ] Now monitoring stream connections.' % (now.minute, now.second)
sys.stdout.flush()
try:
time.sleep(60 * 60 * 24 * 365) #basically, wait indefinitely
except KeyboardInterrupt:
print ''
示例9: main
def main():
parser = argparse.ArgumentParser(description=
"Parse the log_dir location for tor bw logs and generate graphs.")
parser.add_argument("log_dir", help="Location of tor-log-bw.py output logs.")
args = parser.parse_args()
log_dir = args.log_dir
"""Create a log file and setup the event handler for BW events"""
with Controller.from_port(port = 9051) as controller:
controller.authenticate()
"""
TODO This try except could be eliminated and just straight up call log_bw
"""
log_file = os.path.join(log_dir, "tor_bw.log")
create_timed_rotating_log(log_file)
logger = logging.getLogger("Rotating Log")
logger.info("Starting BW Event Logging")
try:
# This makes curses initialize and call draw_bandwidth_graph() with a
# reference to the screen, followed by additional arguments (in this
# case just the controller).
log_bandwidth(controller)
except KeyboardInterrupt:
pass # the user hit ctrl+c
示例10: renew_connection
def renew_connection():
with Controller.from_port(port = 9151) as controller:
controller.authenticate();
print (controller.get_newnym_wait())
time.sleep(controller.get_newnym_wait());
controller.signal(Signal.NEWNYM);
return;
示例11: launch_tor
def launch_tor(country):
print(term.format("Starting Tor with exit node in %s:" % (country), term.Attr.BOLD))
try:
tor_process = stem.process.launch_tor_with_config(
config = {
'SocksPort': str(SOCKS_PORT),
'ControlPort': str(CONTROL_PORT),
'ExitNodes': "{"+country+"}",
},
timeout = 30,
# init_msg_handler = print_bootstrap_lines,
)
# finally:
# print("test")
except OSError:
print("Timeout when trying to find relay....")
return 0
# Add listener
with Controller.from_port(port = CONTROL_PORT) as controller:
controller.authenticate()
stream_listener = functools.partial(stream_event, controller)
controller.add_event_listener(stream_listener, EventType.STREAM)
return tor_process
示例12: __init__
def __init__(self, control_host = _CONTROL_HOST,
control_port = _CONTROL_PORT, sock = None,
authenticator = _AUTHENTICATOR):
"""Initialize the CtlUtil object, connect to Stem."""
self.sock = sock
if not sock:
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.control_host = control_host
self.control_port = control_port
self.authenticator = authenticator
# Try to connect
try:
self.sock.connect((self.control_host, self.control_port))
except:
errormsg = "Could not connect to Tor control port.\n" + \
"Is Tor running on %s with its control port opened on %s?" %\
(control_host, control_port)
logging.error(errormsg)
raise
self.control = Controller.from_port(port = self.control_port)
# Authenticate connection
self.control.authenticate(config.authenticator)
示例13: _getController
def _getController(controlAddr="127.0.0.1", controlPort=9051, passphrase=None, incorrectPasswordMsg="", printError=True):
"""
Custom handler for establishing a stem connection (... needs an overhaul).
"""
controller = None
try:
chroot = util.torTools.getConn().getPathPrefix()
controller = Controller.from_port(controlAddr, controlPort)
try:
controller.authenticate(password = passphrase, chroot_path = chroot)
except stem.connection.MissingPassword:
try:
passphrase = getpass.getpass("Controller password: ")
controller.authenticate(password = passphrase, chroot_path = chroot)
except:
return None
return controller
except Exception, exc:
if controller: controller.close()
if passphrase and str(exc) == "Unable to authenticate: password incorrect":
# provide a warning that the provided password didn't work, then try
# again prompting for the user to enter it
print incorrectPasswordMsg
return _getController(controlAddr, controlPort)
elif printError:
print exc
return None
示例14: get_exit
def get_exit(is_running):
"""
Get list of exit node from stem
"""
if is_running:
try:
with Controller.from_port(port = 6969) as controller:
controller.authenticate()
exit = {'count': [], 'fingerprint': [], 'nickname': [], 'ipaddress': []}
count = -1
for circ in controller.get_circuits():
if circ.status != stem.CircStatus.BUILT:
continue
exit_fp, exit_nickname = circ.path[-1]
exit_desc = controller.get_network_status(exit_fp, None)
exit_address = exit_desc.address if exit_desc else 'unknown'
count += 1
exit['count'].append(count)
exit['fingerprint'].append(exit_fp)
exit['nickname'].append(exit_nickname)
exit['ipaddress'].append(exit_address)
return exit
except stem.SocketError as exc:
notify("TorTP", "[!] Unable to connect to port 6969 (%s)" % exc)
sys.exit(1)
else:
notify("TorTP", "[!] Tor is not running")
sys.exit(0)
示例15: handle_timeout
def handle_timeout(process, onion, identity_lock):
# halt the main thread while we grab a new identity
identity_lock.clear()
# kill the onionscan process
try:
process.kill()
print("[!!!] Killed the onionscan process.")
except:
pass
# Now we switch TOR identities to make sure we have a good connection
with Controller.from_port(port=9051) as torcontrol:
# authenticate to our local TOR controller
torcontrol.authenticate(PASSWD)
# send the signal for a new identity
torcontrol.signal(Signal.NEWNYM)
# wait for the new identity to be initialized
time.sleep(torcontrol.get_newnym_wait())
print("[!!!] Switched TOR identities.")
# push the onion back on to the list
session_onions.append(onion)
random.shuffle(session_onions)
# allow the main thread to resume executing
identity_lock.set()
return