本文整理汇总了Python中paramiko.DSSKey方法的典型用法代码示例。如果您正苦于以下问题:Python paramiko.DSSKey方法的具体用法?Python paramiko.DSSKey怎么用?Python paramiko.DSSKey使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类paramiko
的用法示例。
在下文中一共展示了paramiko.DSSKey方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_authorized_keys
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import DSSKey [as 别名]
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
示例2: get_pkey_obj
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import DSSKey [as 别名]
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
示例3: ssh_key_gen
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import DSSKey [as 别名]
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.')
示例4: test_4_dict_set
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import DSSKey [as 别名]
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)
示例5: connect
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import DSSKey [as 别名]
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()
示例6: get_pkey
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import DSSKey [as 别名]
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
示例7: test_get_pkey_obj_with_plain_new_dsa_key
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import DSSKey [as 别名]
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)
示例8: load_keyfile
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import DSSKey [as 别名]
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
示例9: _get_pkey_object
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import DSSKey [as 别名]
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)
示例10: _is_key_file_needs_passphrase
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import DSSKey [as 别名]
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
示例11: get_host_key
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import DSSKey [as 别名]
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
示例12: ssh_key_string_to_obj
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import DSSKey [as 别名]
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
示例13: ssh_pubkey_gen
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import DSSKey [as 别名]
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
示例14: ssh_key_string_to_obj
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import DSSKey [as 别名]
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.')
示例15: __resolve_private_key
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import DSSKey [as 别名]
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]