Python paramiko.WarningPolicy() Examples

The following are 30 code examples of paramiko.WarningPolicy(). 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: tunnel.py    From vnpy_crypto with MIT License 8 votes vote down vote up
def _try_passwordless_paramiko(server, keyfile):
    """Try passwordless login with paramiko."""
    if paramiko is None:
        msg = "Paramiko unavailable, "
        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 
Example #2
Source File: tunnel.py    From Computable with MIT License 8 votes vote down vote up
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 
Example #3
Source File: tunnel.py    From pySINDy with MIT License 6 votes vote down vote up
def _try_passwordless_paramiko(server, keyfile):
    """Try passwordless login with paramiko."""
    if paramiko is None:
        msg = "Paramiko unavailable, "
        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 
Example #4
Source File: tunnel.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _try_passwordless_paramiko(server, keyfile):
    """Try passwordless login with paramiko."""
    if paramiko is None:
        msg = "Paramiko unavailable, "
        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 
Example #5
Source File: tunnel.py    From rk with The Unlicense 6 votes vote down vote up
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())
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
        client.connect(server, port, username=username, key_filename=keyfile,
               look_for_keys=True)
    except paramiko.AuthenticationException:
        return False
    else:
        client.close()
        return True 
Example #6
Source File: ios_ssh.py    From decrypt-ios-apps-script with MIT License 6 votes vote down vote up
def ssh_into_device(lport, interactive, decryption_type, full_reversing):
	print "[+] SSH'ing into device"
	try:
		ssh_client.load_system_host_keys()
		ssh_client.set_missing_host_key_policy(paramiko.WarningPolicy)
		ssh_client.connect('localhost', port=lport, username='root', password=root_password)
		if interactive:
			interactive_shell()
		else:
			decrypt_application(decryption_type, lport, full_reversing)
			
	except Exception as e:
		print "[-] SSH error: ", e
		cleanup()
		sys.exit()
	finally:
		cleanup() 
Example #7
Source File: forward.py    From python-hpedockerplugin with Apache License 2.0 5 votes vote down vote up
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) 
Example #8
Source File: test_client.py    From python-hpedockerplugin with Apache License 2.0 5 votes vote down vote up
def _client_host_key_bad(self, host_key):
        threading.Thread(target=self._run).start()
        hostname = '[%s]:%d' % (self.addr, self.port)

        self.tc = paramiko.SSHClient()
        self.tc.set_missing_host_key_policy(paramiko.WarningPolicy())
        known_hosts = self.tc.get_host_keys()
        known_hosts.add(hostname, host_key.get_name(), host_key)

        self.assertRaises(
            paramiko.BadHostKeyException,
            self.tc.connect,
            password='pygmalion',
            **self.connect_kwargs
        ) 
Example #9
Source File: ssh_bruteforce.py    From mec with GNU General Public License v3.0 5 votes vote down vote up
def run():
    '''
    main
    '''
    passwords = []

    for password in open(PASSWORD).read().split('\n'):
        passwords.append(password)

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

    for pwd in passwords:
        try:
            client.connect(TARGET, port=22,
                           username="root",
                           password=pwd,
                           look_for_keys=False,
                           timeout=10)

            _, stdout, stderr = client.exec_command(COMMAND)
            print("exec {}:".format(COMMAND))
            print(TARGET, stdout, stderr)
        except (paramiko.SSHException, paramiko.ssh_exception.NoValidConnectionsError):
            continue
    client.close() 
Example #10
Source File: RemoteJob.py    From dpgen with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _setup_ssh(self,
                   hostname,
                   port, 
                   username = None,
                   password = None):
        ssh_client = paramiko.SSHClient()        
        ssh_client.load_system_host_keys()
        ssh_client.set_missing_host_key_policy(paramiko.WarningPolicy)
        ssh_client.connect(hostname, port=port, username=username, password=password)
        assert(ssh_client.get_transport().is_active())
        return ssh_client 
Example #11
Source File: RemoteJob.py    From dpgen with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _setup_ssh(self,
                   hostname,
                   port, 
                   username = None,
                   password = None):
        ssh_client = paramiko.SSHClient()        
        ssh_client.load_system_host_keys()
        ssh_client.set_missing_host_key_policy(paramiko.WarningPolicy)
        ssh_client.connect(hostname, port=port, username=username, password=password)
        assert(ssh_client.get_transport().is_active())
        return ssh_client 
