本文整理汇总了Python中stem.control.Controller.from_port方法的典型用法代码示例。如果您正苦于以下问题:Python Controller.from_port方法的具体用法?Python Controller.from_port怎么用?Python Controller.from_port使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类stem.control.Controller
的用法示例。
在下文中一共展示了Controller.from_port方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: from stem.control import Controller [as 别名]
# 或者: from stem.control.Controller import from_port [as 别名]
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 ''
示例2: main
# 需要导入模块: from stem.control import Controller [as 别名]
# 或者: from stem.control.Controller import from_port [as 别名]
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
示例3: restartTor
# 需要导入模块: from stem.control import Controller [as 别名]
# 或者: from stem.control.Controller import from_port [as 别名]
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")
示例4: renew_connection
# 需要导入模块: from stem.control import Controller [as 别名]
# 或者: from stem.control.Controller import from_port [as 别名]
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;
示例5: __init__
# 需要导入模块: from stem.control import Controller [as 别名]
# 或者: from stem.control.Controller import from_port [as 别名]
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)
示例6: start_hidden_service
# 需要导入模块: from stem.control import Controller [as 别名]
# 或者: from stem.control.Controller import from_port [as 别名]
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
示例7: change_ipadress
# 需要导入模块: from stem.control import Controller [as 别名]
# 或者: from stem.control.Controller import from_port [as 别名]
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)
示例8: renew
# 需要导入模块: from stem.control import Controller [as 别名]
# 或者: from stem.control.Controller import from_port [as 别名]
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)
示例9: launch_tor
# 需要导入模块: from stem.control import Controller [as 别名]
# 或者: from stem.control.Controller import from_port [as 别名]
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
示例10: checkTor
# 需要导入模块: from stem.control import Controller [as 别名]
# 或者: from stem.control.Controller import from_port [as 别名]
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()
示例11: init_tor
# 需要导入模块: from stem.control import Controller [as 别名]
# 或者: from stem.control.Controller import from_port [as 别名]
def init_tor(socks_port=None, control_port=None):
""" Initiates a tor connection.
:param socks_port: local port socket where tor will listen to requests (configurable in tor.rc).
:type socks_port: int
:param control_port: local port where tor will listen to control requests (configurable in tor.rc).
:type control_port: int
:return: a tor process and a controller of the process.
:rtype: process, controller
"""
if socks_port is None:
socks_port = SOCKS_PORT
if control_port is None:
control_port = CONTROL_PORT
process = stem.process.launch_tor_with_config(
config={
'SocksPort': str(socks_port),
'ControlPort': str(control_port)
},
init_msg_handler=print_bootstrap_lines, timeout=60, take_ownership=True)
controller = Controller.from_port()
controller.authenticate()
return process, controller
示例12: handle_timeout
# 需要导入模块: from stem.control import Controller [as 别名]
# 或者: from stem.control.Controller import from_port [as 别名]
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
示例13: _getController
# 需要导入模块: from stem.control import Controller [as 别名]
# 或者: from stem.control.Controller import from_port [as 别名]
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
# 需要导入模块: from stem.control import Controller [as 别名]
# 或者: from stem.control.Controller import from_port [as 别名]
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: enable_torproxy
# 需要导入模块: from stem.control import Controller [as 别名]
# 或者: from stem.control.Controller import from_port [as 别名]
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"})