def valid_ssh(hostname, port, username, password=None, pkey=None, with_expect=True): try: private_key = AppSetting.get('private_key') public_key = AppSetting.get('public_key') except KeyError: private_key, public_key = SSH.generate_key() AppSetting.set('private_key', private_key, 'ssh private key') AppSetting.set('public_key', public_key, 'ssh public key') if password: _cli = SSH(hostname, port, username, password=str(password)) _cli.add_public_key(public_key) if pkey: private_key = pkey try: cli = SSH(hostname, port, username, private_key) cli.ping() except BadAuthenticationType: if with_expect: raise TypeError('该主机不支持密钥认证,请参考官方文档,错误代码:E01') return False except AuthenticationException: if password and with_expect: raise ValueError('密钥认证失败,请参考官方文档,错误代码:E02') return False return True
def _get_ssh(kwargs, pkey=None, private_key=None, public_key=None, password=None): try: ssh = SSH(pkey=pkey or private_key, **kwargs) ssh.get_client() return ssh except AuthenticationException as e: if password: with SSH(password=str(password), **kwargs) as ssh: ssh.add_public_key(public_key) return _get_ssh(kwargs, private_key) raise e