Python stem.control.Controller.from_port() Examples

The following are 21 code examples of stem.control.Controller.from_port(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module stem.control.Controller , or try the search function .
Example #1
Source File: event_listening.py    From stem with GNU Lesser General Public License v3.0 6 votes vote down vote up
def main():
  with Controller.from_port(port = 9051) as controller:
    controller.authenticate()

    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).

      curses.wrapper(draw_bandwidth_graph, controller)
    except KeyboardInterrupt:
      pass  # the user hit ctrl+c 
Example #2
Source File: torcontroller.py    From tor-browser-crawler with GNU General Public License v2.0 6 votes vote down vote up
def launch_tor_service(self):
        """Launch Tor service and return the process."""
        if self.pollute:
            self.tmp_tor_data_dir = ut.clone_dir_temporary(self.tor_data_path)
            self.torrc_dict.update({'DataDirectory': self.tmp_tor_data_dir})

        print("Tor config: %s" % self.torrc_dict)
        # the following may raise, make sure it's handled
        self.tor_process = stem.process.launch_tor_with_config(
            config=self.torrc_dict,
            init_msg_handler=self.tor_log_handler,
            tor_cmd=self.tor_binary_path,
            timeout=270
        )
        self.controller = Controller.from_port(port=self.control_port)
        self.controller.authenticate()
        return self.tor_process 
Example #3
Source File: swtch.py    From bane with MIT License 6 votes vote down vote up
def tor_switch_with_password(interval=30,password=None,p=9051,logs=True):
 '''
   this one does work on any OS, you just need to activate tor's control port 9051 and set the password.

   it takes the next parameters:

   new: (set by default to: 30) the interval in seconds between switching tor's nodes
   password: your password
   p: (set by default to: 9051) tor's control port
   logs: (set by default to: True) showing the screen prints
'''
 if password==None:
  print("[-]you need to put your control port's password for authentication!!!")
 else:
  while True:
   try:
    with Controller.from_port(port = p) as controller:
     controller.authenticate(password =password )
     controller.signal(Signal.NEWNYM)
     controller.close()
    if logs==True:
     print("IP changed, sleeping for {} seconds...".format(interval))
    time.sleep(interval)
   except KeyboardInterrupt:
    break 
Example #4
Source File: pytor.py    From PyTor with GNU General Public License v2.0 5 votes vote down vote up
def newId():
    global changeIDInPregress
    changeIDInPregress = True
    with Controller.from_port(port = 9051) as controller:
        controller.authenticate(password = password)
        controller.signal(Signal.NEWNYM)
    time.sleep(3)
    changeIDInPregress = False 
Example #5
Source File: exit_used.py    From stem with GNU Lesser General Public License v3.0 5 votes vote down vote up
def main():
  print("Tracking requests for tor exits. Press 'enter' to end.")
  print("")

  with Controller.from_port() as controller:
    controller.authenticate()

    stream_listener = functools.partial(stream_event, controller)
    controller.add_event_listener(stream_listener, EventType.STREAM)

    raw_input()  # wait for user to press enter 
Example #6
Source File: crawler.py    From fingerprint-securedrop with GNU Affero General Public License v3.0 5 votes vote down vote up
def authenticate_to_tor_controlport(self):
        self.logger.info("Authenticating to the tor controlport...")
        try:
            self.controller = Controller.from_port(port=self.control_port)
        except stem.SocketError as exc:
            panic("Unable to connect to tor on port {self.control_port}: "
                  "{exc}".format(**locals()))
        try:
            self.controller.authenticate()
        except stem.connection.MissingPassword:
            panic("Unable to authenticate to tor controlport. Please add "
                  "`CookieAuth 1` to your tor configuration file.") 
Example #7
Source File: InstagramPySession.py    From instagram-py with MIT License 5 votes vote down vote up
def OpenTorController(self, port, password):
        try:
            self.tor_controller = Controller.from_port(port=int(port))
            if password == None:
                self.tor_controller.authenticate()
            else:
                self.tor_controller.authenticate(password=password)
        except Exception as err:
            self.cli.ReportError(
                "Tor configuration invalid or server down :: {}".format(err)) 
Example #8
Source File: changer.py    From TorIpChanger with MIT License 5 votes vote down vote up
def _obtain_new_ip(self):
        """
        Change Tor's IP.
        """
        with Controller.from_port(
            address=self.tor_address, port=self.tor_port
        ) as controller:
            controller.authenticate(password=self.tor_password)
            controller.signal(Signal.NEWNYM)

        # Wait till the IP 'settles in'.
        sleep(self.post_new_ip_sleep) 
