예제 #1
0
    def _get_ssh_client(self, host):
        """
        Create a SSH Client based on host, username and password if provided.
        If there is any AuthenticationException/SSHException, raise HTTP Error 403 as permission denied.

        :param host:
        :return: ssh client instance
        """
        try:
            ssh = paramiko.SSHClient()
            ssh.load_system_host_keys()
            ssh.set_missing_host_key_policy(paramiko.RejectPolicy())
            host_ip = gethostbyname(host)
            if remote_pwd:
                ssh.connect(host_ip,
                            port=ssh_port,
                            username=remote_user,
                            password=remote_pwd)
            else:
                ssh.connect(host_ip, port=ssh_port, username=remote_user)
        except Exception as e:
            self.log.error(
                "Exception '{}' occurred when creating a SSHClient connecting to '{}:{}' with user '{}', "
                "message='{}'.".format(
                    type(e).__name__, host, ssh_port, remote_user, e))
            if e is paramiko.SSHException or paramiko.AuthenticationException:
                error_message_prefix = "Failed to authenticate SSHClient with password"
                error_message = error_message_prefix + (
                    " provided" if remote_pwd else "-less SSH")
                raise tornado.web.HTTPError(403, error_message)
            else:
                raise e
        return ssh
예제 #2
0
파일: submission.py 프로젝트: afcarl/tej
 def _ssh_client(self):
     """Gets an SSH client to connect with.
     """
     ssh = paramiko.SSHClient()
     ssh.load_system_host_keys()
     ssh.set_missing_host_key_policy(paramiko.RejectPolicy())
     return ssh
예제 #3
0
    def __init__(self, ip, username, password='', secret='', port=22, device_type='', verbose=True,
                 global_delay_factor=.5, use_keys=False, key_file=None, ssh_strict=False,
                 system_host_keys=False, alt_host_keys=False, alt_key_file='',
                 ssh_config_file=None):

        self.ip = ip
        self.port = int(port)
        self.username = username
        self.password = password
        self.secret = secret
        self.device_type = device_type
        self.ansi_escape_codes = False

        # Use the greater of global_delay_factor or delay_factor local to method
        self.global_delay_factor = global_delay_factor

        # set in set_base_prompt method
        self.base_prompt = ''

        if not ssh_strict:
            self.key_policy = paramiko.AutoAddPolicy()
        else:
            self.key_policy = paramiko.RejectPolicy()

        # Options for SSH host_keys
        self.system_host_keys = system_host_keys
        self.alt_host_keys = alt_host_keys
        self.alt_key_file = alt_key_file

        # For SSH proxy support
        self.ssh_config_file = ssh_config_file

        self.establish_connection(verbose=verbose, use_keys=use_keys, key_file=key_file)
        self.session_preparation()
예제 #4
0
 def __init__(self,
              host,
              port,
              username,
              password,
              accept_all_keys=False,
              host_key_file=None,
              use_system_hosts=False,
              timeout=10,
              timeout_limit=3):
     self._buffer = b""
     self._ssh_conn = paramiko.SSHClient()
     if accept_all_keys:
         self._ssh_conn.set_missing_host_key_policy(
             paramiko.AutoAddPolicy())
     else:
         self._ssh_conn.set_missing_host_key_policy(paramiko.RejectPolicy())
     if use_system_hosts:
         self._ssh_conn.load_system_host_keys()
     if host_key_file is not None and isfile(host_key_file):
         self._ssh_conn.load_host_keys(host_key_file)
     if username is not None and password is not None:
         self._ssh_conn.connect(host,
                                port=port,
                                username=username,
                                password=password)
         if host_key_file is not None:
             self._ssh_conn.save_host_keys(host_key_file)
         self._channel = self._ssh_conn.invoke_shell("raw")
         self._channel.settimeout(timeout)
         self.timeout_limit = timeout_limit
     else:
         raise TS3Exception("Connecting via ssh requires a password.")