Example #12
Source File: SSHContext.py    From dpgen with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _setup_ssh(self,
                   hostname,
                   port, 
                   username = None,
                   password = None):
        self.ssh = paramiko.SSHClient()        
        # ssh_client.load_system_host_keys()        
        self.ssh.set_missing_host_key_policy(paramiko.WarningPolicy)
        self.ssh.connect(hostname, port=port, username=username, password=password)
        assert(self.ssh.get_transport().is_active())
        transport = self.ssh.get_transport()
        transport.set_keepalive(60) 
Example #13
Source File: scp_upload.py    From panotti with MIT License 5 votes vote down vote up
def scp_upload(src_blob='Preproc.tar.gz', dst_blob="~", options={'hostname': 'lecun', 'username': 'shawley'}, progress=simple_callback):
    # from https://gist.github.com/acdha/6064215

    #--- Make the Paramiko SSH thing use my .ssh/config file (b/c I like ProxyCommand!)
    client = SSHClient()
    client.load_system_host_keys()
    client._policy = WarningPolicy()
    client.set_missing_host_key_policy(WarningPolicy())  # hmm. WarningPolicy? Most people use AutoAddPolicy. 

    ssh_config = SSHConfig()
    user_config_file = os.path.expanduser("~/.ssh/config")
    if os.path.exists(user_config_file):
        with open(user_config_file) as f:
            ssh_config.parse(f)

    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'] = ProxyCommand(user_config['proxycommand'])

    client.connect(**cfg)

    socket_timeout = None # number of seconds for timeout. None = never timeout. TODO: None means program may hang. But timeouts are annoying!

    # SCPCLient takes a paramiko transport and progress callback as its arguments.
    scp = SCPClient(client.get_transport(), progress=progress, socket_timeout=socket_timeout)

    # NOW we can finally upload! (in a separate process)
    #scp.put(src_blob, dst_blob)   # now in scp_thread

    # we want this to be non-blocking so we stick it in a thread
    thread = threading.Thread(target=scp_thread, args=(scp,src_blob, dst_blob) )
    thread.start()

    #scp.close()  # now in scp_thread 
Example #14
Source File: tunnel.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _paramiko_tunnel(lport, rport, server, remoteip, keyfile=None, password=None):
    """Function for actually starting a paramiko tunnel, to be passed
    to multiprocessing.Process(target=this), and not called directly.
    """
    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, password=password)
#    except paramiko.AuthenticationException:
#        if password is None:
#            password = getpass("%s@%s's password: "%(username, server))
#            client.connect(server, port, username=username, password=password)
#        else:
#            raise
    except Exception as e:
        print('*** Failed to connect to %s:%d: %r' % (server, port, e))
        sys.exit(1)

    # Don't let SIGINT kill the tunnel subprocess
    signal.signal(signal.SIGINT, signal.SIG_IGN)

    try:
        forward_tunnel(lport, remoteip, rport, client.get_transport())
    except KeyboardInterrupt:
        print('SIGINT: Port forwarding stopped cleanly')
        sys.exit(0)
    except Exception as e:
        print("Port forwarding stopped uncleanly: %s"%e)
        sys.exit(255) 
Example #15
Source File: cmd_executer.py    From tacker with Apache License 2.0 5 votes vote down vote up
def __connect(self):
        try:
            self.__ssh = paramiko.SSHClient()
            self.__ssh.set_missing_host_key_policy(paramiko.WarningPolicy())
            self.__ssh.connect(self.__host, username=self.__user,
                password=self.__password, timeout=self.__timeout)
            LOG.info("Connected to %s", self.__host)
        except paramiko.AuthenticationException:
            LOG.error("Authentication failed when connecting to %s",
                      self.__host)
            raise exceptions.NotAuthorized
        except paramiko.SSHException:
            LOG.error("Could not connect to %s. Giving up", self.__host)
            raise 
Example #16
Source File: rforward.py    From python-hpedockerplugin with Apache License 2.0 5 votes vote down vote up
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) 
Example #17
Source File: tunnel.py    From Computable with MIT License 5 votes vote down vote up
def _paramiko_tunnel(lport, rport, server, remoteip, keyfile=None, password=None):
    """Function for actually starting a paramiko tunnel, to be passed
    to multiprocessing.Process(target=this), and not called directly.
    """
    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, password=password)
