Python paramiko.RSAKey() Examples

The following are 30 code examples of paramiko.RSAKey(). 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 paramiko , or try the search function .
Example #1
Source File: handler.py    From adminset with GNU General Public License v2.0 7 votes vote down vote up
def get_pkey_obj(cls, privatekey, password, filename):
        bpass = to_bytes(password) if password else None

        pkey = cls.get_specific_pkey(paramiko.RSAKey, privatekey, bpass)\
            or cls.get_specific_pkey(paramiko.DSSKey, privatekey, bpass)\
            or cls.get_specific_pkey(paramiko.ECDSAKey, privatekey, bpass)\
            or cls.get_specific_pkey(paramiko.Ed25519Key, privatekey, bpass)

        if not pkey:
            if not password:
                error = 'Invalid private key: {}'.format(filename)
            else:
                error = (
                    'Wrong password {!r} for decrypting the private key.'
                ) .format(password)
            raise InvalidValueError(error)

        return pkey 
Example #2
Source File: utils.py    From diting with GNU General Public License v2.0 7 votes vote down vote up
def ssh_key_gen(length=2048, type='rsa', password=None, username='jumpserver', hostname=None):
    """Generate user ssh private and public key

    Use paramiko RSAKey generate it.
    :return private key str and public key str
    """

    if hostname is None:
        hostname = os.uname()[1]

    f = StringIO()
    try:
        if type == 'rsa':
            private_key_obj = paramiko.RSAKey.generate(length)
        elif type == 'dsa':
            private_key_obj = paramiko.DSSKey.generate(length)
        else:
            raise IOError('SSH private key must be `rsa` or `dsa`')
        private_key_obj.write_private_key(f, password=password)
        private_key = f.getvalue()
        public_key = ssh_pubkey_gen(private_key_obj, username=username, hostname=hostname)
        return private_key, public_key
    except IOError:
        raise IOError('These is error when generate ssh key.') 
Example #3
Source File: helpers.py    From shakedown with Apache License 2.0 7 votes vote down vote up
def validate_key(key_path):
    """ Validate a key

        :param key_path: path to a key to use for authentication
        :type key_path: str

        :return: key object used for authentication
        :rtype: paramiko.RSAKey
    """

    key_path = os.path.expanduser(key_path)

    if not os.path.isfile(key_path):
        return False

    return paramiko.RSAKey.from_private_key_file(key_path) 
Example #4
Source File: test_client.py    From python-hpedockerplugin with Apache License 2.0 6 votes vote down vote up
def test_7_banner_timeout(self):
        """
        verify that the SSHClient has a configurable banner timeout.
        """
        # Start the thread with a 1 second wait.
        threading.Thread(target=self._run, kwargs={'delay': 1}).start()
        host_key = paramiko.RSAKey.from_private_key_file(test_path('test_rsa.key'))
        public_host_key = paramiko.RSAKey(data=host_key.asbytes())

        self.tc = paramiko.SSHClient()
        self.tc.get_host_keys().add('[%s]:%d' % (self.addr, self.port), 'ssh-rsa', public_host_key)
        # Connect with a half second banner timeout.
        kwargs = dict(self.connect_kwargs, banner_timeout=0.5)
        self.assertRaises(
            paramiko.SSHException,
            self.tc.connect,
            **kwargs
        ) 
Example #5
Source File: main.py    From chain with Apache License 2.0 6 votes vote down vote up
def get_pkey(self, privatekey, password):
        password = password.encode('utf-8') if password else None

        pkey = self.get_specific_pkey(paramiko.RSAKey, privatekey, password)\
            or self.get_specific_pkey(paramiko.DSSKey, privatekey, password)\
            or self.get_specific_pkey(paramiko.ECDSAKey, privatekey, password)\
            or self.get_specific_pkey(paramiko.Ed25519Key, privatekey,
                                      password)
        if not pkey:
            raise ValueError('Not a valid private key file or '
                             'wrong password for decrypting the private key.')
        return pkey 
Example #6
Source File: __init__.py    From pyrexecd with MIT License 6 votes vote down vote up
def get_authorized_keys(path):
    keys = []
    with open(path) as fp:
        for line in fp:
            flds = line.split(' ')
            if len(flds) < 2: continue
            if flds[0] == 'ssh-rsa':
                f = paramiko.RSAKey
            elif flds[0] == 'ssh-dss':
                f = paramiko.DSSKey
            elif flds[0].startswith('ecdsa-'):
                f = paramiko.ECDSAKey
            else:
                continue
            data = decodebytes(flds[1].encode('ascii'))
            keys.append(f(data=data))
    return keys