예제 #5
0
 def __init__(self,
              sourcepath,
              hostname,
              user,
              port=22,
              password=None,
              ssh_id=None,
              ssh_hostkey=None,
              ssh_unknown_hosts=False,
              temppath=None,
              keep_tmp=False):
     if not _PARAMIKO:
         raise ImportError("Cannot import paramiko, which is needed for "
                           "SFTPFilesystemCache")
     self._hostname = hostname
     self._username = user
     self._password = password
     # TODO: ssh_id checken
     # TODO: ssh_agent
     self._ssh_id = None
     self._port = port
     self._ssh = paramiko.SSHClient()
     self._ssh.load_system_host_keys()
     if ssh_hostkey is not None:
         self._ssh.load_host_keys(ssh_hostkey)
     if ssh_unknown_hosts:
         self._ssh.set_missing_host_key_policy(paramiko.WarningPolicy())
     else:
         self._ssh.set_missing_host_key_policy(paramiko.RejectPolicy())
     # TODO: persistently connect
     super(SFTPFilesystemCache, self).__init__(sourcepath, temppath,
                                               keep_tmp)
예제 #6
0
    def _get_ssh_client(self, host):
        """
        Create a SSH Client based on host, username and password if provided.
        If there is any AuthenticationException/SSHException, raise HTTP Error 403 as permission denied.

        :param host:
        :return: ssh client instance
        """
        try:
            ssh = paramiko.SSHClient()
            ssh.load_system_host_keys()
            ssh.set_missing_host_key_policy(paramiko.RejectPolicy())
            host_ip = gethostbyname(host)
            if remote_pwd:
                ssh.connect(host_ip,
                            port=ssh_port,
                            username=remote_user,
                            password=remote_pwd)
            else:
                ssh.connect(host_ip, port=ssh_port, username=remote_user)
        except Exception as e:
            http_status_code = 500
            current_host = gethostbyname(gethostname())
            error_message = "Exception '{}' occurred when creating a SSHClient at {} connecting " \
                            "to '{}:{}' with user '{}', message='{}'.".\
                format(type(e).__name__, current_host, host, ssh_port, remote_user, e)
            if e is paramiko.SSHException or paramiko.AuthenticationException:
                http_status_code = 403
                error_message_prefix = "Failed to authenticate SSHClient with password"
                error_message = error_message_prefix + (
                    " provided" if remote_pwd else "-less SSH")

            self.log_and_raise(http_status_code=http_status_code,
                               reason=error_message)
        return ssh
예제 #7
0
    def test_ssh_key_policy(self, mock_sshclient):
        mock_sshclient.return_value = FakeSSHClient()

        # create with customized setting
        sshpool = utils.SSHPool("127.0.0.1",
                                22,
                                10,
                                "test",
                                password="******",
                                min_size=1,
                                max_size=1,
                                missing_key_policy=paramiko.RejectPolicy(),
                                hosts_key_file='dummy_host_keyfile')
        with sshpool.item() as ssh:
            self.assertTrue(isinstance(ssh.get_policy(),
                                       paramiko.RejectPolicy))
            self.assertEqual(ssh.hosts_key_file, 'dummy_host_keyfile')

        # create with default setting
        sshpool = utils.SSHPool("127.0.0.1",
                                22,
                                10,
                                "test",
                                password="******",
                                min_size=1,
                                max_size=1)
        with sshpool.item() as ssh:
            self.assertTrue(
                isinstance(ssh.get_policy(), paramiko.AutoAddPolicy))
            self.assertEqual(ssh.system_host_keys, 'system_host_keys')
예제 #8
0
파일: shell.py 프로젝트: evil-org/ansible
    def open(self,
             host,
             port=22,
             username=None,
             password=None,
             timeout=10,
             key_filename=None,
             pkey=None,
             look_for_keys=None,
             allow_agent=False,
             key_policy="loose"):

        self.ssh = paramiko.SSHClient()
        if key_policy != "ignore":
            self.ssh.load_system_host_keys()
            try:
                self.ssh.load_host_keys(
                    os.path.expanduser('~/.ssh/known_hosts'))
            except IOError:
                pass

        if key_policy == "strict":
            self.ssh.set_missing_host_key_policy(paramiko.RejectPolicy())
        else:
            self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        # unless explicitly set, disable look for keys if a password is
        # present. this changes the default search order paramiko implements
        if not look_for_keys:
            look_for_keys = password is None

        try:
            self.ssh.connect(
                host,
                port=port,
                username=username,
                password=password,
                timeout=timeout,
                look_for_keys=look_for_keys,
                pkey=pkey,
                key_filename=key_filename,
                allow_agent=allow_agent,
            )

            self.shell = self.ssh.invoke_shell()
            self.shell.settimeout(timeout)
        except socket.gaierror:
            raise ShellError("unable to resolve host name")
        except AuthenticationException:
            raise ShellError('Unable to authenticate to remote device')
        except socket.error:
            exc = get_exception()
            if exc.errno == 60:
                raise ShellError('timeout trying to connect to host')
            raise

        if self.kickstart:
            self.shell.sendall("\n")

        self.receive()