#    except paramiko.AuthenticationException:
#        if password is None:
#            password = getpass("%s@%s's password: "%(username, server))
#            client.connect(server, port, username=username, password=password)
#        else:
#            raise
    except Exception as e:
        print('*** Failed to connect to %s:%d: %r' % (server, port, e))
        sys.exit(1)

    # print('Now forwarding port %d to %s:%d ...' % (lport, server, rport))

    try:
        forward_tunnel(lport, remoteip, rport, client.get_transport())
    except KeyboardInterrupt:
        print('SIGINT: Port forwarding stopped cleanly')
        sys.exit(0)
    except Exception as e:
        print("Port forwarding stopped uncleanly: %s"%e)
        sys.exit(255) 
Example #18
Source File: test_ssh_gss.py    From python-hpedockerplugin with Apache License 2.0 5 votes vote down vote up
def _test_connection(self, **kwargs):
        """
        (Most) kwargs get passed directly into SSHClient.connect().

        The exception is ... no exception yet
        """
        host_key = paramiko.RSAKey.from_private_key_file('tests/test_rsa.key')
        public_host_key = paramiko.RSAKey(data=host_key.asbytes())

        self.tc = paramiko.SSHClient()
        self.tc.set_missing_host_key_policy(paramiko.WarningPolicy())
        self.tc.get_host_keys().add('[%s]:%d' % (self.addr, self.port),
                                    'ssh-rsa', public_host_key)
        self.tc.connect(hostname=self.addr, port=self.port, username=self.username, gss_host=self.hostname,
                        gss_auth=True, **kwargs)

        self.event.wait(1.0)
        self.assert_(self.event.is_set())
        self.assert_(self.ts.is_active())
        self.assertEquals(self.username, self.ts.get_username())
        self.assertEquals(True, self.ts.is_authenticated())

        stdin, stdout, stderr = self.tc.exec_command('yes')
        schan = self.ts.accept(1.0)

        schan.send('Hello there.\n')
        schan.send_stderr('This is on stderr.\n')
        schan.close()

        self.assertEquals('Hello there.\n', stdout.readline())
        self.assertEquals('', stdout.readline())
        self.assertEquals('This is on stderr.\n', stderr.readline())
        self.assertEquals('', stderr.readline())

        stdin.close()
        stdout.close()
        stderr.close() 
Example #19
Source File: tunnel.py    From pySINDy with MIT License 5 votes vote down vote up
def _paramiko_tunnel(lport, rport, server, remoteip, keyfile=None, password=None):
    """Function for actually starting a paramiko tunnel, to be passed
    to multiprocessing.Process(target=this), and not called directly.
    """
    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, password=password)
#    except paramiko.AuthenticationException:
#        if password is None:
#            password = getpass("%s@%s's password: "%(username, server))
#            client.connect(server, port, username=username, password=password)
#        else:
#            raise
    except Exception as e:
        print('*** Failed to connect to %s:%d: %r' % (server, port, e))
        sys.exit(1)

    # Don't let SIGINT kill the tunnel subprocess
    signal.signal(signal.SIGINT, signal.SIG_IGN)

    try:
        forward_tunnel(lport, remoteip, rport, client.get_transport())
    except KeyboardInterrupt:
        print('SIGINT: Port forwarding stopped cleanly')
        sys.exit(0)
    except Exception as e:
        print("Port forwarding stopped uncleanly: %s"%e)
        sys.exit(255) 
Example #20
Source File: tunnel.py    From rk with The Unlicense 5 votes vote down vote up
def _paramiko_tunnel(lport, rport, server, remoteip, keyfile=None, password=None):
    """Function for actually starting a paramiko tunnel, to be passed
    to multiprocessing.Process(target=this), and not called directly.
    """
    username, server, port = _split_server(server)
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    #client.set_missing_host_key_policy(paramiko.WarningPolicy())
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    try:
        client.connect(server, port, username=username, key_filename=keyfile,
                       look_for_keys=True, password=password)