# run_server 
Example #7
Source File: backup_writers.py    From coriolis with GNU Affero General Public License v3.0 6 votes vote down vote up
def _check_deserialize_key(key):
    res = None
    if isinstance(key, paramiko.RSAKey):
        LOG.trace("Key is already in the proper format.")
        res = key
    elif type(key) is str:
        LOG.trace("Deserializing PEM-encoded private key.")
        res = utils.deserialize_key(
            key, CONF.serialization.temp_keypair_password)
    else:
        raise exception.CoriolisException(
            "Private key must be either a PEM-encoded string or "
            "a paramiko.RSAKey instance. Got type '%s'." % (
                type(key)))

    return res 
Example #8
Source File: main.py    From autoops with Apache License 2.0 6 votes vote down vote up
def get_pkey(self, privatekey, password):
        password = password.encode('utf-8') if password else None

        pkey = self.get_specific_pkey(paramiko.RSAKey, privatekey, password)\
            or self.get_specific_pkey(paramiko.DSSKey, privatekey, password)\
            or self.get_specific_pkey(paramiko.ECDSAKey, privatekey, password)\
            or self.get_specific_pkey(paramiko.Ed25519Key, privatekey,
                                      password)
        if not pkey:
            raise ValueError('Not a valid private key file or '
                             'wrong password for decrypting the private key.')
        return pkey 
Example #9
Source File: test_forwarder.py    From sshtunnel with MIT License 5 votes vote down vote up
def test_connect_by_paramiko_key(self):
        """ Test connecting when ssh_private_key is a paramiko.RSAKey """
        ssh_key = paramiko.RSAKey.from_private_key_file(
            get_test_data_path(PKEY_FILE)
        )
        with self._test_server(
            (self.saddr, self.sport),
            ssh_username=SSH_USERNAME,
            ssh_pkey=ssh_key,
            remote_bind_address=(self.eaddr, self.eport),
            logger=self.log,
        ):
            pass 
Example #10
Source File: utils.py    From diting with GNU General Public License v2.0 5 votes vote down vote up
def ssh_key_string_to_obj(text, password=None):
    key = None
    try:
        key = paramiko.RSAKey.from_private_key(StringIO(text), password=password)
    except paramiko.SSHException:
        pass

    try:
        key = paramiko.DSSKey.from_private_key(StringIO(text), password=password)
    except paramiko.SSHException:
        pass
    return key 
Example #11
Source File: utils.py    From diting with GNU General Public License v2.0 5 votes vote down vote up
def ssh_pubkey_gen(private_key=None, username='jumpserver', hostname='localhost', password=None):
    if isinstance(private_key, bytes):
        private_key = private_key.decode("utf-8")
    if isinstance(private_key, string_types):
        private_key = ssh_key_string_to_obj(private_key, password=password)
    if not isinstance(private_key, (paramiko.RSAKey, paramiko.DSSKey)):
        raise IOError('Invalid private key')

    public_key = "%(key_type)s %(key_content)s %(username)s@%(hostname)s" % {
        'key_type': private_key.get_name(),
        'key_content': private_key.get_base64(),
        'username': username,
        'hostname': hostname,
    }
    return public_key 
Example #12
Source File: pshitt.py    From pshitt with GNU General Public License v3.0 5 votes vote down vote up
def _setup_paramiko(self):
        paramiko.util.log_to_file(self.args.log, level=self.loglevel)
        self.host_key = paramiko.RSAKey(filename=self.args.key) 
Example #13
Source File: ssh_client.py    From credcheck with MIT License 5 votes vote down vote up
def ssh_connect(self):
        key = paramiko.RSAKey(data=base64.b64decode(b"AAA..."))
        client = paramiko.SSHClient()
        client.get_host_keys().add("ssh.example.com", "ssh-rsa", key)
        client.connect("ssh.example.com", username="strongbad", password="thecheat") 
