本文整理汇总了Python中paramiko.PasswordRequiredException方法的典型用法代码示例。如果您正苦于以下问题:Python paramiko.PasswordRequiredException方法的具体用法?Python paramiko.PasswordRequiredException怎么用?Python paramiko.PasswordRequiredException使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类paramiko
的用法示例。
在下文中一共展示了paramiko.PasswordRequiredException方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_specific_pkey
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import PasswordRequiredException [as 别名]
def get_specific_pkey(self, name, offset, password):
self.iostr.seek(offset)
logging.debug('Reset offset to {}.'.format(offset))
logging.debug('Try parsing it as {} type key'.format(name))
pkeycls = getattr(paramiko, name+'Key')
pkey = None
try:
pkey = pkeycls.from_private_key(self.iostr, password=password)
except paramiko.PasswordRequiredException:
raise InvalidValueError('Need a passphrase to decrypt the key.')
except (paramiko.SSHException, ValueError) as exc:
self.last_exception = exc
logging.debug(str(exc))
return pkey
示例2: check_auth_password
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import PasswordRequiredException [as 别名]
def check_auth_password(self, username, password):
logger.info("-=-=- %s -=-=-\nUser: %s\nPassword: %s\n" % (self.client_address[0], username, password))
print " IP: %s\n User: %s\n Pass: %s\n" % (self.client_address[0], username, password)
if DENY_ALL == True:
return paramiko.AUTH_FAILED
f = open("blocked.dat","r")
data = str(f.readlines()).find(self.client_address[0])
if data > 1:
if ran:
new_key()
return paramiko.PasswordRequiredException
else:
f = open("blocked.dat","a")
deepscan(self.client_address[0],f)
paramiko.OPEN_FAILED_CONNECT_FAILED
if (username == "root") and (password in PASSWORDS):
return paramiko.AUTH_SUCCESSFUL
return paramiko.AUTH_FAILED
示例3: try_load_private_key_interactive
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import PasswordRequiredException [as 别名]
def try_load_private_key_interactive(filename, password=None,
error_context=None):
"""Wraps the try_load_private_key method such that it can request a password
from the user via stdin if necessary."""
try:
return try_load_private_key(
filename,
password=password,
error_context=error_context,
)
except paramiko.PasswordRequiredException:
print("The SSH key %s requires a password")
password = getpass.getpass("Please enter the password for this key:")
return try_load_private_key(
filename,
password=password,
error_context=error_context,
)
示例4: test_get_pkey_obj_with_encrypted_key
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import PasswordRequiredException [as 别名]
def test_get_pkey_obj_with_encrypted_key(self):
fname = 'test_ed25519_password.key'
password = 'abc123'
cls = paramiko.Ed25519Key
key = read_file(make_tests_data_path(fname))
pkey = IndexHandler.get_pkey_obj(key, password, fname)
self.assertIsInstance(pkey, cls)
with self.assertRaises(InvalidValueError) as ctx:
pkey = IndexHandler.get_pkey_obj(key, 'wrongpass', fname)
self.assertIn('Wrong password', str(ctx.exception))
with self.assertRaises(InvalidValueError) as ctx:
pkey = IndexHandler.get_pkey_obj('x'+key, '', fname)
self.assertIn('Invalid private key', str(ctx.exception))
with self.assertRaises(paramiko.PasswordRequiredException):
pkey = IndexHandler.get_pkey_obj(key, '', fname)
示例5: __try_connect
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import PasswordRequiredException [as 别名]
def __try_connect(self, *args, **kwargs):
raise_error = kwargs.pop('raise_error', False)
try:
self.client.connect(self.server[0], self.server[1], username=self.username, allow_agent=False, timeout=12.0, *args, **kwargs)
except paramiko.PasswordRequiredException:
raise
except paramiko.AuthenticationException as error:
if raise_error:
raise error
return False
self.__connected = True
return True
示例6: load_key
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import PasswordRequiredException [as 别名]
def load_key(self, key_path, password):
"""
Creates paramiko rsa key
:type key_path: str
:param key_path: path to rsa key
:type password: str
:param password: password to try if rsa key is encrypted
"""
try:
return paramiko.RSAKey.from_private_key_file(key_path)
except PasswordRequiredException as ex:
return paramiko.RSAKey.from_private_key_file(key_path,
password=password)
示例7: get_specific_pkey
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import PasswordRequiredException [as 别名]
def get_specific_pkey(self, pkeycls, privatekey, password):
logging.info('Trying {}'.format(pkeycls.__name__))
try:
pkey = pkeycls.from_private_key(io.StringIO(privatekey),
password=password)
except paramiko.PasswordRequiredException:
raise ValueError('Need password to decrypt the private key.')
except paramiko.SSHException:
pass
else:
return pkey
示例8: manual_auth
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import PasswordRequiredException [as 别名]
def manual_auth(username, hostname):
try:
default_path = os.path.join(os.environ['HOME'], '.ssh', 'id_rsa')
path = default_path
try:
key = paramiko.RSAKey.from_private_key_file(path)
except paramiko.PasswordRequiredException:
password = getpass.getpass('RSA key password: ')
key = paramiko.RSAKey.from_private_key_file(path, password)
t.auth_publickey(username, key)
except IOError:
default_path = os.path.join(os.environ['HOME'], '.ssh', 'id_dsa')
path = default_path
try:
key = paramiko.DSSKey.from_private_key_file(path)
except paramiko.PasswordRequiredException:
password = getpass.getpass('DSS key password: ')
key = paramiko.DSSKey.from_private_key_file(path, password)
t.auth_publickey(username, key)
#except paramiko.AuthenticationException as e:
except:
pw = getpass.getpass('Password for %s@%s: ' % (username, hostname))
try:
t.auth_password(username, pw)
except (paramiko.AuthenticationException, KeyboardInterrupt) as error:
print 'Permission denied, Authentication Error'
示例9: test_get_specific_pkey_with_encrypted_key
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import PasswordRequiredException [as 别名]
def test_get_specific_pkey_with_encrypted_key(self):
fname = 'test_rsa_password.key'
cls = paramiko.RSAKey
password = 'television'
key = read_file(make_tests_data_path(fname))
pkey = IndexHandler.get_specific_pkey(cls, key, password)
self.assertIsInstance(pkey, cls)
pkey = IndexHandler.get_specific_pkey(cls, 'x'+key, None)
self.assertIsNone(pkey)
with self.assertRaises(paramiko.PasswordRequiredException):
pkey = IndexHandler.get_specific_pkey(cls, key, None)
示例10: get_specific_pkey
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import PasswordRequiredException [as 别名]
def get_specific_pkey(cls, pkeycls, privatekey, password):
logging.info('Trying {}'.format(pkeycls.__name__))
try:
pkey = pkeycls.from_private_key(io.StringIO(privatekey),
password=password)
except paramiko.PasswordRequiredException:
raise
except paramiko.SSHException:
pass
else:
return pkey
示例11: manual_auth
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import PasswordRequiredException [as 别名]
def manual_auth(username, hostname):
default_auth = 'p'
auth = input('Auth by (p)assword, (r)sa key, or (d)ss key? [%s] ' % default_auth)
if len(auth) == 0:
auth = default_auth
if auth == 'r':
default_path = os.path.join(os.environ['HOME'], '.ssh', 'id_rsa')
path = input('RSA key [%s]: ' % default_path)
if len(path) == 0:
path = default_path
try:
key = paramiko.RSAKey.from_private_key_file(path)
except paramiko.PasswordRequiredException:
password = getpass.getpass('RSA key password: ')
key = paramiko.RSAKey.from_private_key_file(path, password)
t.auth_publickey(username, key)
elif auth == 'd':
default_path = os.path.join(os.environ['HOME'], '.ssh', 'id_dsa')
path = input('DSS key [%s]: ' % default_path)
if len(path) == 0:
path = default_path
try:
key = paramiko.DSSKey.from_private_key_file(path)
except paramiko.PasswordRequiredException:
password = getpass.getpass('DSS key password: ')
key = paramiko.DSSKey.from_private_key_file(path, password)
t.auth_publickey(username, key)
else:
pw = getpass.getpass('Password for %s@%s: ' % (username, hostname))
t.auth_password(username, pw)
# setup logging
示例12: init
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import PasswordRequiredException [as 别名]
def init(hostname, username, keyfile, passwd):
global sftp, tc
t = paramiko.Transport(hostname)
tc = t
try:
key = paramiko.RSAKey.from_private_key_file(keyfile, passwd)
except paramiko.PasswordRequiredException:
sys.stderr.write('\n\nparamiko.RSAKey.from_private_key_file REQUIRES PASSWORD.\n')
sys.stderr.write('You have two options:\n')
sys.stderr.write('* Use the "-K" option to point to a different (non-password-protected)\n')
sys.stderr.write(' private key file.\n')
sys.stderr.write('* Use the "-P" option to provide the password needed to unlock this private\n')
sys.stderr.write(' key.\n')
sys.stderr.write('\n')
sys.exit(1)
try:
t.connect(username=username, pkey=key)
except paramiko.SSHException:
t.close()
sys.stderr.write('\n\nparamiko.Transport.connect FAILED.\n')
sys.stderr.write('There are several possible reasons why it might fail so quickly:\n\n')
sys.stderr.write('* The host to connect to (%s) is not a valid SSH server.\n' % hostname)
sys.stderr.write(' (Use the "-H" option to change the host.)\n')
sys.stderr.write('* The username to auth as (%s) is invalid.\n' % username)
sys.stderr.write(' (Use the "-U" option to change the username.)\n')
sys.stderr.write('* The private key given (%s) is not accepted by the server.\n' % keyfile)
sys.stderr.write(' (Use the "-K" option to provide a different key file.)\n')
sys.stderr.write('\n')
sys.exit(1)
sftp = paramiko.SFTP.from_transport(t)
示例13: __resolve_private_key
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import PasswordRequiredException [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]
示例14: _create_ssh_forwarder
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import PasswordRequiredException [as 别名]
def _create_ssh_forwarder(self, server, username, password, window=None):
"""
Create and set the
:py:attr:`~.KingPhisherClientApplication._ssh_forwarder` attribute.
:param tuple server: The server information as a host and port tuple.
:param str username: The username to authenticate to the SSH server with.
:param str password: The password to authenticate to the SSH server with.
:param window: The GTK window to use as the parent for error dialogs.
:type window: :py:class:`Gtk.Window`
:rtype: int
:return: The local port that is forwarded to the remote server or None if the connection failed.
"""
window = window or self.get_active_window()
title_ssh_error = 'Failed To Connect To The SSH Service'
server_remote_port = self.config['server_remote_port']
try:
self._ssh_forwarder = ssh_forward.SSHTCPForwarder(
server,
username,
password,
('127.0.0.1', server_remote_port),
private_key=self.config.get('ssh_preferred_key'),
missing_host_key_policy=ssh_host_key.MissingHostKeyPolicy(self)
)
self._ssh_forwarder.start()
except ssh_forward.KingPhisherSSHKeyError as error:
gui_utilities.show_dialog_error('SSH Key Configuration Error', window, error.message)
except errors.KingPhisherAbortError as error:
self.logger.info("ssh connection aborted ({0})".format(error.message))
except paramiko.PasswordRequiredException:
gui_utilities.show_dialog_error(title_ssh_error, window, 'The specified SSH key requires a password.')
except paramiko.AuthenticationException:
self.logger.warning('failed to authenticate to the remote ssh server')
gui_utilities.show_dialog_error(title_ssh_error, window, 'The server responded that the credentials are invalid.')
except paramiko.SSHException as error:
self.logger.warning("failed with ssh exception '{0}'".format(error.args[0]))
except socket.error as error:
gui_utilities.show_dialog_exc_socket_error(error, window, title=title_ssh_error)
except Exception as error:
self.logger.warning('failed to connect to the remote ssh server', exc_info=True)
gui_utilities.show_dialog_error(title_ssh_error, window, "An {0}.{1} error occurred.".format(error.__class__.__module__, error.__class__.__name__))
else:
return self._ssh_forwarder.local_server
self.emit('server-disconnected')
return
示例15: try_load_private_key
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import PasswordRequiredException [as 别名]
def try_load_private_key(filename, password=None, error_context=None):
"""Attempts to load a private key from the given file. Tries different types
of keys (RSA, DSS, ECDSA, Ed25519)."""
try:
logger.debug("Attempting to load private key file as RSA key")
return paramiko.rsakey.RSAKey.from_private_key_file(filename,
password=password)
except paramiko.PasswordRequiredException as e:
raise e
except Exception as e:
logger.debug("Cannot load as RSA key: %s" % e)
try:
logger.debug("Attempting to load private key file as DSS key")
return paramiko.dsskey.DSSKey.from_private_key_file(filename,
password=password)
except paramiko.PasswordRequiredException as e:
raise e
except Exception as e:
logger.debug("Cannot load as DSS key: %s" % e)
try:
logger.debug("Attempting to load private key file as ECDSA key")
return paramiko.ecdsakey.ECDSAKey.from_private_key_file(filename,
password=password)
except paramiko.PasswordRequiredException as e:
raise e
except Exception as e:
logger.debug("Cannot load as ECDSA key: %s" % e)
try:
logger.debug("Attempting to load private key file as Ed25519 key")
return paramiko.ed25519key.Ed25519Key.from_private_key_file(filename,
password=password)
except paramiko.PasswordRequiredException as e:
raise e
except Exception as e:
logger.debug("Cannot load as Ed25519 key: %s" % e)
raise ProjectConfigurationError(
message="Failed to load private key for SFTP deployment: %s" % filename,
context=error_context,
)