#    except paramiko.AuthenticationException:
#        if password is None:
#            password = getpass("%s@%s's password: "%(username, server))
#            client.connect(server, port, username=username, password=password)
#        else:
#            raise
    except Exception as e:
        print('*** Failed to connect to %s:%d: %r' % (server, port, e))
        sys.exit(1)

    # Don't let SIGINT kill the tunnel subprocess
    signal.signal(signal.SIGINT, signal.SIG_IGN)

    try:
        forward_tunnel(lport, remoteip, rport, client.get_transport())
    except KeyboardInterrupt:
        print('SIGINT: Port forwarding stopped cleanly')
        sys.exit(0)
    except Exception as e:
        print("Port forwarding stopped uncleanly: %s"%e)
        sys.exit(255) 
Example #21
Source File: tunnel.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def _paramiko_tunnel(lport, rport, server, remoteip, keyfile=None, password=None):
    """Function for actually starting a paramiko tunnel, to be passed
    to multiprocessing.Process(target=this), and not called directly.
    """
    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, password=password)
#    except paramiko.AuthenticationException:
#        if password is None:
#            password = getpass("%s@%s's password: "%(username, server))
#            client.connect(server, port, username=username, password=password)
#        else:
#            raise
    except Exception as e:
        print('*** Failed to connect to %s:%d: %r' % (server, port, e))
        sys.exit(1)

    # Don't let SIGINT kill the tunnel subprocess
    signal.signal(signal.SIGINT, signal.SIG_IGN)

    try:
        forward_tunnel(lport, remoteip, rport, client.get_transport())
    except KeyboardInterrupt:
        print('SIGINT: Port forwarding stopped cleanly')
        sys.exit(0)
    except Exception as e:
        print("Port forwarding stopped uncleanly: %s"%e)
        sys.exit(255) 
Example #22
Source File: tunnel.py    From Computable with MIT License 5 votes vote down vote up
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 
Example #23
Source File: paramiko.py    From testinfra with Apache License 2.0 5 votes vote down vote up
def client(self):
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.WarningPolicy())
        cfg = {
            "hostname": self.host.name,
            "port": int(self.host.port) if self.host.port else 22,
            "username": self.host.user,
            "timeout": self.timeout,
        }
        if self.ssh_config:
            with open(self.ssh_config) as f:
                ssh_config = paramiko.SSHConfig()
                ssh_config.parse(f)
                self._load_ssh_config(client, cfg, ssh_config)
        else:
            # fallback reading ~/.ssh/config
            default_ssh_config = os.path.join(
                os.path.expanduser('~'), '.ssh', 'config')
            try:
                with open(default_ssh_config) as f:
                    ssh_config = paramiko.SSHConfig()
                    ssh_config.parse(f)
            except IOError:
                pass
            else:
                self._load_ssh_config(client, cfg, ssh_config)

        if self.ssh_identity_file:
            cfg["key_filename"] = self.ssh_identity_file
        client.connect(**cfg)
        return client 
Example #24
Source File: tunnel.py    From Computable with MIT License 5 votes vote down vote up
def _paramiko_tunnel(lport, rport, server, remoteip, keyfile=None, password=None):
    """Function for actually starting a paramiko tunnel, to be passed
    to multiprocessing.Process(target=this), and not called directly.
    """
    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, password=password)
#    except paramiko.AuthenticationException:
#        if password is None:
#            password = getpass("%s@%s's password: "%(username, server))
#            client.connect(server, port, username=username, password=password)
#        else:
#            raise
    except Exception as e:
        print ('*** Failed to connect to %s:%d: %r' % (server, port, e))
        sys.exit(1)
    
    # Don't let SIGINT kill the tunnel subprocess
    signal.signal(signal.SIGINT, signal.SIG_IGN)
    
    try:
        forward_tunnel(lport, remoteip, rport, client.get_transport())
    except KeyboardInterrupt:
        print ('SIGINT: Port forwarding stopped cleanly')
        sys.exit(0)
    except Exception as e:
        print ("Port forwarding stopped uncleanly: %s"%e)
        sys.exit(255) 