Example #14
Source File: validate.py    From zimfarm with GNU General Public License v3.0 5 votes vote down vote up
def ssh_key():
    """
    Validate ssh public keys exists and matches with username
    """

    # validate request json
    class KeySchema(Schema):
        username = fields.String(required=True, validate=validate.Length(min=1))
        key = fields.String(required=True, validate=validate.Length(min=1))

    try:
        request_json = KeySchema().load(request.get_json())
    except ValidationError as e:
        raise errors.InvalidRequestJSON(e.messages)

    # compute fingerprint
    try:
        key = request_json["key"]
        rsa_key = paramiko.RSAKey(data=base64.b64decode(key))
        fingerprint = binascii.hexlify(rsa_key.get_fingerprint()).decode()
    except (binascii.Error, paramiko.SSHException):
        raise errors.BadRequest("Invalid RSA key")

    # database
    username = request_json["username"]
    user = Users().update_one(
        {
            "username": username,
            "ssh_keys": {"$elemMatch": {"fingerprint": fingerprint}},
        },
        {"$set": {"ssh_keys.$.last_used": datetime.now()}},
    )

    if user.matched_count == 0:
        raise errors.Unauthorized()
    return Response(status=HTTPStatus.NO_CONTENT) 
Example #15
Source File: test_forwarder.py    From sshtunnel with MIT License 5 votes vote down vote up
def _run_ssh_server(self):
        self.log.info('ssh-server Start')
        try:
            self.socks, addr = self.ssockl.accept()
        except socket.timeout:
            self.log.error('ssh-server connection timed out!')
            self.running_threads.remove('ssh-server')
            return
        self.ts = paramiko.Transport(self.socks)
        host_key = paramiko.RSAKey.from_private_key_file(
            get_test_data_path(PKEY_FILE)
        )
        self.ts.add_server_key(host_key)
        server = NullServer(allowed_keys=FINGERPRINTS.keys(),
                            log=self.log)
        t = threading.Thread(target=self._do_forwarding,
                             name='forward-server')
        t.daemon = DAEMON_THREADS
        self.running_threads.append(t.name)
        self.threads[t.name] = t
        t.start()
        self.ts.start_server(self.ssh_event, server)
        self.wait_for_thread(t,
                             timeout=None,
                             who='ssh-server')
        self.log.info('ssh-server shutting down')
        self.running_threads.remove('ssh-server') 
Example #16
Source File: patator_ext.py    From project-black with GNU General Public License v2.0 5 votes vote down vote up
def load_keyfile(keyfile):
  for cls in (paramiko.RSAKey, paramiko.DSSKey, paramiko.ECDSAKey):
    try:
      return cls.from_private_key_file(keyfile)
    except paramiko.SSHException:
      pass
  else:
    raise 
Example #17
Source File: test_forwarder.py    From sshtunnel with MIT License 5 votes vote down vote up
def test_read_private_key_file(self):
        """ Test that an encrypted private key can be opened """
        encr_pkey = get_test_data_path(ENCRYPTED_PKEY_FILE)
        pkey = sshtunnel.SSHTunnelForwarder.read_private_key_file(
            encr_pkey,
            pkey_password='sshtunnel',
            logger=self.log
        )
        _pkey = paramiko.RSAKey.from_private_key_file(
            get_test_data_path(PKEY_FILE)
        )
        self.assertEqual(pkey, _pkey)

        # Using a wrong password returns None
        self.assertIsNone(sshtunnel.SSHTunnelForwarder.read_private_key_file(
            encr_pkey,
            pkey_password='bad password',
            logger=self.log
        ))
        self.assertIn("Private key file ({0}) could not be loaded as type "
                      "{1} or bad password"
                      .format(encr_pkey, type(_pkey)),
                      self.sshtunnel_log_messages['debug'])
        # Using no password on an encrypted key returns None
        self.assertIsNone(sshtunnel.SSHTunnelForwarder.read_private_key_file(
            encr_pkey,
            logger=self.log
        ))
        self.assertIn('Password is required for key {0}'.format(encr_pkey),
                      self.sshtunnel_log_messages['error']) 
Example #18
Source File: test_kex_gss.py    From python-hpedockerplugin with Apache License 2.0 5 votes vote down vote up
def _run(self):
        self.socks, addr = self.sockl.accept()
        self.ts = paramiko.Transport(self.socks, gss_kex=True)
        host_key = paramiko.RSAKey.from_private_key_file('tests/test_rsa.key')
        self.ts.add_server_key(host_key)
        self.ts.set_gss_host(targ_name)
        try:
            self.ts.load_server_moduli()
        except:
            print ('(Failed to load moduli -- gex will be unsupported.)')
        server = NullServer()
        self.ts.start_server(self.event, server) 
