Python paramiko 模块,WarningPolicy() 实例源码

我们从Python开源项目中,提取了以下22个代码示例,用于说明如何使用paramiko.WarningPolicy()

项目:trex-http-proxy    作者:alwye    | 项目源码 | 文件源码
def _try_passwordless_paramiko(server, keyfile):
    """Try passwordless login with paramiko."""
    if paramiko is None:
        msg = "Paramiko unavaliable, "
        if sys.platform == 'win32':
            msg += "Paramiko is required for ssh tunneled connections on Windows."
        else:
            msg += "use OpenSSH."
        raise ImportError(msg)
    username, server, port = _split_server(server)
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.WarningPolicy())
    try:
        client.connect(server, port, username=username, key_filename=keyfile,
               look_for_keys=True)
    except paramiko.AuthenticationException:
        return False
    else:
        client.close()
        return True
项目:starwatts-boto    作者:defab-sw    | 项目源码 | 文件源码
def paramiko_connect(host):
    client = paramiko.SSHClient()
    client._policy = paramiko.WarningPolicy()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    ssh_config = paramiko.SSHConfig()
    user_config_file = os.path.expanduser("~/.ssh/config")
    try:
        with open(user_config_file) as f:
            ssh_config.parse(f)
    except FileNotFoundError:
        print("{} file could not be found. Aborting.".format(user_config_file))
        sys.exit(1)
    cfg = {'hostname': options['hostname'], 'username': options["username"]}

    user_config = ssh_config.lookup(cfg['hostname'])
    for k in ('hostname', 'username', 'port'):
        if k in user_config:
            cfg[k] = user_config[k]

    if 'proxycommand' in user_config:
        cfg['sock'] = paramiko.ProxyCommand(user_config['proxycommand'])

    return client.connect(**cfg)
项目:pydsef    作者:DSEF    | 项目源码 | 文件源码
def exec_command(self, cmd, block = True):
        """Executes a command on the master node. If block is True, wait until command finishes and return stdout,
        otherwise exit immediately and return (stdin, stdout, stderr)"""
        if self.client == None:
            self.client = ssh.SSHClient()
            self.client.load_system_host_keys()
            self.client.set_missing_host_key_policy(ssh.WarningPolicy)
            self.client.connect(self.hostname, username = self.username)

            self.exec_command('mkdir -p dsef')

        (stdin, stdout, stderr) = self.client.exec_command("cd ~/{} && {}".format(self.dist_sys, cmd), get_pty = True)
        if block:
            return str(stdout.read(), 'ascii')
        else:
            return (stdin, stdout, stderr)
项目:os-xenapi    作者:openstack    | 项目源码 | 文件源码
def __init__(self, ip, username, password=None, pkey=None,
                 key_filename=None, log=None, look_for_keys=False,
                 allow_agent=False):
        self.client = paramiko.SSHClient()
        self.client.set_missing_host_key_policy(paramiko.WarningPolicy())
        self.client.connect(ip, username=username, password=password,
                            pkey=pkey, key_filename=key_filename,
                            look_for_keys=look_for_keys,
                            allow_agent=allow_agent)
        self.ip = ip
        self.log = log
项目:zanph    作者:zanph    | 项目源码 | 文件源码
def _try_passwordless_paramiko(server, keyfile):
    """Try passwordless login with paramiko."""
    if paramiko is None:
        msg = "Paramiko unavaliable, "
        if sys.platform == 'win32':
            msg += "Paramiko is required for ssh tunneled connections on Windows."
        else:
            msg += "use OpenSSH."
        raise ImportError(msg)
    username, server, port = _split_server(server)
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.WarningPolicy())
    try:
        client.connect(server, port, username=username, key_filename=keyfile,
               look_for_keys=True)
    except paramiko.AuthenticationException:
        return False
    else:
        client.close()
        return True
项目:Daytse.bundle    作者:shvets    | 项目源码 | 文件源码
def __init__(self, host, port, username, password, key=None, passphrase=None):
        self.username = username
        self.password = password

        self.ssh = paramiko.SSHClient()
        # ssh.load_system_host_keys()
        self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        # ssh.set_missing_host_key_policy(paramiko.WarningPolicy())

        if key is not None:
            key = paramiko.RSAKey.from_private_key(StringIO(key), password=passphrase)
        self.ssh.connect(host, port, username=username, password=password, pkey=key, timeout=self.TIMEOUT)
项目:trex-http-proxy    作者:alwye    | 项目源码 | 文件源码
def _try_passwordless_paramiko(server, keyfile):
    """Try passwordless login with paramiko."""
    if paramiko is None:
        msg = "Paramiko unavaliable, "
        if sys.platform == 'win32':
            msg += "Paramiko is required for ssh tunneled connections on Windows."
        else:
            msg += "use OpenSSH."
        raise ImportError(msg)
    username, server, port = _split_server(server)
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.WarningPolicy())
    try:
        client.connect(server, port, username=username, key_filename=keyfile,
               look_for_keys=True)
    except paramiko.AuthenticationException:
        return False
    else:
        client.close()
        return True