Example #25
Source File: __init__.py    From platypush with MIT License 4 votes vote down vote up
def _connect(self,
                 host: str,
                 port: int = 22,
                 user: Optional[str] = None,
                 password: Optional[str] = None,
                 key_file: Optional[str] = None,
                 passphrase: Optional[str] = None,
                 compress: bool = False,
                 timeout: Optional[int] = None,
                 auth_timeout: Optional[int] = None) -> SSHClient:
        try:
            host, port, user = self._get_host_port_user(host, port, user)
            key = (host, port, user)
            if key in self._sessions:
                self.logger.info('[Connect] The SSH session is already active: {user}@{host}:{port}'.format(
                    user=user, host=host, port=port))
                return self._sessions[key]

            key_file, passphrase = self._get_key(key_file, passphrase)
            client = SSHClient()
            client.set_missing_host_key_policy(WarningPolicy())

            args = {
                'hostname': host,
                'port': port,
                'username': user,
                'compress': compress,
                'timeout': timeout,
                'auth_timeout': auth_timeout,
            }

            if password:
                args['password'] = password
            elif key_file:
                args['key_filename'] = key_file
                args['passphrase'] = passphrase
                args['gss_auth'] = GSS_AUTH_AVAILABLE
                args['gss_kex'] = GSS_AUTH_AVAILABLE
            else:
                client.load_system_host_keys()

            client.connect(**args)
            self._sessions[key] = client
            return client
        except Exception as e:
            self.logger.exception(e)
            raise AssertionError('Connection to {} failed: {}'.format(host, str(e))) 
Example #26
Source File: ssh_wrapper_plumbum.py    From sshkernel with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def load_ssh_config_for_plumbum(filename, host):
    """Parse and postprocess ssh_config
    and rename some keys for plumbum.ParamikoMachine.__init__()
    """

    conf = paramiko.config.SSHConfig()
    expanded_path = os.path.expanduser(filename)

    if os.path.exists(expanded_path):
        with open(expanded_path) as ssh_config:
            conf.parse(ssh_config)

    lookup = conf.lookup(host)

    plumbum_kwargs = dict(
        user=None,
        port=None,
        keyfile=None,
        load_system_ssh_config=False,
        # TODO: Drop WarningPolicy
        # This is need in current plumbum and wrapper implementation
        # in case proxycommand is set.
        missing_host_policy=paramiko.WarningPolicy(),
    )

    plumbum_host = host
    if "hostname" in lookup:
        plumbum_host = lookup.get("hostname")

    if "port" in lookup:
        plumbum_kwargs["port"] = int(lookup["port"])

    plumbum_kwargs["user"] = lookup.get("user")
    plumbum_kwargs["keyfile"] = lookup.get("identityfile")

    if "proxycommand" in lookup:
        plumbum_kwargs["load_system_ssh_config"] = True
        # load_system_ssh_config: read system SSH config for ProxyCommand configuration.
        # https://plumbum.readthedocs.io/en/latest/_modules/plumbum/machines/paramiko_machine.html

        if lookup.get("hostname") != host:
            msg = (
                "can't handle both ProxyCommand and HostName at once, "
                "please drop either"
            )
            raise ValueError(msg)
        plumbum_host = host
        # When load_system_ssh_config is True, plumbum_host must be Host
        # instead of HostName.
        # Otherwise parsing SSH config will fail in Plumbum.

    # Plumbum doesn't support agent-forwarding
    forward_agent = lookup.get("forwardagent")

    return (plumbum_host, plumbum_kwargs, forward_agent) 
Example #27
Source File: test_utils.py    From pyznap with GNU General Public License v3.0 4 votes vote down vote up
def open_ssh(user, host, key=None, port=22):
    """Opens an ssh connection to host.

    Parameters:
    ----------
    user : {str}
        Username to use
    host : {str}
        Host to connect to
    key : {str}, optional
        Path to ssh keyfile (the default is None, meaning the standard location
        '~/.ssh/id_rsa' will be checked)
    port : {int}, optional
        Port number to connect to (the default is 22)

    Raises
    ------
    FileNotFoundError
        If keyfile does not exist
    SSHException
        General exception raised if anything goes wrong during ssh connection

    Returns
    -------
    paramiko.SSHClient
        Open ssh connection.
    """

    logger = logging.getLogger(__name__)

    if not key:
        key = os.path.expanduser('~/.ssh/id_rsa')
    if not os.path.isfile(key):
        logger.error('{} is not a valid ssh key file...'.format(key))
        raise FileNotFoundError(key)

    ssh = pm.SSHClient()
    # Append username & hostname attributes to ssh class
    ssh.user, ssh.host = user, host
    try:
        ssh.load_system_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
    except (IOError, FileNotFoundError):
        ssh.load_system_host_keys()
    ssh.set_missing_host_key_policy(pm.WarningPolicy())

    try:
        ssh.connect(hostname=host, port=port, username=user, key_filename=key, timeout=5,
                    look_for_keys=False)
        # Test connection
        ssh.exec_command('ls', timeout=5)
    except (AuthenticationException, BadAuthenticationType,
            BadHostKeyException, ChannelException, NoValidConnectionsError,
            PasswordRequiredException, SSHException, PartialAuthentication,
            ProxyCommandFailure, timeout, gaierror) as err:
        logger.error('Could not connect to host {:s}: {}...'.format(host, err))
        # Raise general exception to be catched outside
        raise SSHException(err)

    return ssh 