예제 #9
0
    def __init__(self,
                 ip=u'',
                 host=u'',
                 username=u'',
                 password=u'',
                 secret=u'',
                 port=22,
                 device_type=u'',
                 verbose=False,
                 global_delay_factor=.1,
                 use_keys=False,
                 key_file=None,
                 ssh_strict=False,
                 system_host_keys=False,
                 alt_host_keys=False,
                 alt_key_file='',
                 ssh_config_file=None,
                 timeout=8):

        if ip:
            self.host = ip
            self.ip = ip
        elif host:
            self.host = host
        if not ip and not host:
            raise ValueError("Either ip or host must be set")
        self.port = int(port)
        self.username = username
        self.password = password
        self.secret = secret
        self.device_type = device_type
        self.ansi_escape_codes = False
        self.verbose = verbose
        self.timeout = timeout

        # Use the greater of global_delay_factor or delay_factor local to method
        self.global_delay_factor = global_delay_factor

        # set in set_base_prompt method
        self.base_prompt = ''

        if not ssh_strict:
            self.key_policy = paramiko.AutoAddPolicy()
        else:
            self.key_policy = paramiko.RejectPolicy()

        # Options for SSH host_keys
        self.use_keys = use_keys
        self.key_file = key_file
        self.system_host_keys = system_host_keys
        self.alt_host_keys = alt_host_keys
        self.alt_key_file = alt_key_file

        # For SSH proxy support
        self.ssh_config_file = ssh_config_file

        self.establish_connection()
        self.session_preparation()
예제 #10
0
    def create(self):
        try:
            ssh = paramiko.SSHClient()
            if ',' in self.hosts_key_file:
                files = string.split(self.hosts_key_file, ',')
                for f in files:
                    ssh.load_host_keys(f)
            else:
                ssh.load_host_keys(self.hosts_key_file)
            # If strict_ssh_host_key_policy is set we want to reject, by
            # default if there is not entry in the known_hosts file.
            # Otherwise we use AutoAddPolicy which accepts on the first
            # Connect but fails if the keys change.  load_host_keys can
            # handle hashed known_host entries.
            if self.strict_ssh_host_key_policy:
                ssh.set_missing_host_key_policy(paramiko.RejectPolicy())
            else:
                ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

            if self.password:
                ssh.connect(self.ip,
                            port=self.port,
                            username=self.login,
                            password=self.password,
                            timeout=self.conn_timeout)
            elif self.privatekey:
                pkfile = os.path.expanduser(self.privatekey)
                privatekey = paramiko.RSAKey.from_private_key_file(pkfile)
                ssh.connect(self.ip,
                            port=self.port,
                            username=self.login,
                            pkey=privatekey,
                            timeout=self.conn_timeout)
            else:
                msg = _("Specify a password or private_key")
                raise exception.CinderException(msg)

            # Paramiko by default sets the socket timeout to 0.1 seconds,
            # ignoring what we set through the sshclient.
            # This doesn't help for
            # keeping long lived connections. Hence we have to bypass it, by
            # overriding it after the transport is initialized. We are setting
            # the sockettimeout to None and setting a
            # keepalive packet so that,
            # the server will keep the connection open. All that does is send
            # a keepalive packet every ssh_conn_timeout seconds.
            if self.conn_timeout:
                transport = ssh.get_transport()
                transport.sock.settimeout(None)
                transport.set_keepalive(self.conn_timeout)
            return ssh
        except Exception as e:
            msg = _("Error connecting via ssh: %s") % six.text_type(e)
            LOG.error(msg)
            raise paramiko.SSHException(msg)
예제 #11
0
 def connect(self):
     log.info("Attempting establishment of new paramiko SSH channel")
     self.ssh = paramiko.SSHClient()
     self.ssh.set_missing_host_key_policy(paramiko.RejectPolicy(
     ) if self.strict_host_key_checking else paramiko.WarningPolicy())
     self.ssh.connect(hostname=self.hostname,
                      port=self.port,
                      username=self.username,
                      password=self.password,
                      key_filename=self.private_key,
                      timeout=self.timeout)