Example #19
Source File: test_kex_gss.py    From python-hpedockerplugin with Apache License 2.0 5 votes vote down vote up
def _test_gsskex_and_auth(self, gss_host, rekey=False):
        """
        Verify that Paramiko can handle SSHv2 GSS-API / SSPI authenticated
        Diffie-Hellman Key Exchange and user authentication with the GSS-API
        context created during key exchange.
        """
        host_key = paramiko.RSAKey.from_private_key_file('tests/test_rsa.key')
        public_host_key = paramiko.RSAKey(data=host_key.asbytes())

        self.tc = paramiko.SSHClient()
        self.tc.get_host_keys().add('[%s]:%d' % (self.hostname, self.port),
                                    'ssh-rsa', public_host_key)
        self.tc.connect(self.hostname, self.port, username=self.username,
                        gss_auth=True, gss_kex=True, gss_host=gss_host)

        self.event.wait(1.0)
        self.assert_(self.event.is_set())
        self.assert_(self.ts.is_active())
        self.assertEquals(self.username, self.ts.get_username())
        self.assertEquals(True, self.ts.is_authenticated())
        self.assertEquals(True, self.tc.get_transport().gss_kex_used)

        stdin, stdout, stderr = self.tc.exec_command('yes')
        schan = self.ts.accept(1.0)
        if rekey:
            self.tc.get_transport().renegotiate_keys()

        schan.send('Hello there.\n')
        schan.send_stderr('This is on stderr.\n')
        schan.close()

        self.assertEquals('Hello there.\n', stdout.readline())
        self.assertEquals('', stdout.readline())
        self.assertEquals('This is on stderr.\n', stderr.readline())
        self.assertEquals('', stderr.readline())

        stdin.close()
        stdout.close()
        stderr.close() 
Example #20
Source File: test_ssh_gss.py    From python-hpedockerplugin with Apache License 2.0 5 votes vote down vote up
def _run(self):
        self.socks, addr = self.sockl.accept()
        self.ts = paramiko.Transport(self.socks)
        host_key = paramiko.RSAKey.from_private_key_file('tests/test_rsa.key')
        self.ts.add_server_key(host_key)
        server = NullServer()
        self.ts.start_server(self.event, server) 
Example #21
Source File: test_ssh_gss.py    From python-hpedockerplugin with Apache License 2.0 5 votes vote down vote up
def _test_connection(self, **kwargs):
        """
        (Most) kwargs get passed directly into SSHClient.connect().

        The exception is ... no exception yet
        """
        host_key = paramiko.RSAKey.from_private_key_file('tests/test_rsa.key')
        public_host_key = paramiko.RSAKey(data=host_key.asbytes())

        self.tc = paramiko.SSHClient()
        self.tc.set_missing_host_key_policy(paramiko.WarningPolicy())
        self.tc.get_host_keys().add('[%s]:%d' % (self.addr, self.port),
                                    'ssh-rsa', public_host_key)
        self.tc.connect(hostname=self.addr, port=self.port, username=self.username, gss_host=self.hostname,
                        gss_auth=True, **kwargs)

        self.event.wait(1.0)
        self.assert_(self.event.is_set())
        self.assert_(self.ts.is_active())
        self.assertEquals(self.username, self.ts.get_username())
        self.assertEquals(True, self.ts.is_authenticated())

        stdin, stdout, stderr = self.tc.exec_command('yes')
        schan = self.ts.accept(1.0)

        schan.send('Hello there.\n')
        schan.send_stderr('This is on stderr.\n')
        schan.close()

        self.assertEquals('Hello there.\n', stdout.readline())
        self.assertEquals('', stdout.readline())
        self.assertEquals('This is on stderr.\n', stderr.readline())
        self.assertEquals('', stderr.readline())

        stdin.close()
        stdout.close()
        stderr.close() 
Example #22
Source File: test_hostkeys.py    From python-hpedockerplugin with Apache License 2.0 5 votes vote down vote up
def test_2_add(self):
        hostdict = paramiko.HostKeys('hostfile.temp')
        hh = '|1|BMsIC6cUIP2zBuXR3t2LRcJYjzM=|hpkJMysjTk/+zzUUzxQEa2ieq6c='
        key = paramiko.RSAKey(data=decodebytes(keyblob))
        hostdict.add(hh, 'ssh-rsa', key)
        self.assertEqual(3, len(list(hostdict)))
        x = hostdict['foo.example.com']
        fp = hexlify(x['ssh-rsa'].get_fingerprint()).upper()
        self.assertEqual(b'7EC91BB336CB6D810B124B1353C32396', fp)
        self.assertTrue(hostdict.check('foo.example.com', key)) 
