本文整理汇总了Python中stem.control.Controller类的典型用法代码示例。如果您正苦于以下问题:Python Controller类的具体用法?Python Controller怎么用?Python Controller使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Controller类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
开发者ID:PyStaDa,项目名称:munin-tor,代码行数:10,代码来源:tor_.py
示例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
开发者ID:FedericoCeratto,项目名称:or-applet,代码行数:13,代码来源:orctl.py
示例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)
开发者ID:mic100,项目名称:seloger.com,代码行数:7,代码来源:tool_kit.py
示例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)
开发者ID:jameswenzel,项目名称:jwp,代码行数:27,代码来源:LazyTor.py
示例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()
开发者ID:virgil,项目名称:OnionDrop,代码行数:29,代码来源:toHSO.py
示例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
开发者ID:chubbymaggie,项目名称:exitmap,代码行数:26,代码来源:exitmap.py
示例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")
开发者ID:artycorp,项目名称:counter,代码行数:7,代码来源:search.py
示例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 ''
开发者ID:Jesse-V,项目名称:OnioNS-client,代码行数:35,代码来源:onions-stem.py
示例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
开发者ID:bbbburns,项目名称:tor-bw-logger,代码行数:28,代码来源:tor-log-bw.py
示例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;
开发者ID:gerald-lindner,项目名称:01_MA,代码行数:7,代码来源:testing_area.py
示例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
开发者ID:Sushisugre,项目名称:infosec,代码行数:25,代码来源:exit_node.py
示例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)
开发者ID:sree-dev,项目名称:weather,代码行数:30,代码来源:ctlutil.py
示例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
开发者ID:refnode,项目名称:arm,代码行数:32,代码来源:starter.py
示例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)
开发者ID:alitalia,项目名称:stem-tortp,代码行数:28,代码来源:tortp.py
示例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
开发者ID:clementtrebuchet,项目名称:backend_myinc,代码行数:32,代码来源:onions_scan.py
示例16: start_hidden_service
def start_hidden_service(port):
# come up with a hidden service directory name
hidserv_dir_rand = random_string(8)
if get_platform() == "Windows":
if 'Temp' in os.environ:
temp = os.environ['Temp'].replace('\\', '/')
else:
temp = 'C:/tmp'
hidserv_dir = "{0}/onionshare_{1}".format(temp, hidserv_dir_rand)
else:
hidserv_dir = "/tmp/onionshare_{0}".format(hidserv_dir_rand)
# connect to the tor controlport
controlports = [9051, 9151]
controller = False
for controlport in controlports:
try:
controller = Controller.from_port(port=controlport)
except SocketError:
pass
if not controller:
raise NoTor(translated("cant_connect_ctrlport").format(controlports))
controller.authenticate()
# set up hidden service
controller.set_options([
('HiddenServiceDir', hidserv_dir),
('HiddenServicePort', '80 127.0.0.1:{0}'.format(port))
])
# figure out the .onion hostname
hostname_file = '{0}/hostname'.format(hidserv_dir)
onion_host = open(hostname_file, 'r').read().strip()
return onion_host
开发者ID:loganbr,项目名称:onionshare,代码行数:35,代码来源:onionshare.py
示例17: enable_torproxy
def enable_torproxy():
"""
Use Tor ControlPort for enable Tor Transparent Proxy
"""
with Controller.from_port(port = 9051) as controller:
controller.authenticate()
controller.set_options({"VirtualAddrNetwork": "10.192.0.0/10", "TransPort": "9040", "TransListenAddress": "127.0.0.1","AvoidDiskWrites": "1", "WarnUnsafeSocks": "1"})
开发者ID:paskao,项目名称:stem-tortp,代码行数:7,代码来源:tortp.py
示例18: determine_exits
def determine_exits(self, state):
global can_exit
if options.exits is not None:
exits = map(lambda l: in_consensus(state, l), options.exits)
exits = filter(lambda r: r is not None, exits)
else:
exits = state.routers_by_hash.values()
exits = filter(lambda r: "exit" in r.flags, exits)
# get descriptors from stem
con = Controller.from_port(port = self.options.control_port)
con.authenticate()
descriptors = {}
for desc in con.get_server_descriptors():
descriptors[desc.fingerprint] = desc
con.close()
can_exit_func = functools.partial(can_exit, descriptors,
warn=not options.num_exits)
exits = map(can_exit_func, exits)
exits = filter(lambda t: t[0] is not None, exits)
if options.num_exits is not None:
if options.num_exits > len(exits):
print "Not enough exits. Giving you all I've got."
else:
exits = random.sample(exits, options.num_exits)
return exits
开发者ID:arlolra,项目名称:exitaddr,代码行数:30,代码来源:common.py
示例19: enable_tordns
def enable_tordns():
"""
Use Tor ControlPort for enable TorDNS
"""
with Controller.from_port(port = 9051) as controller:
controller.authenticate()
controller.set_options({"DNSPort": "9053", "DNSListenAddress": "127.0.0.1", "AutomapHostsOnResolve": "1", "AutomapHostsSuffixes": ".exit,.onion"})
开发者ID:paskao,项目名称:stem-tortp,代码行数:7,代码来源:tortp.py
示例20: judgeActive
def judgeActive(onion_addr):
# conn = get_connection()
proc = os.getpid()
print('{0} doubled to {1} by process id: {2}'.format(
onion_addr, '*', proc))
with Controller.from_port(port=9053) as controller:
controller.authenticate("111111")
try:
# cur = conn.cursor()######
hs_descriptor = controller.get_hidden_service_descriptor(onion_addr,await_result = True)
# print(hs_descriptor)
sql = 'update ONION SET status = 1 WHERE onion_addr = "%s" ' % (onion_addr[:-6])
# print(sql)
# cur.execute(sql)#######
print(onion_addr + " is alive from process " + str(proc) + time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
except stem.DescriptorUnavailable:
# print("Descriptor not found, the hidden service may be offline.")
sql = 'update ONION SET status = -1 WHERE onion_addr = "%s" ' % (onion_addr[:-6])
# print(sql)
# cur.execute(sql)#########
print(onion_addr + " is died from process " + str(proc) + time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
except Exception,e:
print '------------------------------------'
print("timeout is found" + onion_addr + str(e) + time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
print ("-----------------------------")
try:#This place is more important that using the try catch make the timeout come realize and useable,so why
controller.close()
# conn.commit()#######
# cur.close()#########
# conn.close()########
except Exception,e:
print "excepiton found" + str(e)
开发者ID:shuaiyin,项目名称:pystudy,代码行数:33,代码来源:judgeActive.py
注:本文中的stem.control.Controller类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论