Пример #1
0
    def __init__(self,
                 hostname,
                 username=None,
                 password=None,
                 port=22,
                 private_key=None,
                 connect_timeout=None,
                 missing_host_key=None,
                 sock=None):
        super(SshShell, self).__init__(hostname=hostname,
                                       username=username,
                                       password=password,
                                       port=port,
                                       connect_timeout=connect_timeout,
                                       missing_host_key=missing_host_key)

        try:
            self._pkey = RSAKey.from_private_key(StringIO(private_key))
        except SSHException:
            try:
                self._pkey = DSSKey.from_private_key(StringIO(private_key))
            except SSHException:
                raise ValidatorException("Unknown private key format")

        self._sock = sock
Пример #2
0
    def from_line(cls, line):
        """
        Parses the given line of text to find the names for the host,
        the type of key, and the key data. The line is expected to be in the
        format used by the openssh known_hosts file.

        Lines are expected to not have leading or trailing whitespace.
        We don't bother to check for comments or empty lines.  All of
        that should be taken care of before sending the line to us.

        @param line: a line from an OpenSSH known_hosts file
        @type line: str
        """
        fields = line.split(' ')
        if len(fields) < 3:
            # Bad number of fields
            return None
        fields = fields[:3]

        names, keytype, key = fields
        names = names.split(',')

        # Decide what kind of key we're looking at and create an object
        # to hold it accordingly.
        if keytype == 'ssh-rsa':
            key = RSAKey(data=base64.decodestring(key))
        elif keytype == 'ssh-dss':
            key = DSSKey(data=base64.decodestring(key))
        else:
            return None

        return cls(names, key)
Пример #3
0
    def generatekey(self):
        public_key = StringIO()
        private_key = StringIO()
        public_key_value = None
        private_key_value = None
        try:
            if self.keytype == 'rsa':
                key = RSAKey.generate(self.rsabits)
            elif self.keytype == 'ecdsa':
                key = ECDSAKey.generate(bits=self.ecdsabits)
            elif self.keytype == 'dss':
                key = DSSKey.generate(bits=self.dssbits)
            else:
                return None, "sshkey暂时不支持其它类型 %s" % self.keytype
            key.write_private_key(private_key)
            public_key.write("%s %s %s" %
                             (key.get_name(), key.get_base64(), self.basename))
            public_key_value = public_key.getvalue()
            private_key_value = private_key.getvalue()
            cache.set("user_%s_private_key" % self.username, private_key_value)
            cache.set("user_%s_public_key" % self.username, public_key_value)

        except Exception as e:
            logger.error(e.args)
            return None, e.args
        finally:
            public_key.close()
            private_key.close()
        return {
            "publickey": public_key_value,
            "privatekey": private_key_value
        }, None
Пример #4
0
    def __init__(self,
                 hostname,
                 username=None,
                 password=None,
                 port=22,
                 private_key=None,
                 connect_timeout=None,
                 missing_host_key=None,
                 sock=None):
        super(SshShell, self).__init__(hostname=hostname,
                                       username=username,
                                       password=password,
                                       port=port,
                                       connect_timeout=connect_timeout,
                                       missing_host_key=missing_host_key)

        try:
            self._pkey = RSAKey.from_private_key(StringIO(private_key))
        except SSHException:
            try:
                self._pkey = DSSKey.from_private_key(StringIO(private_key))
            except SSHException:
                raise ValidatorException("Unknown private key format")

        self._sock = sock
Пример #5
0
def parse_private_key(private_key):
    try:
        return RSAKey.from_private_key(StringIO(private_key))
    except SSHException:
        try:
            return DSSKey.from_private_key(StringIO(private_key))
        except SSHException:
            return None
Пример #6
0
def _parse_dsa_key(msg):
    # See comment for _parse_rsa_key
    key_msg = Message()
    key_msg.add_string('ssh-dss')
    key_msg.add_mpint(msg.get_mpint())
    key_msg.add_mpint(msg.get_mpint())
    key_msg.add_mpint(msg.get_mpint())
    key_msg.add_mpint(msg.get_mpint())
    key_msg.rewind()
    return DSSKey(msg=key_msg)
Пример #7
0
    def assignKey(self, key):
        self.origKey = key
        # dump key to file
        self.dumpKey(self.keyPath, self.origKey)

        try:
            self._pkey = RSAKey.from_private_key(StringIO(self.origKey))
        except paramiko.SSHException:
            try:
                self._pkey = DSSKey.from_private_key(StringIO(self.origKey))
            except paramiko.SSHException:
                raise "Unknown private key format"
Пример #8
0
    def load_pkey(clasobj, keytype, location):
        kt = keytype.upper()
        if kt == "RSA":
            return RSAKey.from_private_key_file(location)

        elif kt == "DSA":
            return DSSKey.from_private_key_file(location)

        else:
            raise Exception(
                "Unknown key type '{0}' in sftp_account::load_pkey".format(
                    keytype))