예제 #12
0
    def __connect_to_host(cls, config: dict) -> para.SSHClient:
        """connect to remote host"""
        kwargs = {}
        kwargs['username'] = config.get('REMOTE_USER', None)
        kwargs['password'] = config.get('REMOTE_PASS', None)

        ssh_client = para.SSHClient()
        ssh_client.load_system_host_keys()
        ssh_client.set_missing_host_key_policy(para.RejectPolicy())
        ssh_client.connect(hostname=config['SERVER_IP'], **kwargs)
        return ssh_client
 def test_create_ssh_client(self, load_mock):
     mock_args = {}
     mock_args['known_hosts_file'] = 'dummy_host_key_file'
     mock_args['missing_key_policy'] = paramiko.RejectPolicy()
     ssh_client = self.create_ssh_client(**mock_args)
     self.assertEqual(ssh_client._host_keys_filename, 'dummy_host_key_file')
     self.assertTrue(isinstance(ssh_client._policy, paramiko.RejectPolicy))
     mock_args = {}
     ssh_client = self.create_ssh_client(**mock_args)
     self.assertIsNone(ssh_client._host_keys_filename)
     self.assertTrue(isinstance(ssh_client._policy, paramiko.WarningPolicy))
예제 #14
0
def spawnShell(user, password, server, port):
  global debug, verbose

# if debug: paramiko.util.log_to_file(os.path.expanduser('~/.ssssh.log'))
  if debug: paramiko.common.logging.basicConfig(level=paramiko.common.DEBUG)

  try:
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.RejectPolicy())
    if verbose: print("Connecting to \"%s\" on port %s" % (server, port))

    try:
      client.connect(server, port, user, password)
    except paramiko.ssh_exception.AuthenticationException:
      print("Invalid credentials. Username or password incorrect.")
      client.close()
      sys.exit()
    except paramiko.ssh_exception.BadHostKeyException:
      print("Rejecting bad host key.")
      client.close()
      sys.exit()
    except paramiko.ssh_exception.SSHException:
      t = client.get_transport()
      key = t.get_remote_server_key()
      # https://www.adampalmer.me/iodigitalsec/2014/11/24/ssh-fingerprint-and-hostkey-with-paramiko-in-python/
      key_type = key.get_name()
      key_ascii = base64.encodestring(key.__str__()).replace('\n', '')
      if verbose: print("[%s]:%s %s %s" % (server, port, key_type, key_ascii))
      print("Rejecting unknown host key for %s. (%s)" % (server, key_type))
      client.close()
      sys.exit()
    except socket.error: 
      print("Can not connect to %s on port %s." % (server, port))
      client.close()
      sys.exit()
    except Exception as e:
      print("ERROR: Caught exception: %s: %s" % (e.__class__, e))
      client.close()
      sys.exit()
    c = client.invoke_shell()
    if debug: print(repr(client.get_transport()))
    interactive_shell(c)
    c.close()
    client.close()
  except Exception as e:
    print("ERROR: Caught exception: %s: %s" % (e.__class__, e))
#   traceback.print_exc()
    try:
      client.close()
    except:
      pass
    sys.exit()
예제 #15
0
    def _create_ssh(self, **kwargs):
        try:
            ssh = paramiko.SSHClient()

            known_hosts_file = kwargs.get('known_hosts_file', None)
            if known_hosts_file is None:
                ssh.load_system_host_keys()
            else:
                # Make sure we can open the file for appending first.
                # This is needed to create the file when we run CI tests with
                # no existing key file.
                open(known_hosts_file, 'a').close()
                ssh.load_host_keys(known_hosts_file)

            missing_key_policy = kwargs.get('missing_key_policy', None)
            if missing_key_policy is None:
                missing_key_policy = paramiko.AutoAddPolicy()
            elif isinstance(missing_key_policy, basestring):
                # To make it configurable, allow string to be mapped to object.
                if missing_key_policy == paramiko.AutoAddPolicy().__class__.\
                        __name__:
                    missing_key_policy = paramiko.AutoAddPolicy()
                elif missing_key_policy == paramiko.RejectPolicy().__class__.\
                        __name__:
                    missing_key_policy = paramiko.RejectPolicy()
                elif missing_key_policy == paramiko.WarningPolicy().__class__.\
                        __name__:
                    missing_key_policy = paramiko.WarningPolicy()
                else:
                    raise exceptions.SSHException(
                        "Invalid missing_key_policy: %s" % missing_key_policy
                    )

            ssh.set_missing_host_key_policy(missing_key_policy)

            self.ssh = ssh
        except Exception as e:
            msg = "Error connecting via ssh: %s" % e
            self._logger.error(msg)
            raise paramiko.SSHException(msg)