Example #28
Source File: tunneling.py    From gradio-UI with Apache License 2.0 4 votes vote down vote up
def create_tunnel(payload, local_server, local_server_port):
    client = paramiko.SSHClient()
    # client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.set_missing_host_key_policy(paramiko.WarningPolicy())

    verbose(
        "Connecting to ssh host {}:{} ...".format(payload["host"], int(payload[
                                                                     "port"]))
    )
    try:
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            client.connect(
                hostname=payload["host"],
                port=int(payload["port"]),
                username=payload["user"],
                pkey=paramiko.RSAKey.from_private_key(StringIO(payload["key"])),
            )
    except Exception as e:
        print(
            "*** Failed to connect to {}:{}: {}}".format(payload["host"],
                                                    int(payload["port"]), e)
        )
        sys.exit(1)

    verbose(
        "Now forwarding remote port {} to {}:{} ...".format(int(payload[
                                                              "remote_port"]),
                                                            local_server,
                                                            local_server_port)
    )

    thread = threading.Thread(
        target=reverse_forward_tunnel,
        args=(
            int(payload["remote_port"]),
            local_server,
            local_server_port,
            client.get_transport(),
        ),
        daemon=True,
    )
    thread.start()

    return payload["share_url"] 
Example #29
Source File: sync_users.py    From fence with Apache License 2.0 4 votes vote down vote up
def _get_from_sftp_with_proxy(self, server, path):
        """
        Download all data from sftp sever to a local dir

        Args:
            server (dict) : dictionary containing info to access sftp server
            path (str): path to local directory

        Returns:
            None
        """
        proxy = None
        if server.get("proxy", "") != "":
            command = "ssh -i ~/.ssh/id_rsa {user}@{proxy} nc {host} {port}".format(
                user=server.get("proxy_user", ""),
                proxy=server.get("proxy", ""),
                host=server.get("host", ""),
                port=server.get("port", 22),
            )
            self.logger.info("SSH proxy command: {}".format(command))

            proxy = ProxyCommand(command)

        with paramiko.SSHClient() as client:
            client.set_log_channel(self.logger.name)

            client.set_missing_host_key_policy(paramiko.WarningPolicy())
            parameters = {
                "hostname": str(server.get("host", "")),
                "username": str(server.get("username", "")),
                "password": str(server.get("password", "")),
                "port": int(server.get("port", 22)),
            }
            if proxy:
                parameters["sock"] = proxy

            self.logger.info("SSH connection parameters: {}".format(parameters))
            client.connect(**parameters)
            with client.open_sftp() as sftp:
                download_dir(sftp, "./", path)

        if proxy:
            proxy.close() 
Example #30
Source File: tunneling.py    From gradio-UI with Apache License 2.0 4 votes vote down vote up
def create_tunnel(payload, local_server, local_server_port):
    client = paramiko.SSHClient()
    # client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.set_missing_host_key_policy(paramiko.WarningPolicy())

    verbose(
        "Connecting to ssh host {}:{} ...".format(payload["host"], int(payload[
                                                                     "port"]))
    )
    try:
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            client.connect(
                hostname=payload["host"],
                port=int(payload["port"]),
                username=payload["user"],
                pkey=paramiko.RSAKey.from_private_key(StringIO(payload["key"])),
            )
    except Exception as e:
        print(
            "*** Failed to connect to {}:{}: {}}".format(payload["host"],
                                                    int(payload["port"]), e)
        )
        sys.exit(1)

    verbose(
        "Now forwarding remote port {} to {}:{} ...".format(int(payload[
                                                              "remote_port"]),
                                                            local_server,
                                                            local_server_port)
    )

    thread = threading.Thread(
        target=reverse_forward_tunnel,
        args=(
            int(payload["remote_port"]),
            local_server,
            local_server_port,
            client.get_transport(),
        ),
        daemon=True,
    )
    thread.start()

    return payload["share_url"]