Example #23
Source File: test_client.py    From python-hpedockerplugin with Apache License 2.0 5 votes vote down vote up
def _run(self, allowed_keys=None, delay=0):
        if allowed_keys is None:
            allowed_keys = FINGERPRINTS.keys()
        self.socks, addr = self.sockl.accept()
        self.ts = paramiko.Transport(self.socks)
        keypath = test_path('test_rsa.key')
        host_key = paramiko.RSAKey.from_private_key_file(keypath)
        self.ts.add_server_key(host_key)
        keypath = test_path('test_ecdsa_256.key')
        host_key = paramiko.ECDSAKey.from_private_key_file(keypath)
        self.ts.add_server_key(host_key)
        server = NullServer(allowed_keys=allowed_keys)
        if delay:
            time.sleep(delay)
        self.ts.start_server(self.event, server) 
Example #24
Source File: test_client.py    From python-hpedockerplugin with Apache License 2.0 5 votes vote down vote up
def test_5_save_host_keys(self):
        """
        verify that SSHClient correctly saves a known_hosts file.
        """
        warnings.filterwarnings('ignore', 'tempnam.*')

        host_key = paramiko.RSAKey.from_private_key_file(test_path('test_rsa.key'))
        public_host_key = paramiko.RSAKey(data=host_key.asbytes())
        fd, localname = mkstemp()
        os.close(fd)

        client = paramiko.SSHClient()
        self.assertEquals(0, len(client.get_host_keys()))

        host_id = '[%s]:%d' % (self.addr, self.port)

        client.get_host_keys().add(host_id, 'ssh-rsa', public_host_key)
        self.assertEquals(1, len(client.get_host_keys()))
        self.assertEquals(public_host_key, client.get_host_keys()[host_id]['ssh-rsa'])

        client.save_host_keys(localname)

        with open(localname) as fd:
            assert host_id in fd.read()

        os.unlink(localname) 
Example #25
Source File: test_client.py    From python-hpedockerplugin with Apache License 2.0 5 votes vote down vote up
def test_host_key_negotiation_2(self):
        host_key = paramiko.RSAKey.generate(2048)
        self._client_host_key_bad(host_key) 
Example #26
Source File: helpers.py    From shakedown with Apache License 2.0 5 votes vote down vote up
def get_transport(host, username, key):
    """ Create a transport object

        :param host: the hostname to connect to
        :type host: str
        :param username: SSH username
        :type username: str
        :param key: key object used for authentication
        :type key: paramiko.RSAKey

        :return: a transport object
        :rtype: paramiko.Transport
    """

    if host == shakedown.master_ip():
        transport = paramiko.Transport(host)
    else:
        transport_master = paramiko.Transport(shakedown.master_ip())
        transport_master = start_transport(transport_master, username, key)

        if not transport_master.is_authenticated():
            print("error: unable to authenticate {}@{} with key {}".format(username, shakedown.master_ip(), key))
            return False

        try:
            channel = transport_master.open_channel('direct-tcpip', (host, 22), ('127.0.0.1', 0))
        except paramiko.SSHException:
            print("error: unable to connect to {}".format(host))
            return False

        transport = paramiko.Transport(channel)

    return transport 
Example #27
Source File: server.py    From mock-ssh-server with MIT License 5 votes vote down vote up
def __init__(self, server, client_conn):
        self.server = server
        self.thread = None
        self.command_queues = {}
        client, _ = client_conn
        self.transport = t = paramiko.Transport(client)
        t.add_server_key(paramiko.RSAKey(filename=SERVER_KEY_PATH))
        t.set_subsystem_handler("sftp", sftp.SFTPServer) 
Example #28
Source File: server.py    From mock-ssh-server with MIT License 5 votes vote down vote up
def add_user(self, uid, private_key_path, keytype="ssh-rsa"):
        if keytype == "ssh-rsa":
            key = paramiko.RSAKey.from_private_key_file(private_key_path)
        elif keytype == "ssh-dss":
            key = paramiko.DSSKey.from_private_key_file(private_key_path)
        elif keytype in paramiko.ECDSAKey.supported_key_format_identifiers():
            key = paramiko.ECDSAKey.from_private_key_file(private_key_path)
        elif keytype == "ssh-ed25519":
            key = paramiko.Ed25519Key.from_private_key_file(private_key_path)
        else:
            raise Exception("Unable to handle key of type {}".format(keytype))

        self._users[uid] = (private_key_path, key) 
Example #29
Source File: server.py    From mock-ssh-server with MIT License 5 votes vote down vote up
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 
Example #30
Source File: test_handler.py    From webssh with MIT License 5 votes vote down vote up
def test_get_pkey_obj_with_encrypted_new_rsa_key(self):
        fname = 'test_new_rsa_password.key'
        password = '123456'
        self._test_with_encrypted_key(fname, password, paramiko.RSAKey)