예제 #16
0
    def __init__(self, machine, **kwargs):
        """
        Initialize the SshTransport class.

        :param machine: the machine to connect to
        :param load_system_host_keys: (optional, default False)
           if False, do not load the system host keys
        :param key_policy: (optional, default = paramiko.RejectPolicy())
           the policy to use for unknown keys

        Other parameters valid for the ssh connect function (see the
        self._valid_connect_params list) are passed to the connect
        function (as port, username, password, ...); taken from the
        accepted paramiko.SSHClient.connect() params.
        """
        import paramiko
        super(SshTransport, self).__init__()

        self._is_open = False
        self._sftp = None
        self._proxy = None

        self._machine = machine

        self._client = paramiko.SSHClient()
        self._load_system_host_keys = kwargs.pop('load_system_host_keys', False)
        if self._load_system_host_keys:
            self._client.load_system_host_keys()

        self._safe_open_interval = kwargs.pop('safe_interval', self._DEFAULT_SAFE_OPEN_INTERVAL)

        self._missing_key_policy = kwargs.pop('key_policy', 'RejectPolicy')  # This is paramiko default
        if self._missing_key_policy == 'RejectPolicy':
            self._client.set_missing_host_key_policy(paramiko.RejectPolicy())
        elif self._missing_key_policy == 'WarningPolicy':
            self._client.set_missing_host_key_policy(paramiko.WarningPolicy())
        elif self._missing_key_policy == 'AutoAddPolicy':
            self._client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        else:
            raise ValueError('Unknown value of the key policy, allowed values '
                             'are: RejectPolicy, WarningPolicy, AutoAddPolicy')

        self._connect_args = {}
        for k in self._valid_connect_params:
            try:
                self._connect_args[k] = kwargs.pop(k)
            except KeyError:
                pass

        if kwargs:
            raise ValueError('The following parameters were not accepted by '
                             'the transport: {}'.format(','.join(str(k) for k in kwargs)))
예제 #17
0
    def test_12_reject_policy(self):
        """
        verify that SSHClient's RejectPolicy works.
        """
        threading.Thread(target=self._run).start()

        self.tc = paramiko.SSHClient()
        self.tc.set_missing_host_key_policy(paramiko.RejectPolicy())
        self.assertEqual(0, len(self.tc.get_host_keys()))
        self.assertRaises(paramiko.SSHException,
                          self.tc.connect,
                          password='******',
                          **self.connect_kwargs)
예제 #18
0
    def _client_host_key_good(self, ktype, kfile):
        threading.Thread(target=self._run).start()
        hostname = '[%s]:%d' % (self.addr, self.port)

        self.tc = paramiko.SSHClient()
        self.tc.set_missing_host_key_policy(paramiko.RejectPolicy())
        host_key = ktype.from_private_key_file(_support(kfile))
        known_hosts = self.tc.get_host_keys()
        known_hosts.add(hostname, host_key.get_name(), host_key)

        self.tc.connect(password='******', **self.connect_kwargs)
        self.event.wait(1.0)
        self.assertTrue(self.event.is_set())
        self.assertTrue(self.ts.is_active())
        self.assertEqual(True, self.ts.is_authenticated())
예제 #19
0
 def client(self, uid):
     private_key_path, _ = self._users[uid]
     c = paramiko.SSHClient()
     host_keys = c.get_host_keys()
     key = paramiko.RSAKey.from_private_key_file(SERVER_KEY_PATH)
     host_keys.add(self.host, "ssh-rsa", key)
     host_keys.add("[%s]:%d" % (self.host, self.port), "ssh-rsa", key)
     c.set_missing_host_key_policy(paramiko.RejectPolicy())
     c.connect(hostname=self.host,
               port=self.port,
               username=uid,
               key_filename=private_key_path,
               allow_agent=False,
               look_for_keys=False)
     return c
