Python paramiko.DSSKey() Examples
The following are 20
code examples of paramiko.DSSKey().
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: utils.py From diting with GNU General Public License v2.0 | 7 votes |
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 #2
Source File: handler.py From adminset with GNU General Public License v2.0 | 7 votes |
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 #3
Source File: test_hostkeys.py From python-hpedockerplugin with Apache License 2.0 | 6 votes |
def test_4_dict_set(self): hostdict = paramiko.HostKeys('hostfile.temp') key = paramiko.RSAKey(data=decodebytes(keyblob)) key_dss = paramiko.DSSKey(data=decodebytes(keyblob_dss)) hostdict['secure.example.com'] = { 'ssh-rsa': key, 'ssh-dss': key_dss } hostdict['fake.example.com'] = {} hostdict['fake.example.com']['ssh-rsa'] = key self.assertEqual(3, len(hostdict)) self.assertEqual(2, len(list(hostdict.values())[0])) self.assertEqual(1, len(list(hostdict.values())[1])) self.assertEqual(1, len(list(hostdict.values())[2])) fp = hexlify(hostdict['secure.example.com']['ssh-rsa'].get_fingerprint()).upper() self.assertEqual(b'7EC91BB336CB6D810B124B1353C32396', fp) fp = hexlify(hostdict['secure.example.com']['ssh-dss'].get_fingerprint()).upper() self.assertEqual(b'4478F0B9A23CC5182009FF755BC1D26C', fp)
Example #4
Source File: main.py From autoops with Apache License 2.0 | 6 votes |
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 #5
Source File: __init__.py From pyrexecd with MIT License | 6 votes |
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 #6
Source File: main.py From chain with Apache License 2.0 | 6 votes |
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 #7
Source File: patator.py From patator with GNU General Public License v2.0 | 5 votes |
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 #8
Source File: paramiko_ssh.py From st2 with Apache License 2.0 | 5 votes |
def _get_pkey_object(self, key_material, passphrase): """ Try to detect private key type and return paramiko.PKey object. """ for cls in [paramiko.RSAKey, paramiko.DSSKey, paramiko.ECDSAKey]: try: key = cls.from_private_key(StringIO(key_material), password=passphrase) except paramiko.ssh_exception.SSHException: # Invalid key, try other key type pass else: return key # If a user passes in something which looks like file path we throw a more friendly # exception letting the user know we expect the contents a not a path. # Note: We do it here and not up the stack to avoid false positives. contains_header = REMOTE_RUNNER_PRIVATE_KEY_HEADER in key_material.lower() if not contains_header and (key_material.count('/') >= 1 or key_material.count('\\') >= 1): msg = ('"private_key" parameter needs to contain private key data / content and not ' 'a path') elif passphrase: msg = 'Invalid passphrase or invalid/unsupported key type' else: msg = 'Invalid or unsupported key type' raise paramiko.ssh_exception.SSHException(msg)
Example #9
Source File: paramiko_ssh.py From st2 with Apache License 2.0 | 5 votes |
def _is_key_file_needs_passphrase(file): for cls in [paramiko.RSAKey, paramiko.DSSKey, paramiko.ECDSAKey]: try: cls.from_private_key_file(file, password=None) except paramiko.ssh_exception.PasswordRequiredException: return True except paramiko.ssh_exception.SSHException: continue return False
Example #10
Source File: __init__.py From pyrexecd with MIT License | 5 votes |
def get_host_key(path): if path.endswith('rsa_key'): f = paramiko.RSAKey elif path.endswith('dsa_key'): f = paramiko.DSSKey elif path.endswith('ecdsa_key'): f = paramiko.ECDSAKay else: raise ValueError(path) return f(filename=path) # get_authorized_keys
Example #11
Source File: test_handler.py From webssh with MIT License | 5 votes |
def test_get_pkey_obj_with_plain_new_dsa_key(self): pk = self.get_pk_obj('test_new_dsa.key') self.assertIsInstance(pk.get_pkey_obj(), paramiko.DSSKey)
Example #12
Source File: patator_ext.py From project-black with GNU General Public License v2.0 | 5 votes |
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 #13
Source File: utils.py From diting with GNU General Public License v2.0 | 5 votes |
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 #14
Source File: utils.py From diting with GNU General Public License v2.0 | 5 votes |
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 #15
Source File: ssh.py From django-webssh with Apache License 2.0 | 5 votes |
def connect(self, host, user, password=None, ssh_key=None, port=22, timeout=30, term='xterm', pty_width=80, pty_height=24): try: ssh_client = paramiko.SSHClient() ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) if ssh_key: key = get_key_obj(paramiko.RSAKey, pkey_obj=ssh_key, password=password) or \ get_key_obj(paramiko.DSSKey, pkey_obj=ssh_key, password=password) or \ get_key_obj(paramiko.ECDSAKey, pkey_obj=ssh_key, password=password) or \ get_key_obj(paramiko.Ed25519Key, pkey_obj=ssh_key, password=password) ssh_client.connect(username=user, hostname=host, port=port, pkey=key, timeout=timeout) else: ssh_client.connect(username=user, password=password, hostname=host, port=port, timeout=timeout) transport = ssh_client.get_transport() self.channel = transport.open_session() self.channel.get_pty(term=term, width=pty_width, height=pty_height) self.channel.invoke_shell() for i in range(2): recv = self.channel.recv(1024).decode('utf-8') self.message['status'] = 0 self.message['message'] = recv message = json.dumps(self.message) self.websocker.send(message) except socket.timeout: self.message['status'] = 1 self.message['message'] = 'ssh 连接超时' message = json.dumps(self.message) self.websocker.send(message) self.close() except: self.close()
Example #16
Source File: bot_net.py From violent-python3 with GNU General Public License v3.0 | 4 votes |
def load_keyfile(self, keyfile): # if keyfile isn't one of these 3 types it # will be treated as a plaintext password for cls in (paramiko.RSAKey, paramiko.DSSKey, paramiko.ECDSAKey): try: return cls.from_private_key_file(keyfile) except: pass else: return None
Example #17
Source File: ssh_forward.py From king-phisher with BSD 3-Clause "New" or "Revised" License | 4 votes |
def __resolve_private_key(self, private_key, agent_keys): private_key = private_key.strip() pkey_type = private_key.split(':', 1)[0].lower() if pkey_type in ('file', 'key'): if pkey_type == 'file': file_path = os.path.expandvars(private_key[5:]) if not os.access(file_path, os.R_OK): self.logger.warning("the user specified ssh key file '{0}' can not be opened".format(file_path)) raise KingPhisherSSHKeyError('The SSH key file can not be opened.') self.logger.debug('loading the user specified ssh key file: ' + file_path) file_h = open(file_path, 'r') first_line = file_h.readline() file_h.seek(0, os.SEEK_SET) else: self.logger.debug('loading the user specified ssh key string from memory') key_str = private_key[4:] file_h = io.StringIO(key_str) first_line = key_str.split('\n', 1)[0] if 'BEGIN DSA PRIVATE KEY' in first_line: KeyKlass = paramiko.DSSKey elif 'BEGIN RSA PRIVATE KEY' in first_line: KeyKlass = paramiko.RSAKey else: file_h.close() self.logger.warning('the user specified ssh key does not appear to be a valid dsa or rsa private key') raise KingPhisherSSHKeyError('The SSH key file is not a DSA or RSA private key.') try: private_key = KeyKlass.from_private_key(file_h) except paramiko.PasswordRequiredException: self.logger.warning('the user specified ssh key is encrypted and requires a password') raise finally: file_h.close() return private_key # if the key has whitespace, discard anything after the first occurrence private_key = private_key.split(' ', 1)[0] # if it's not one of the above, treat it like it's a fingerprint if pkey_type == 'sha256': # OpenSSH 6.8 started to use sha256 & base64 for keys algorithm = pkey_type private_key = private_key[7:] + '=' decode = binascii.a2b_base64 else: algorithm = 'md5' private_key = private_key.replace(':', '') decode = binascii.a2b_hex try: private_key = decode(private_key) except binascii.Error as error: self.logger.warning("the user specified ssh key could not be decoded (type: {0}, error: {1!r})".format(pkey_type, error)) raise KingPhisherSSHKeyError('The preferred SSH key could not be decoded.') private_key = tuple(key for key in agent_keys if hashlib.new(algorithm, key.blob).digest() == private_key) if not private_key: self.logger.warning('the user specified ssh key could not be loaded from the ssh agent') raise KingPhisherSSHKeyError('The preferred SSH key could not be loaded from the SSH agent.') return private_key[0]
Example #18
Source File: sshtunnel.py From sshtunnel with MIT License | 4 votes |
def get_keys(logger=None, host_pkey_directories=None, allow_agent=False): """ Load public keys from any available SSH agent or local .ssh directory. Arguments: logger (Optional[logging.Logger]) host_pkey_directories (Optional[list[str]]): List of local directories where host SSH pkeys in the format "id_*" are searched. For example, ['~/.ssh'] .. versionadded:: 0.1.0 allow_agent (Optional[boolean]): Whether or not load keys from agent Default: False Return: list """ keys = SSHTunnelForwarder.get_agent_keys(logger=logger) \ if allow_agent else [] if host_pkey_directories is not None: paramiko_key_types = {'rsa': paramiko.RSAKey, 'dsa': paramiko.DSSKey, 'ecdsa': paramiko.ECDSAKey, 'ed25519': paramiko.Ed25519Key} for directory in host_pkey_directories or [DEFAULT_SSH_DIRECTORY]: for keytype in paramiko_key_types.keys(): ssh_pkey_expanded = os.path.expanduser( os.path.join(directory, 'id_{}'.format(keytype)) ) if os.path.isfile(ssh_pkey_expanded): ssh_pkey = SSHTunnelForwarder.read_private_key_file( pkey_file=ssh_pkey_expanded, logger=logger, key_type=paramiko_key_types[keytype] ) if ssh_pkey: keys.append(ssh_pkey) if logger: logger.info('{0} keys loaded from host directory'.format( len(keys)) ) return keys
Example #19
Source File: sshtunnel.py From sshtunnel with MIT License | 4 votes |
def read_private_key_file(pkey_file, pkey_password=None, key_type=None, logger=None): """ Get SSH Public key from a private key file, given an optional password Arguments: pkey_file (str): File containing a private key (RSA, DSS or ECDSA) Keyword Arguments: pkey_password (Optional[str]): Password to decrypt the private key logger (Optional[logging.Logger]) Return: paramiko.Pkey """ ssh_pkey = None for pkey_class in (key_type,) if key_type else ( paramiko.RSAKey, paramiko.DSSKey, paramiko.ECDSAKey, paramiko.Ed25519Key ): try: ssh_pkey = pkey_class.from_private_key_file( pkey_file, password=pkey_password ) if logger: logger.debug('Private key file ({0}, {1}) successfully ' 'loaded'.format(pkey_file, pkey_class)) break except paramiko.PasswordRequiredException: if logger: logger.error('Password is required for key {0}' .format(pkey_file)) break except paramiko.SSHException: if logger: logger.debug('Private key file ({0}) could not be loaded ' 'as type {1} or bad password' .format(pkey_file, pkey_class)) return ssh_pkey
Example #20
Source File: utils.py From jumpserver-python-sdk with GNU General Public License v2.0 | 4 votes |
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 # def ssh_pubkey_gen(private_key=None, username='jumpserver', hostname='localhost'): # if isinstance(private_key, str): # private_key = ssh_key_string_to_obj(private_key) # # 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 # # # 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.')