Ejemplo n.º 1
0
 def initiate_connection(self, verbose=False):
     """
     connect telnet
     :param hostname: str - ip for hostname to connect at.
     :param username: str - username used to connection
     :param password: str - password used to connection
     :param port: int - port used for connection
     :return: telnet prompt
     """
     if verbose:
         log_func_details(hostname=self.hostname,
                          password=self.password,
                          verbose=verbose)
     try:
         self._client = telnetlib.Telnet(self.hostname, Telnet.port)
         if self._client is None:
             return False
     except Exception as e:
         logger.error("error connecting to telnet!!")
         raise ConnectionError(e)
     self._client.write(b'\n')
     self._client.read_until(b'login:'******'ascii') + b'\n')
     self._client.read_until(b'Password:'******'ascii') + b'\n')
     time.sleep(5)
     self.telnet_prompt = self._client.read_very_eager().decode(
         'ascii').splitlines()[-1]
     logger.info('connected to Telnet!')
     logger.info("the Telnet prompt is: {0}".format(self.telnet_prompt))
     return True
Ejemplo n.º 2
0
def run_command_via_ssh(command, device=None, verbose=False):
    """
    running command using default credentials, Run Shell command
    on local or remote device Return command exit code.
    :param device:  None if Local , String if remote
    :param verbose:  true for debug mode , False for info
    :param command: command string
    :type command: str
    :type device: str
    :type verbose: bool
    :return: return code
    :rtype: int
    :TODO adding more than try statement to try multiple scenarios from username/pass
    """

    if verbose:
        log_func_details(command=command, device=device, verbose=verbose)
    if device is not None:
        try:
            logger.debug("< Device: %s > runCommand : %s" % (device, command))
            logger.debug(
                "trying connection using the using default <pg,q1w2e3r4>....")
            ssh_params = ConnParamsFactory.get_params(
                ConnectionType.SSH,
                hostname=device,
                username=SSHCredentials.PG_USERNAME,
                password=SSHCredentials.PG_PASSWORD)
            ssh_params.get_params_dict(True)
            conn = ConnectionFactory.get_connection(ConnectionType.SSH,
                                                    ssh_params)
            ssh_conn = ssh_casting(conn)
            ssh_conn.initiate_connection(verbose=True)
            _, _, _, rc = ssh_conn.exec_command(command=command)
            logger.info("run command passed successfully!!")
            conn.terminate_connection()
            logger.info("connection closed!")
        except Exception as e:
            raise Exception("Error running command: {0}".format(e))
        return rc

    else:
        if verbose:
            logger.info("runCommand : " + str(command))
        with open(os.devnull, 'w') as tempf:
            proc = subprocess.Popen(command,
                                    shell=True,
                                    stdout=tempf,
                                    stderr=tempf)
            proc.communicate()
            return proc.returncode
Ejemplo n.º 3
0
 def exec_tail_log(self,
                   cmd,
                   name,
                   thread_id,
                   dict,
                   map,
                   timeout=10,
                   enable_wait=True,
                   verbose=True,
                   logger=None):
     """
         this function send the command for the channel, and wait for prompt
     :param cmd: the text to send to the channel
     :param prompt: prompt to wait after sending the command. default value is gp prompt
     :param timeout: timeout for the command to finish
     :param enable_wait: when true, the function will run in  blocking mode and wait for given prompt
                         when false, the function will run the command and return.
     :return: buffer: [interactive mode] the output of the command
              stdin, stdout, stderr: [non interactive mode] channel standard output
     """
     if verbose:
         log_func_details(cmd=cmd,
                          name=name,
                          thread_id=thread_id,
                          dict=dict,
                          map=map,
                          timeout=timeout,
                          enable_wait=enable_wait,
                          verbose=verbose,
                          logger=logger)
     _id = threading.get_ident()
     thread_id[_id] = True
     dict[name] = ''
     map[name] = _id
     shell = self._client.invoke_shell()
     shell.send(cmd + '\n')
     start_time = time.time()
     while timeout > time.time() - start_time or (timeout == -1
                                                  and thread_id[_id]):
         if shell.recv_ready():
             line = shell.recv(9999)
             if verbose and logger:
                 logger.debug(line)
             dict[name] += line.decode("utf-8")
     return dict[name]
Ejemplo n.º 4
0
    def initiate_connection(self, verbose=True):
        """
        open a connection to the given machine, the function set a channel for interactive shell.
        if it fail to open a connection the function will print an error to logger an then raise an exception
        :param verbose <boolean> trace option
        :return: connection (self._client)
        """
        if verbose:
            logger.debug("[*] initiate the ssh connection... ")
            log_func_details(hostname=self.hostname,
                             username=self.username,
                             passwor=self.password,
                             port=self.port,
                             timeout=self.timeout,
                             verbose=verbose)
        self._client = paramiko.SSHClient()
        self._client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        connection_success = False
        for i in range(self.retries):
            try:
                logger.debug("retries #:{0}".format(i + 1))
                self._client.connect(hostname=self.hostname,
                                     port=self.port,
                                     username=self.username,
                                     password=self.password,
                                     timeout=self.timeout)
                connection_success = True
                break
            except Exception as e:
                logger.error(e)
                time.sleep(3)
                pass

        if not connection_success:
            logger.error(
                "fail to connect to hostname: {0} username: {1} password: {2}".
                format(self.hostname, self.username, self.password))
            raise Exception

        logger.info("connected to host: {0}".format(self.hostname))