예제 #20
0
    def test_13_reject_policy_gsskex(self):
        """
        verify that SSHClient's RejectPolicy works,
        even if gssapi-keyex was enabled but not used.
        """
        # Test for a bug present in paramiko versions released before 2017-08-01
        threading.Thread(target=self._run).start()

        self.tc = paramiko.SSHClient()
        self.tc.set_missing_host_key_policy(paramiko.RejectPolicy())
        self.assertEqual(0, len(self.tc.get_host_keys()))
        self.assertRaises(paramiko.SSHException,
                          self.tc.connect,
                          password='******',
                          gss_kex=True,
                          **self.connect_kwargs)
예제 #21
0
파일: ssh.py 프로젝트: dbribe/DemoANPR
    def __init__(self, machine_handler, user="******", auto_add=False):
        # TODO: This class should not use a machine handler, but rather just an ip and a logger class
        self.machine_handler = machine_handler
        self.address = machine_handler.private_ip_address
        self.user = user
        self.client = paramiko.SSHClient()
        self.client.load_system_host_keys()
        if auto_add:
            self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        else:
            self.client.set_missing_host_key_policy(paramiko.RejectPolicy())

        self.client.connect(self.address, username=user)

        #TODO: mciucu - make a global lazyprop decorator, and then use that to wrap ftp_client
        self.ftp_client = self.client.open_sftp()
 def __init__(self,
              host,
              port,
              username,
              password,
              accept_all_keys=False,
              host_key_file=None,
              use_system_hosts=False,
              timeout=10,
              timeout_limit=3):
     """
     Create a new SSH connection wrapper.
     :param host:  Hostname of the Server  to connect to.
     :param port:  Ts3Server SSH port.
     :param username:  Serverquery username
     :param password:  Serverquery password
     :param accept_all_keys:  Accept all host keys (dangerous!) (default=false)
     :param host_key_file:  Path to the host key file to use (default=None)
     :param use_system_hosts:  Should the system known hosts be used? (default=False)
     :param timeout:  Timeout in seconds (default=10)
     :param timeout_limit:   How often a timeout is allowed to happen while reading before we
                             assume the server connection died. (default=3)
     """
     self._buffer = b""
     self._ssh_conn = paramiko.SSHClient()
     if accept_all_keys:
         self._ssh_conn.set_missing_host_key_policy(
             paramiko.AutoAddPolicy())
     else:
         self._ssh_conn.set_missing_host_key_policy(paramiko.RejectPolicy())
     if use_system_hosts:
         self._ssh_conn.load_system_host_keys()
     if host_key_file is not None and isfile(host_key_file):
         self._ssh_conn.load_host_keys(host_key_file)
     if username is not None and password is not None:
         self._ssh_conn.connect(host,
                                port=port,
                                username=username,
                                password=password)
         if host_key_file is not None:
             self._ssh_conn.save_host_keys(host_key_file)
         self._channel = self._ssh_conn.invoke_shell("raw")
         self._channel.settimeout(timeout)
         self.timeout_limit = timeout_limit
     else:
         raise TS3Exception("Connecting via ssh requires a password.")
예제 #23
0
    def create(self):
        try:
            ssh = paramiko.SSHClient()
            if ',' in self.hosts_key_file:
                files = self.hosts_key_file.split(',')
                for f in files:
                    ssh.load_host_keys(f)
            else:
                ssh.load_host_keys(self.hosts_key_file)
            # If strict_ssh_host_key_policy is set we want to reject, by
            # default if there is not entry in the known_hosts file.
            # Otherwise we use AutoAddPolicy which accepts on the first
            # Connect but fails if the keys change.  load_host_keys can
            # handle hashed known_host entries.
            if self.strict_ssh_host_key_policy:
                ssh.set_missing_host_key_policy(paramiko.RejectPolicy())
            else:
                ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

            if self.password:
                ssh.connect(self.ip,
                            port=self.port,
                            username=self.login,
                            password=self.password,
                            timeout=self.conn_timeout)
            elif self.privatekey:
                pkfile = os.path.expanduser(self.privatekey)
                privatekey = paramiko.RSAKey.from_private_key_file(pkfile)
                ssh.connect(self.ip,
                            port=self.port,
                            username=self.login,
                            pkey=privatekey,
                            timeout=self.conn_timeout)
            else:
                msg = _("Specify a password or private_key")
                raise exception.CinderException(msg)

            if self.conn_timeout:
                transport = ssh.get_transport()
                transport.set_keepalive(self.conn_timeout)
            return ssh
        except Exception as e:
            msg = _("Error connecting via ssh: %s") % six.text_type(e)
            LOG.error(msg)
            raise paramiko.SSHException(msg)