项目:trex-http-proxy    作者:alwye    | 项目源码 | 文件源码
def _try_passwordless_paramiko(server, keyfile):
    """Try passwordless login with paramiko."""
    if paramiko is None:
        msg = "Paramiko unavaliable, "
        if sys.platform == 'win32':
            msg += "Paramiko is required for ssh tunneled connections on Windows."
        else:
            msg += "use OpenSSH."
        raise ImportError(msg)
    username, server, port = _split_server(server)
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.WarningPolicy())
    try:
        client.connect(server, port, username=username, key_filename=keyfile,
               look_for_keys=True)
    except paramiko.AuthenticationException:
        return False
    else:
        client.close()
        return True
项目:trex-http-proxy    作者:alwye    | 项目源码 | 文件源码
def _try_passwordless_paramiko(server, keyfile):
    """Try passwordless login with paramiko."""
    if paramiko is None:
        msg = "Paramiko unavaliable, "
        if sys.platform == 'win32':
            msg += "Paramiko is required for ssh tunneled connections on Windows."
        else:
            msg += "use OpenSSH."
        raise ImportError(msg)
    username, server, port = _split_server(server)
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.WarningPolicy())
    try:
        client.connect(server, port, username=username, key_filename=keyfile,
               look_for_keys=True)
    except paramiko.AuthenticationException:
        return False
    else:
        client.close()
        return True
项目:trex-http-proxy    作者:alwye    | 项目源码 | 文件源码
def _try_passwordless_paramiko(server, keyfile):
    """Try passwordless login with paramiko."""
    if paramiko is None:
        msg = "Paramiko unavaliable, "
        if sys.platform == 'win32':
            msg += "Paramiko is required for ssh tunneled connections on Windows."
        else:
            msg += "use OpenSSH."
        raise ImportError(msg)
    username, server, port = _split_server(server)
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.WarningPolicy())
    try:
        client.connect(server, port, username=username, key_filename=keyfile,
               look_for_keys=True)
    except paramiko.AuthenticationException:
        return False
    else:
        client.close()
        return True
项目:trex-http-proxy    作者:alwye    | 项目源码 | 文件源码
def _try_passwordless_paramiko(server, keyfile):
    """Try passwordless login with paramiko."""
    if paramiko is None:
        msg = "Paramiko unavaliable, "
        if sys.platform == 'win32':
            msg += "Paramiko is required for ssh tunneled connections on Windows."
        else:
            msg += "use OpenSSH."
        raise ImportError(msg)
    username, server, port = _split_server(server)
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.WarningPolicy())
    try:
        client.connect(server, port, username=username, key_filename=keyfile,
               look_for_keys=True)
    except paramiko.AuthenticationException:
        return False
    else:
        client.close()
        return True
项目:vanilla-nodebb-importer    作者:Linux-statt-Windows    | 项目源码 | 文件源码
def __makeConnection(self, host, user, pw):
        """
        Private Method to create a SSH connection.

        @param      host <string>
                    The server host name or IP-Address.

        @param      user <string>
                    The user name for the SSH connection.

        @param      pw <string>
                    The password for the SSH connection.

        @return     sshClient <SSH Connection>
                    A SSH connection instance.
        """

        sshClient = paramiko.SSHClient()
        sshClient.load_system_host_keys()
        sshClient.set_missing_host_key_policy(paramiko.WarningPolicy())

        try:
            sshClient.connect(host, username=user, password=pw)
        except paramiko.SSHException:
            print("\033[31mConnection Error !!!")
            print("Something is going wrong during the SSH connection.\033[0m\n")
            sys.exit(1)

        return sshClient
项目:obsoleted-vpduserv    作者:InfraSIM    | 项目源码 | 文件源码
def main():
    options, server, remote = parse_options()

    password = None
    if options.readpass:
        password = getpass.getpass('Enter SSH password: ')

    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.WarningPolicy())

    verbose('Connecting to ssh host %s:%d ...' % (server[0], server[1]))
    try:
        client.connect(server[0], server[1], username=options.user, key_filename=options.keyfile,
                       look_for_keys=options.look_for_keys, password=password)
    except Exception as e:
        print('*** Failed to connect to %s:%d: %r' % (server[0], server[1], e))
        sys.exit(1)

    verbose('Now forwarding remote port %d to %s:%d ...' % (options.port, remote[0], remote[1]))

    try:
        reverse_forward_tunnel(options.port, remote[0], remote[1], client.get_transport())
    except KeyboardInterrupt:
        print('C-c: Port forwarding stopped.')
        sys.exit(0)