Example #9
Source File: tor.py    From kalel with GNU General Public License v3.0 5 votes vote down vote up
def switch_tor():
    print t()+" Please wait..."
    time.sleep(7)
    print t()+" Requesting new circuit...",
    with Controller.from_port(port=9051) as controller:
        controller.authenticate()
        controller.signal(Signal.NEWNYM)
    print bcolors.GREEN+"[done]"+bcolors.ENDC
    print t()+" Fetching current IP..."
    print t()+" CURRENT IP : "+bcolors.GREEN+ip()+bcolors.ENDC
    f = open('module/tor/tor.ip', 'w')
    f.write(ip())
    f.close() 
Example #10
Source File: get_reformagkh_overhaul.py    From reformagkh with GNU General Public License v2.0 5 votes vote down vote up
def change_proxy():
    with Controller.from_port(port = 9151) as controller:
            controller.authenticate(password="password")
            controller.signal(Signal.NEWNYM) 
Example #11
Source File: get_reformagkh_myhouse.py    From reformagkh with GNU General Public License v2.0 5 votes vote down vote up
def change_proxy():
    with Controller.from_port(port = 9151) as controller:
            controller.authenticate(password="password")
            controller.signal(Signal.NEWNYM) 
Example #12
Source File: get_reformagkh_atd.py    From reformagkh with GNU General Public License v2.0 5 votes vote down vote up
def change_proxy():
    with Controller.from_port(port = 9151) as controller:
            controller.authenticate(password="password")
            controller.signal(Signal.NEWNYM) 
Example #13
Source File: torghost.py    From torghost with GNU General Public License v3.0 5 votes vote down vote up
def switch_tor():
    print(t() + ' Please wait...')
    time.sleep(7)
    print(t() + ' Requesting new circuit...',)
    with Controller.from_port(port=9051) as controller:
        controller.authenticate()
        controller.signal(Signal.NEWNYM)
    print(bcolors.GREEN + '[done]' + bcolors.ENDC)
    print(t() + ' Fetching current IP...')
    print(t() + ' CURRENT IP : ' + bcolors.GREEN + ip() + bcolors.ENDC) 
Example #14
Source File: proxy.py    From PythonScrapyBasicSetup with MIT License 5 votes vote down vote up
def import_settings(self):
        settings = get_project_settings()
        self.password = settings['AUTH_PASSWORD']
        self.http_proxy = settings['HTTP_PROXY']
        self.control_port = settings['CONTROL_PORT']
        self.max_req_per_ip = settings['MAX_REQ_PER_IP']

        self.exit_nodes = settings['EXIT_NODES']
        if self.exit_nodes:
            with Controller.from_port(port=self.control_port) as controller:
                controller.authenticate(self.password)
                controller.set_conf('ExitNodes', self.exit_nodes)
                controller.close() 
Example #15
Source File: proxy.py    From PythonScrapyBasicSetup with MIT License 5 votes vote down vote up
def change_ip_address(self):
        with Controller.from_port(port=self.control_port) as controller:
            controller.authenticate(self.password)
            controller.signal(Signal.NEWNYM)
            controller.close() 
Example #16
Source File: utils.py    From mlconjug with MIT License 5 votes vote down vote up
def renew_tor_circuit(self):
        """
        Renews the Tor circuit.
        Sends a NEWNYM message to the Tor network to create a new circuit.

        :return: bool.
            Whether a new tor ciruit was created.

        """

        def renew_circuit(password):
            """
            Sends a NEWNYM message to the Tor network to create a new circuit.

            :param password:
            :return: bool.
            """
            controller.authenticate(password=password)
            if controller.is_newnym_available():  # true if tor would currently accept a NEWNYM signal.
                controller.signal(Signal.NEWNYM)
                print('New Tor circuit created')
                result = True
            else:
                delay = controller.get_newnym_wait()
                print('Delay to create new Tor circuit: {0}s'.format(delay))
                result = False
            return result

        # Needs to reload the default socket to be able to send the is_newnym_avilable and get_newnym_wait signals
        reload(socket)
        if isinstance(self.controlport, int):
            with Controller.from_port(port=self.controlport) as controller:
                is_renewed = renew_circuit(self.password)
        elif isinstance(self.controlport, basestring):
            with Controller.from_socket_file(path=self.controlport) as controller:
                is_renewed = renew_circuit(self.password)
        else:
            is_renewed = False
        gevent.monkey.patch_socket()
        return is_renewed 