예제 #24
0
    def open_sftp_connection(self, options):
        host = self.get_option("host", options)
        port = self.get_option("port", options)
        user = self.get_option("user", options)
        password = self.get_option("password", options)
        ssh_priv_key = self.get_option("privateKeyPath", options)
        ssh_priv_key_pass = self.get_option("privateKeyPass", options)

        # delete files
        try:
            current_app.logger.debug(
                "Connecting to {0}@{1}:{2}".format(user, host, port)
            )
            ssh = paramiko.SSHClient()

            # allow connection to the new unknown host
            ssh.set_missing_host_key_policy(paramiko.RejectPolicy())

            # open the ssh connection
            if password:
                current_app.logger.debug("Using password")
                ssh.connect(host, username=user, port=port, password=password)
            elif ssh_priv_key:
                current_app.logger.debug("Using RSA private key")
                pkey = paramiko.RSAKey.from_private_key_file(
                    ssh_priv_key, ssh_priv_key_pass
                )
                ssh.connect(host, username=user, port=port, pkey=pkey)
            else:
                current_app.logger.error(
                    "No password or private key provided. Can't proceed"
                )
                raise AuthenticationException

            # open the sftp session inside the ssh connection
            return ssh.open_sftp(), ssh

        except AuthenticationException as e:
            current_app.logger.error("ERROR in {0}: {1}".format(e.__class__, e))
            raise AuthenticationException("Couldn't connect to {0}, due to an Authentication exception.")
        except NoValidConnectionsError as e:
            current_app.logger.error("ERROR in {0}: {1}".format(e.__class__, e))
            raise NoValidConnectionsError("Couldn't connect to {0}, possible timeout or invalid hostname")
예제 #25
0
    def _get_ssh_client(self, host):
        """
        Create a SSH Client based on host, username and password if provided.
        If there is any AuthenticationException/SSHException, raise HTTP Error 403 as permission denied.

        :param host:
        :return: ssh client instance
        """
        ssh = None

        global remote_user
        global remote_pwd
        if remote_user is None:
            remote_user = os.getenv('RP_REMOTE_USER', getpass.getuser())
            remote_pwd = os.getenv(
                'RP_REMOTE_PWD')  # this should use password-less ssh

        try:
            ssh = paramiko.SSHClient()
            ssh.load_system_host_keys()
            ssh.set_missing_host_key_policy(paramiko.RejectPolicy())
            host_ip = gethostbyname(host)
            if remote_pwd:
                ssh.connect(host_ip,
                            port=ssh_port,
                            username=remote_user,
                            password=remote_pwd)
            else:
                ssh.connect(host_ip, port=ssh_port, username=remote_user)
        except Exception as e:
            current_host = gethostbyname(gethostname())
            error_message = "Exception '{}' occurred when creating a SSHClient at {} connecting " \
                            "to '{}:{}' with user '{}', message='{}'.". \
                format(type(e).__name__, current_host, host, ssh_port, remote_user, e)
            if e is paramiko.SSHException or paramiko.AuthenticationException:
                error_message_prefix = "Failed to authenticate SSHClient with password"
                error_message = error_message_prefix + (
                    " provided" if remote_pwd else "-less SSH")
                self.log_and_raise(PermissionError(error_message))
            self.log_and_raise(RuntimeError(error_message))
        return ssh
예제 #26
0
    def _ssh_authentication(self) -> None:
        """Search/add/save the servers key for the SSH authentication process"""

        # set to reject policy (avoid MITM attacks)
        self._socket.set_missing_host_key_policy(paramiko.RejectPolicy())
        # openssh is posix, so this might only a posix approach
        # https://stackoverflow.com/q/32945533
        try:
            # load the keys into paramiko and check if remote is in the list
            self._socket.load_host_keys(filename=self.known_hosts_file)
        except OSError as e:
            if e.errno != errno.ENOENT:
                raise GvmError("Something went wrong with reading "
                               f"the known_hosts file: {e}") from None
        hostkeys = self._socket.get_host_keys()
        if not hostkeys.lookup(self.hostname):
            # Key not found, so connect to remote and fetch the key
            # with the paramiko Transport protocol
            key = self._get_remote_host_key()

            self._ssh_authentication_input_loop(hostkeys=hostkeys, key=key)