项目:obsoleted-vpduserv    作者:InfraSIM    | 项目源码 | 文件源码
def main():
    options, server, remote = parse_options()

    password = None
    if options.readpass:
        password = getpass.getpass('Enter SSH password: ')

    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.WarningPolicy())

    verbose('Connecting to ssh host %s:%d ...' % (server[0], server[1]))
    try:
        client.connect(server[0], server[1], username=options.user, key_filename=options.keyfile,
                       look_for_keys=options.look_for_keys, password=password)
    except Exception as e:
        print('*** Failed to connect to %s:%d: %r' % (server[0], server[1], e))
        sys.exit(1)

    verbose('Now forwarding port %d to %s:%d ...' % (options.port, remote[0], remote[1]))

    try:
        forward_tunnel(options.port, remote[0], remote[1], client.get_transport())
    except KeyboardInterrupt:
        print('C-c: Port forwarding stopped.')
        sys.exit(0)
项目:JumpServer    作者:youkelike    | 项目源码 | 文件源码
def ssh_login(user_obj,bind_host_obj,mysql_engine,log_recording):
    try:
        client = paramiko.SSHClient()
        client.load_system_host_keys()
        client.set_missing_host_key_policy(paramiko.WarningPolicy())
        print('**** Connecting... ****')
        client.connect(bind_host_obj.host.ip_addr,
                       bind_host_obj.host.port,
                       bind_host_obj.remote_user.username,
                       bind_host_obj.remote_user.password,
                       timeout=30)
        cmd_caches = []

        chan = client.invoke_shell()
        print(repr(client.get_transport()))
        print('**** Here we go ****')

        #????????
        cmd_caches.append(models.AuditLog(user_id=user_obj.id,
                                          bind_host_id=bind_host_obj.id,
                                          action_type='login',
                                          date=datetime.datetime.now()
                                          ))
        log_recording(cmd_caches)

        #??paramiko??????shell
        interactive.interactive_shell(chan,user_obj,bind_host_obj,cmd_caches,log_recording)

        chan.close()
        client.close()
    except Exception as ex:
        print('**** Caught Exception: %s: %s ****' % (ex.__class___,ex))
        traceback.print_exec()
        try:
            client.close()
        except:
            pass
        sys.exit(1)
项目:deb-python-hplefthandclient    作者:openstack    | 项目源码 | 文件源码
def _create_ssh(self, **kwargs):
        try:
            ssh = paramiko.SSHClient()

            known_hosts_file = kwargs.get('known_hosts_file', None)
            if known_hosts_file is None:
                ssh.load_system_host_keys()
            else:
                # Make sure we can open the file for appending first.
                # This is needed to create the file when we run CI tests with
                # no existing key file.
                open(known_hosts_file, 'a').close()
                ssh.load_host_keys(known_hosts_file)

            missing_key_policy = kwargs.get('missing_key_policy', None)
            if missing_key_policy is None:
                missing_key_policy = paramiko.AutoAddPolicy()
            elif isinstance(missing_key_policy, basestring):
                # To make it configurable, allow string to be mapped to object.
                if missing_key_policy == paramiko.AutoAddPolicy().__class__.\
                        __name__:
                    missing_key_policy = paramiko.AutoAddPolicy()
                elif missing_key_policy == paramiko.RejectPolicy().__class__.\
                        __name__:
                    missing_key_policy = paramiko.RejectPolicy()
                elif missing_key_policy == paramiko.WarningPolicy().__class__.\
                        __name__:
                    missing_key_policy = paramiko.WarningPolicy()
                else:
                    raise exceptions.SSHException(
                        "Invalid missing_key_policy: %s" % missing_key_policy
                    )

            ssh.set_missing_host_key_policy(missing_key_policy)

            self.ssh = ssh
        except Exception as e:
            msg = "Error connecting via ssh: %s" % e
            self._logger.error(msg)
            raise paramiko.SSHException(msg)
项目:xf    作者:red-green    | 项目源码 | 文件源码
def sshconnect():
    host = raw_input('host to connect to (no port)> ')
    port = input('port> ')
    user = raw_input('username> ')
    pwd = getpass.getpass('password> ')
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.WarningPolicy())
    client.connect(host, port, user, pwd)
    chan = client.invoke_shell()
    interactive.interactive_shell(chan)
    chan.close()
    client.close()