Example #17
Source File: tor_util.py    From specter-desktop with MIT License 5 votes vote down vote up
def run_on_hidden_service(app, tor_password=None, tor_port=80, save_address_to=None, **kwargs):
    port = 5000 # default flask port
    if "port" in kwargs:
        port = kwargs["port"]
    else:
        kwargs["port"] = port

    with Controller.from_port() as controller:
        print(' * Connecting to tor')
        controller.authenticate(tor_password)

        key_path = os.path.abspath(os.path.expanduser(os.path.join(DATA_FOLDER,'.tor_service_key')))
        tor_service_id = None

        if not os.path.exists(key_path):
            service = controller.create_ephemeral_hidden_service({tor_port: port}, await_publication = True)
            tor_service_id = service.service_id
            print("* Started a new hidden service with the address of %s.onion" % tor_service_id)

            with open(key_path, 'w') as key_file:
                key_file.write('%s:%s' % (service.private_key_type, service.private_key))
        else:
            with open(key_path) as key_file:
                key_type, key_content = key_file.read().split(':', 1)

            service = controller.create_ephemeral_hidden_service({tor_port: port}, key_type = key_type, key_content = key_content, await_publication = True)
            tor_service_id = service.service_id
            print("* Resumed %s.onion" % tor_service_id)

        # save address to file
        if save_address_to is not None:
            with open(save_address_to, "w") as f:
                f.write("%s.onion" % tor_service_id)

        try:
            app.run(**kwargs)
        finally:
            if tor_service_id:
                print(" * Shutting down our hidden service")
                controller.remove_ephemeral_hidden_service(tor_service_id) 
Example #18
Source File: fb.py    From facebrute with GNU General Public License v3.0 5 votes vote down vote up
def function(email,passw):
	headers = {'User-Agent':random.choice(open('user-agents.txt').read().splitlines()),'Accept-Language':'en-US,en;q=0.5'}
	payload['email'] = email
	payload['pass'] = passw
	e = ''
	if l == 1:e = requests.get('https://api.ipify.org',proxies=proxy,verify=False).text
	with Controller.from_port(port = 9051) as c:
		c.authenticate()
		c.signal(Signal.NEWNYM)
		A=requests.post(post_url,data=payload,headers=headers,proxies=proxy,verify=False)				
		soup = BeautifulSoup(re.sub("</"," </", A.text),"lxml")
		for s in soup(["style","script"]):s.decompose()
		clean = re.sub("To personalize content, tailor and measure ads, and provide a safer experience, we use cookies. By tapping on the site, you agree to our use of cookies on and off Facebook. Learn more, including about controls: Cookies Policy . Facebook ","", re.sub(' +',' ',soup.get_text()))
		print('\n ['+str(k)+'/'+str(g)+'] Trying',passw+' '+e+' FB says '+clean[:28])
		open(email+'_response.txt','a').write(clean+' '+passw)
		if 'Facebook ' in clean[:9] or 'Please confirm your identity' in clean or 'Your account has been temporarily locked' in clean:
			open('found.txt','a').write('\nUsername='+email+' Password='+passw)
			quit('\n \033[1;32m[+] Congrats!!! Password is : '+passw+' [+] Saved : found.txt\n\n')
		elif'Please try again later'in clean or 'You Can\'t Do That Right Now' in  clean:
			open(email+'_left_password.txt','a').write(passw+'\n')
			print('\033[93m [+] IP used so much.\n [+] Password Saved in '+email+'_left_password.txt')
			m = input(' [+] Enter minutes to sleep for or nothing for no sleep : ')
			if(m.isdigit()):
				print(' [+] Waiting for '+m+' minutes...\033[97m')
				time.sleep(int(m)*60)
			return False	
		else:
			return False 
Example #19
Source File: control.py    From stem with GNU Lesser General Public License v3.0 5 votes vote down vote up
def from_port(address: str = '127.0.0.1', port: Union[int, str] = 'default') -> 'stem.control.Controller':
    """
    Constructs a :class:`~stem.socket.ControlPort` based Controller.

    If the **port** is **'default'** then this checks on both 9051 (default
    for relays) and 9151 (default for the Tor Browser). This default may change
    in the future.

    .. versionchanged:: 1.5.0
       Use both port 9051 and 9151 by default.

    :param address: ip address of the controller
    :param 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
    """

    import stem.connection

    if not stem.util.connection.is_valid_ipv4_address(address):
      raise ValueError('Invalid IP address: %s' % address)
    elif port != 'default' and not stem.util.connection.is_valid_port(port):
      raise ValueError('Invalid port: %s' % port)

    if port == 'default':
      control_port = stem.connection._connection_for_default_port(address)
    else:
      control_port = stem.socket.ControlPort(address, int(port))

    return Controller(control_port) 