예제 #27
0
    def __init__(self,
                 host,
                 path,
                 fnpattern,
                 username=None,
                 password=None,
                 port=22,
                 ssh_id=None,
                 ssh_hostkey=None,
                 ssh_unknown_hosts=False,
                 n_tries=1):

        self.log = logging.getLogger('msschem')

        if not _PARAMIKO:
            raise ImportError('Cannot import paramiko, which is needed for '
                              'SCPDownload')
        if LooseVersion(paramiko.__version__) < LooseVersion('2.2'):
            self.log.warn('Downloading via SCP with ed25519 hostkeys won\'t '
                          'work (paramiko version < 2.2)')

        self.host = host
        self.path = path
        self.fnpattern = fnpattern
        self.username = username
        self.password = password
        if __pymsschem__ == 3:
            self.password = self.password.encode()
        self.port = port
        self.ssh_id = ssh_id
        self.n_tries = n_tries

        self._ssh = paramiko.SSHClient()
        self._ssh.load_system_host_keys()
        if ssh_hostkey is not None:
            self._ssh.load_host_keys(ssh_hostkey)
        if ssh_unknown_hosts:
            self._ssh.set_missing_host_key_policy(paramiko.WarningPolicy())
        else:
            self._ssh.set_missing_host_key_policy(paramiko.RejectPolicy())
예제 #28
0
    def connect_interactive(self):
        """ Establishes SSH connection """

        newssh = paramiko.SSHClient()

        # suppress SSH key warnings
        if not self.key_verify:
            newssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        else:
            newssh.set_missing_host_key_policy(paramiko.RejectPolicy())

        print(f'connecting to {self.nodeip}...')
        try:
            newssh.connect(self.nodeip, username=self.userid, password=self.pw)
        except:
            return {
                'fault':
                f"Error connecting to {self.nodeip}: {sys.exc_info()[:2]}"
            }

        print(
            f'connected, waiting max of {self.prompt_timeout} seconds for {self.msg_initprompt}...'
        )

        new_interactive = newssh.invoke_shell()

        init_time = time()

        while (time() - init_time) < self.prompt_timeout:
            output = new_interactive.recv(8000).decode('UTF-8')
            if self.prompt in output:
                print(
                    f'prompt detected. ({round(time() - init_time,1)} seconds)'
                )
                return new_interactive

        return {
            'fault':
            f"{self.prompt_timeout}{self.msg_timerexp}{self.msg_initprompt}"
        }
예제 #29
0
    def do_connect(self, args):
        # Connect to all hosts in the hosts list
        for host in self.hosts:
            try:
                client = paramiko.SSHClient()
                try:
                    if not os.path.exists(host_keys):
                        with open(host_keys, 'w+') as create:
                            create.close()
                    client.load_host_keys(host_keys)
                except Exception as err:
                    logger.error(err)
                client.set_missing_host_key_policy(paramiko.RejectPolicy())
                client.connect(host['hostname'],
                               username=host['username'],
                               password=decrypt_password(host['ePassword']))
                self.connections.append(client)
                self.count += 1
            except paramiko.AuthenticationException as err:
                err = host['hostname'] + ' ' + err
                logger.error(err)
            except paramiko.SSHException as err:
                print(err)
                add_host = input(
                    'Do you want to add the host to known hosts? y/n: ')
                if add_host == 'y':
                    client.set_missing_host_key_policy(
                        paramiko.AutoAddPolicy())
                    client.connect(host['hostname'],
                                   username=host['username'],
                                   password=decrypt_password(
                                       host['ePassword']))
                    self.connections.append(client)
                    self.count += 1
                logger.error(err)
            except Exception as err:
                err = '{} {}'.format(host['hostname'], err)
                logger.error(err)

        self.prompt = 'ssh {} connected> '.format(self.count)
예제 #30
0
파일: ssh.py 프로젝트: kazhr/config
    def __init__(self,
                 hostname,
                 username,
                 password,
                 ssh_port=22,
                 policy="AutoAdd",
                 timeout=5):

        policy = {
            "AutoAdd": paramiko.AutoAddPolicy(),
            "Warning": paramiko.WarningPolicy(),
            "Reject": paramiko.RejectPolicy(),
        }[policy]

        self.client = paramiko.SSHClient()
        self.client.set_missing_host_key_policy(policy)

        self.hostname = hostname
        self.username = username
        self.password = password
        self.ssh_port = ssh_port
        self.timeout = timeout