Ejemplo n.º 5
0
 def exec_command(self, command=None, verbose=False):
     """
     send command to telnet channel
     :param command: command to send <str>
     :param prompt: prompt to read until
     :return: stdout <str>
     """
     if verbose:
         log_func_details(command=command,
                          prompt=self.telnet_prompt,
                          verbose=verbose)
     if command:
         cmd_to_run = command
     else:
         raise ValueError(
             "should receive command but received None in place!!!")
     self._client.write(cmd_to_run.encode('ascii') + b'\n')
     stdout = self._client.read_until(
         self.telnet_prompt.encode('ascii')).decode('ascii')
     if verbose:
         logger.debug(
             "the stdout after running the following command <{0}> is : {1}"
             .format(command, stdout))
     return stdout
Ejemplo n.º 6
0
 def send_enter(self, verbose=False):
     """
     send enter button to telnet channel
     :return: None
     """
     if verbose:
         logger.debug('TelNet Connection to machine: {0} Port: {1}'.format(
             self.hostname, Telnet.port))
     self._client = telnetlib.Telnet(self.hostname, self.port)
     time.sleep(1)
     logger.debug('Sending "Enter"')
     self._client.write('\r\n'.encode('ascii'))
     logger.debug('Disconnecting')
     self._client.close()
Ejemplo n.º 7
0
 def exec_command(self,
                  command,
                  bufsize=-1,
                  timeout=None,
                  sudo_required=False,
                  get_pty=False,
                  sudo_passwd='q1w2e3r4',
                  verbose=True):
     """
     exec command via ssh
     :param command: <str>
     :param bufsize: <int>
     :param timeout: <int> second , None in None
     :param sudo: <boolean> if sudo needed
     :param get_pty: <boolean>
     :param sudo_passwd: <string> sudo password
     :param verbose <boolean>
     :return: stdin, stdout, stderr , exit_code
     """
     if verbose:
         log_func_details(command=command,
                          bufsize=bufsize,
                          timeout=timeout,
                          sudo=sudo_required,
                          get_pty=get_pty,
                          sudo_passwd=sudo_passwd)
     if sudo_required or "sudo" in command.lower():
         logger.info(
             "sudo command was detected,the password used for sudo is: {0}".
             format(sudo_passwd))
         command = "echo '{0}' | sudo -S {1}".format(sudo_passwd, command)
     stdin, stdout, stderr = self._client.exec_command(
         command, bufsize, timeout, get_pty)
     exit_status = stdout.channel.recv_exit_status()
     stdout = "".join(stdout.readlines())
     stderr = "".join(stderr.readlines())
     if verbose:
         logger.debug("stdout:{0}".format(stdout))
         logger.debug("stderr:{0}".format(stderr))
         logger.debug("exit_status: {0}".format(exit_status))
     return stdin, stdout, stderr, exit_status
Ejemplo n.º 8
0
    def get_connection(connection_type, params, verbose=False):
        """
        factory method to get connection
        :param connection_type: the connection type (look at connection_data->ConnectionType)
        :type connection_type :str
        :param params: params object from type connection_type
        :type params: Params
        :param verbose: True for debug mode/ False for info
        :type verbose: bool
        :return: connection instance
        :rtype: Connection
        """
        if verbose:
            log_func_details(connection_type=connection_type,
                             params=params.get_params_dict())
        logger.debug(
            "[*] in connection factory, trying creating connection from type: {0}..."
            .format(connection_type))
        if connection_type == ConnectionType.SSH:
            connection = SSH(hostname=params.hostname,
                             username=params.username,
                             password=params.password,
                             port=params.port,
                             timeout=params.timeout,
                             retries=params.retries)

        elif connection_type == ConnectionType.TELNET:
            connection = Telnet(hostname=params.hostname,
                                username=params.username,
                                password=params.password,
                                port=params.port)

        elif connection_type == ConnectionType.SSH_TUNNEL:
            connection = SSHTunnel(
                hostname=params.hostname,
                username=params.username,
                password=params.password,
                ssh_pkey_file_path=params.ssh_pkey_file_path,
                port=params.port,
                remote_bind_address=params.remote_bind_address,
                remote_bind_port=params.remote_bind_port)

        elif connection_type == ConnectionType.SFTP:
            connection = SFTP(hostname=params.hostname,
                              username=params.username,
                              password=params.password,
                              port=params.port)

        elif connection_type == ConnectionType.LOCAL:
            connection = LocalCommand()

        else:
            logger.error("can't give you what i don't have!!!, Not supported "
                         "connection {0}".format(connection_type))
            raise ValueError(
                "Not supported connection {0}".format(connection_type))

        logger.debug(
            "checking if the new connection follow connection standard...")
        if isinstance(connection, Connection):
            logger.info(
                "the connection {0} is inherited from connection base and follow Connection standard!"
                .format(connection_type))

        else:
            logger.error(
                "requested connection not upon connection requirement "
                "- not inherited from connection base class")
            raise Exception("return object not inherited from Connection Base")
        logger.info(
            "new instance from {0} was created!".format(connection_type))
        return connection
Ejemplo n.º 9
0
 def get_params_dict(self, verbose=False):
     params_instance = self.__dict__
     if verbose:
         logger.debug("the params object contains the following params:")
         json_print(params_instance)
     return params_instance
Ejemplo n.º 10
0
 def print_lines(self, channel_file):
     for output_line in channel_file.readlines():
         logger.debug(output_line[:-1])