Example #20
Source File: tutorial_examples.py    From stem with GNU Lesser General Public License v3.0 4 votes vote down vote up
def test_exit_used(self, from_port_mock, stdout_mock):
    def tutorial_example(mock_event):
      import functools

      from stem import StreamStatus
      from stem.control import EventType, Controller

      def main():
        print("Tracking requests for tor exits. Press 'enter' to end.\n")

        with Controller.from_port() as controller:
          controller.authenticate()

          stream_listener = functools.partial(stream_event, controller)
          controller.add_event_listener(stream_listener, EventType.STREAM)

          stream_event(controller, mock_event)  # simulate an event during the raw_input()

      def stream_event(controller, event):
        if event.status == StreamStatus.SUCCEEDED and event.circ_id:
          circ = controller.get_circuit(event.circ_id)

          exit_fingerprint = circ.path[-1][0]
          exit_relay = controller.get_network_status(exit_fingerprint)

          print('Exit relay for our connection to %s' % (event.target))
          print('  address: %s:%i' % (exit_relay.address, exit_relay.or_port))
          print('  fingerprint: %s' % exit_relay.fingerprint)
          print('  nickname: %s' % exit_relay.nickname)
          print('  locale: %s\n' % controller.get_info('ip-to-country/%s' % exit_relay.address, 'unknown'))

      main()

    path_1 = ('9EA317EECA56BDF30CAEB208A253FB456EDAB1A0', 'bolobolo1')
    path_2 = ('00C2C2A16AEDB51D5E5FB7D6168FC66B343D822F', 'ph3x')
    path_3 = ('A59E1E7C7EAEE083D756EE1FF6EC31CA3D8651D7', 'chaoscomputerclub19')
    circuit = _get_circ_event(1, 'BUILT', path_1, path_2, path_3, 'GENERAL')

    event_content = '650 STREAM 15 SUCCEEDED 3 64.15.112.44:80'
    event = _get_event(event_content)

    controller = from_port_mock().__enter__()
    controller.get_circuit.return_value = circuit
    controller.get_network_status.return_value = _get_router_status('31.172.30.2', '443', path_3[1], 'pZ4efH6u4IPXVu4f9uwxyj2GUdc=')
    controller.get_info.return_value = 'unknown'

    tutorial_example(event)
    self.assertCountEqual(EXIT_USED_OUTPUT.splitlines(), stdout_mock.getvalue().splitlines()) 
Example #21
Source File: control.py    From stem with GNU Lesser General Public License v3.0 4 votes vote down vote up
def add_event_listener(self, listener: Callable[[stem.response.events.Event], None], *events: 'stem.control.EventType') -> None:
    """
    Directs further tor controller events to a given function. The function is
    expected to take a single argument, which is a
    :class:`~stem.response.events.Event` subclass. For instance the following
    would print the bytes sent and received by tor over five seconds...

    ::

      import time
      from stem.control import Controller, EventType

      def print_bw(event):
        print('sent: %i, received: %i' % (event.written, event.read))

      with Controller.from_port(port = 9051) as controller:
        controller.authenticate()
        controller.add_event_listener(print_bw, EventType.BW)
        time.sleep(5)

    If a new control connection is initialized then this listener will be
    reattached.

    If tor emits a malformed event it can be received by listening for the
    stem.control.MALFORMED_EVENTS constant.

    .. versionchanged:: 1.7.0
       Listener exceptions and malformed events no longer break further event
       processing. Added the **MALFORMED_EVENTS** constant.

    :param listener: function to be called when an event is received
    :param events: event types to be listened for

    :raises: :class:`stem.ProtocolError` if unable to set the events
    """

    # first checking that tor supports these event types

    with self._event_listeners_lock:
      if self.is_authenticated():
        for event_type in events:
          event_type = stem.response.events.EVENT_TYPE_TO_CLASS.get(event_type)

          if event_type and (self.get_version() < event_type._VERSION_ADDED):
            raise stem.InvalidRequest('552', '%s event requires Tor version %s or later' % (event_type, event_type._VERSION_ADDED))

      for event_type in events:
        self._event_listeners.setdefault(event_type, []).append(listener)

      failed_events = self._attach_listeners()[1]

      # restricted the failures to just things we requested

      failed_events = set(failed_events).intersection(set(events))

      if failed_events:
        raise stem.ProtocolError('SETEVENTS rejected %s' % ', '.join(failed_events))