Пример #9
0
    def assignKey(self, key):
        self.origKey = key
        # dump key to file
        self.dumpKey(self.keyPath, self.origKey)

        try:
            self._pkey = RSAKey.from_private_key(StringIO(self.origKey))
        except paramiko.SSHException:
            try:
                self._pkey = DSSKey.from_private_key(StringIO(self.origKey))
            except paramiko.SSHException:
                raise "Unknown private key format"
Пример #10
0
    def from_line(cls, line, lineno=None):
        """
        Parses the given line of text to find the names for the host,
        the type of key, and the key data. The line is expected to be in the
        format used by the OpenSSH known_hosts file.

        Lines are expected to not have leading or trailing whitespace.
        We don't bother to check for comments or empty lines.  All of
        that should be taken care of before sending the line to us.

        :param str line: a line from an OpenSSH known_hosts file
        """
        log = get_logger("paramiko.hostkeys")
        fields = line.split(" ")
        if len(fields) < 3:
            # Bad number of fields
            msg = "Not enough fields found in known_hosts in line {} ({!r})"
            log.info(msg.format(lineno, line))
            return None
        fields = fields[:3]

        names, keytype, key = fields
        names = names.split(",")

        # Decide what kind of key we're looking at and create an object
        # to hold it accordingly.
        try:
            key = b(key)
            if keytype == "ssh-rsa":
                key = RSAKey(data=decodebytes(key))
            elif keytype == "ssh-dss":
                key = DSSKey(data=decodebytes(key))
            elif keytype in ECDSAKey.supported_key_format_identifiers():
                key = ECDSAKey(data=decodebytes(key), validate_point=False)
            elif keytype == "ssh-ed25519":
                key = Ed25519Key(data=decodebytes(key))
            elif keytype == "ssh-xmss":
                key = XMSS(data=decodebytes(key))
            else:
                log.info("Unable to handle key of type {}".format(keytype))
                return None

        except binascii.Error as e:
            raise InvalidHostKey(line, e)

        return cls(names, key)
Пример #11
0
def str_to_key(key_str):
    '''Gets a string with rsa/dsa private key and converts it to paramiko key
    object. Returns RSAKey/DSSKey object if succeeded or None if error occured.'''
    if 'BEGIN RSA' in key_str:
        str_obj = StringIO(key_str)
        try:
            k = RSAKey(file_obj=str_obj)
            return k
        except:
            return None
    elif 'BEGIN DSA' in key_str:
        str_obj = StringIO(key_str)
        try:
            k = DSSKey(file_obj=str_obj)
            return k
        except:
            return None
    else:
        return None
Пример #12
0
    def from_line(cls, line, lineno=None):
        """
        Parses the given line of text to find the names for the host,
        the type of key, and the key data. The line is expected to be in the
        format used by the openssh known_hosts file.

        Lines are expected to not have leading or trailing whitespace.
        We don't bother to check for comments or empty lines.  All of
        that should be taken care of before sending the line to us.

        @param line: a line from an OpenSSH known_hosts file
        @type line: str
        """
        log = get_logger('paramiko.hostkeys')
        fields = line.split(' ')
        if len(fields) < 3:
            # Bad number of fields
            log.info("Not enough fields found in known_hosts in line %s (%r)" %
                     (lineno, line))
            return None
        fields = fields[:3]

        names, keytype, key = fields
        names = names.split(',')

        # Decide what kind of key we're looking at and create an object
        # to hold it accordingly.
        try:
            key = b(key)
            if keytype == 'ssh-rsa':
                key = RSAKey(data=decodebytes(key))
            elif keytype == 'ssh-dss':
                key = DSSKey(data=decodebytes(key))
            elif keytype == 'ecdsa-sha2-nistp256':
                key = ECDSAKey(data=decodebytes(key))
            else:
                log.info("Unable to handle key of type %s" % (keytype, ))
                return None

        except binascii.Error:
            raise InvalidHostKey(line, sys.exc_info()[1])

        return cls(names, key)
Пример #13
0
def test_format_openssh_pubkey():
    rsakey = RSAKey.generate(1024)
    assert parse_openssh_pubkey(format_openssh_pubkey(rsakey)) == rsakey
    dsskey = DSSKey.generate(1024)
    assert parse_openssh_pubkey(format_openssh_pubkey(dsskey)) == dsskey
Пример #14
0
def test_format_openssh_pubkey():
    rsakey = RSAKey.generate(1024)
    assert parse_openssh_pubkey(format_openssh_pubkey(rsakey)) == rsakey
    dsskey = DSSKey.generate(1024)
    assert parse_openssh_pubkey(format_openssh_pubkey(dsskey)) == dsskey