示例#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
示例#2
0
 def terminate_connection(self, sleep_before=0, verbose=True):
     """
     close connection in case the connection still opened until end of the script
     :param sleep_before: in sec <int>
     :param verbose: Boolean - activate the trace
     :return: None
     :Raises: Exception in case cannot close connection
     """
     if verbose:
         log_func_details(sleep_before=sleep_before, verbose=verbose)
     time.sleep(sleep_before)
     try:
         if self._client is not None:
             if self._client.get_transport() is not None:
                 self._client.close()
                 logger.info("connection is closed successfully!")
             else:
                 logger.info("connection is closed!")
         else:
             logger.error(
                 "there is no open connection to close, you should did establish_connection before !!"
                 .format(self._client))
             raise ValueError("no open connection to close!")
     except Exception as e:
         raise Exception("connection <{0}> cannot be closed: {1}".format(
             self._client, e))
def local_casting(conn):
    """
    :param conn:
    :type conn : Connection
    :return:
    :rtype: LocalCommand
    """
    if isinstance(conn, LocalCommand):
        return conn
    else:
        logger.error("casting error, conn passed is not LocalCommand type")
        raise ValueError("LocalCommand casting error")
def ssh_tunnel_casting(conn):
    """
    :param conn:
    :type conn : Connection
    :return:
    :rtype: SSHTunnel
    """
    if isinstance(conn, SSHTunnel):
        return conn
    else:
        logger.error("casting error, conn passed is not SSHTunnel type")
        raise ValueError("SSHTunnel casting error")
def sftp_casting(conn):
    """
    :param conn:
    :type conn : Connection
    :return:
    :rtype: SFTP
    """
    if isinstance(conn, SFTP):
        return conn
    else:
        logger.error("casting error, conn passed is not SFTP type")
        raise ValueError("SFTP casting error")
def telnet_casting(conn):
    """
    :param conn:
    :type conn : Connection
    :return:
    :rtype: Telnet
    """
    if isinstance(conn, Telnet):
        return conn
    else:
        logger.error("casting error, conn passed is not Telnet type")
        raise ValueError("Telnet casting error")
示例#7
0
    def initiate_connection(self, verbose=False):
        """
         initiate_tunnel via ssh (abstract method)
        :param verbose: boolean - for debug purpose
        :return: True/False if tunnel initiated ot not.
        :rtype : bool
        """
        if verbose:
            log_func_details(ssh_address_or_host=self.hostname, ssh_username=self.username,
                             ssh_pkey_file_path=self.ssh_pkey_file_path, remote_bind_address=self.remote_bind_address,
                             remote_bind_port=self.remote_bind_port, verbose=verbose)
        logger.info("start initiating ssh Tunnel between localhost and remote-host: %s " % self.hostname)
        try:
            self.ssh_tunnel = SSHTunnelForwarder(ssh_address_or_host=self.hostname,
                                                 ssh_username=self.username,
                                                 ssh_password=self.password,
                                                 ssh_pkey=self.ssh_pkey_file_path,
                                                 remote_bind_address=(self.remote_bind_address, self.remote_bind_port),
                                                 ssh_port=self.port)
        except Exception as e:
            logger.error("error getting the tunnel connection via SSHTunnelForwarder")
            raise ConnectionError(e)

        logger.info("starting tunnel...")
        self.ssh_tunnel.start()
        logger.info("check if tunnel is active and up after starting tunnel...")
        if (self.ssh_tunnel.tunnel_is_up is not None):
            logger.info("Tunnel is up and ready to go!!!")
            if verbose:
                logger.info("here is tunnel connction details:")
                logger.info("local_bind_address: {0} ".format(self.ssh_tunnel.local_bind_address))
                logger.info("local_bind_host: {0} ".format(self.ssh_tunnel.local_bind_host))
                logger.info("local_bind_port: {0}".format(self.ssh_tunnel.local_bind_port))
                logger.info(
                    "tunnel_is_up: {0}".format(self.ssh_tunnel.tunnel_is_up[self.ssh_tunnel.local_bind_address]))
            self.local_bind_address = self.ssh_tunnel.local_bind_address[0]
            self.local_bind_port = self.ssh_tunnel.local_bind_port
            logger.info("Initiating SSH Tunnel Passed Greatly !!!")
            return True
        return False
示例#8
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))
    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
示例#10
0
    def get_params(connection_type,
                   hostname=None,
                   username=None,
                   password=None,
                   port=None,
                   ssh_pkey_file_path=None,
                   verbose=False):
        """
        factory method to generate params object reltaed to connection type.
        :param connection_type: the connection type between (ssh,sftp,telnet,tunnel,local ...etc)
        :param hostname: the hostname param
        :param username: username for connection
        :param password: password for connection
        :param ssh_pkey_file_path : pem file for some cases
        :param verbose: True for debug/ False for info
        :return: params object related to connection type
        :type connection_type: str
        :type ssh_pkey_file_path: str
        :type hostname: str
        :type username: str
        :type password: str
        :type verbose: bool
        :return params object from type connection_type
        :rtype Params
        """

        log_func_details(connection_type=connection_type,
                         hostname=hostname,
                         username=username,
                         password=password)
        logger.info("[*] creating connection params object from "
                    "type: {0}...".format(connection_type))
        if connection_type == ConnectionType.SSH:
            params_instance = SSHParams(hostname=hostname,
                                        username=username,
                                        password=password)

        elif connection_type == ConnectionType.TELNET:
            params_instance = TelnetParams(hostname=hostname,
                                           username=username,
                                           password=password)

        elif connection_type == ConnectionType.SSH_TUNNEL:
            params_instance = SSHTunnelParams(
                hostname=hostname,
                username=username,
                password=password,
                port=port,
                ssh_pkey_file_path=ssh_pkey_file_path)

        elif connection_type == ConnectionType.SFTP:
            params_instance = SFTPParams(hostname=hostname,
                                         username=username,
                                         password=password)

        elif connection_type == ConnectionType.LOCAL:
            params_instance = LocalConnParam(hostname=hostname,
                                             username=username,
                                             password=password)

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

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

        else:
            logger.error(
                "requested connection params not upon Params requirement "
                "- not inherited from Params base class")
            raise Exception("return object not inherited from Params Base")
        logger.info("new instance from {0} Params was created!".format(
            connection_type))
        return params_instance