项目:starwatts-boto    作者:defab-sw    | 项目源码 | 文件源码
def __init__(self, connection, application, version, environment, project, instance_type='m1.xlarge', user='root',
                 instance=None, ami=None, debug=False):
        if debug:
            logging.basicConfig(level=logging.DEBUG)

        # API attributes
        self.connection = connection

        # AMI and VM attributes
        self.application = application
        self.version = version
        self.environment = environment
        self.project = project
        self.user = user
        self.instance_type = instance_type
        self.ami = ami
        if instance is not None:
            self.instance_name = instance.tags.get('name')
        else:
            self.instance_name = "node_{}_{}".format(self.application, self.project)
        self.instance = instance

        # SSH connection and command attributes
        self.connected = False
        self.errors = list()
        self.ssh_sock = None
        self.ssh_client = paramiko.SSHClient()
        self.ssh_client.load_system_host_keys()
        self.ssh_client._policy = paramiko.WarningPolicy()
        self.ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
项目:cfawsinit    作者:mandarjog    | 项目源码 | 文件源码
def sshclient(self):
        if self._sshclient is None:
            host = urlparse.urlparse(self.url).netloc
            clnt = paramiko.SSHClient()
            clnt.set_missing_host_key_policy(paramiko.WarningPolicy())
            clnt.connect(
                host, username="ubuntu",
                key_filename=self.opts['ssh_private_key_path'])
            self._sshclient = clnt

        return self._sshclient
项目:py3_training    作者:triaquae    | 项目源码 | 文件源码
def ssh_login(user_obj,bind_host_obj,mysql_engine,log_recording):
    # now, connect and use paramiko Client to negotiate SSH2 across the connection
    try:
        client = paramiko.SSHClient()
        client.load_system_host_keys()
        client.set_missing_host_key_policy(paramiko.WarningPolicy())
        print('*** Connecting...')
        #client.connect(hostname, port, username, password)
        client.connect(bind_host_obj.host.ip_addr,
                       bind_host_obj.host.port,
                       bind_host_obj.remoteuser.username,
                       bind_host_obj.remoteuser.password,
                       timeout=30)

        cmd_caches = []
        chan = client.invoke_shell()
        print(repr(client.get_transport()))
        print('*** Here we go!\n')
        cmd_caches.append(models.AuditLog(user_id=user_obj.id,
                                          bind_host_id=bind_host_obj.id,
                                          action_type='login',
                                          date=datetime.datetime.now()
                                          ))
        log_recording(user_obj,bind_host_obj,cmd_caches)
        interactive.interactive_shell(chan,user_obj,bind_host_obj,cmd_caches,log_recording)
        chan.close()
        client.close()

    except Exception as e:
        print('*** Caught exception: %s: %s' % (e.__class__, e))
        traceback.print_exc()
        try:
            client.close()
        except:
            pass
        sys.exit(1)
项目:trojan    作者:Hackerl    | 项目源码 | 文件源码
def main():
    options, server, remote = parse_options()

    password = None
    if options.readpass:
        password = getpass.getpass('Enter SSH password: ')

    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.WarningPolicy())

    verbose('Connecting to ssh host %s:%d ...' % (server[0], server[1]))
    try:
        client.connect(server[0], server[1], username=options.user, key_filename=options.keyfile,
                       look_for_keys=options.look_for_keys, password=password)
    except Exception as e:
        print('*** Failed to connect to %s:%d: %r' % (server[0], server[1], e))
        sys.exit(1)

    verbose('Now forwarding remote port %d to %s:%d ...' % (options.port, remote[0], remote[1]))

    try:
        reverse_forward_tunnel(options.port, remote[0], remote[1], client.get_transport())
    except KeyboardInterrupt:
        print('C-c: Port forwarding stopped.')
        sys.exit(0)
项目:brigade    作者:napalm-automation    | 项目源码 | 文件源码
def ssh_connection(self):
        """Reusable :obj:`paramiko.client.SSHClient`."""
        if hasattr(self, "_ssh_connection"):
            return self._ssh_connection

        # TODO configurable
        ssh_config_file = os.path.join(os.path.expanduser("~"), ".ssh", "config")

        client = paramiko.SSHClient()
        client._policy = paramiko.WarningPolicy()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        ssh_config = paramiko.SSHConfig()
        if os.path.exists(ssh_config_file):
            with open(ssh_config_file) as f:
                ssh_config.parse(f)

        parameters = {
            "hostname": self.host,
            "username": self.username,
            "password": self.password,
            "port": self.ssh_port,
        }

        user_config = ssh_config.lookup(self.host)
        for k in ('hostname', 'username', 'port'):
            if k in user_config:
                parameters[k] = user_config[k]

        if 'proxycommand' in user_config:
            parameters['sock'] = paramiko.ProxyCommand(user_config['proxycommand'])

        # TODO configurable
        #  if ssh_key_file:
        #      parameters['key_filename'] = ssh_key_file
        if 'identityfile' in user_config:
            parameters['key_filename'] = user_config['identityfile']

        client.connect(**parameters)
        self._ssh_connection = client
        return client