def __connect(self): try: logger.info('Attempting Authentication') self.client = SSHClient() self.client.load_system_host_keys() self.client.set_missing_host_key_policy(MissingHostKeyPolicy()) self.client.connect(self.host, username=self.user, password=self.password, key_filename=self.ssh_key_filepath, look_for_keys=True, timeout=5000) logger.info('Successfully Authenticated') # self.scp = SCPClient(self.client.get_transport()) except AuthenticationException as e: logger.error('Authentication failed.') logger.error(e) raise e except Exception as err: logger.error('connection failed') logger.error(err) raise err finally: return self.client
def connect(state, host, **kwargs): ''' Connect to a single host. Returns the SSH client if succesful. Stateless by design so can be run in parallel. ''' logger.debug('Connecting to: {0} ({1})'.format(host.name, kwargs)) name = host.name hostname = host.data.ssh_hostname or name try: # Create new client & connect to the host client = SSHClient() client.set_missing_host_key_policy(MissingHostKeyPolicy()) client.connect(hostname, **kwargs) # Enable SSH forwarding session = client.get_transport().open_session() AgentRequestHandler(session) # Log logger.info('{0}{1}'.format( host.print_prefix, click.style('Connected', 'green'), )) return client except AuthenticationException as e: auth_kwargs = {} for key, value in kwargs.items(): if key in ('username', 'password'): auth_kwargs[key] = value continue if key == 'pkey' and value: auth_kwargs['key'] = host.data.ssh_key auth_args = ', '.join('{0}={1}'.format(key, value) for key, value in auth_kwargs.items()) _log_connect_error(host, 'Authentication error', auth_args) except SSHException as e: _log_connect_error(host, 'SSH error', e) except gaierror: _log_connect_error(host, 'Could not resolve hostname', hostname) except socket_error as e: _log_connect_error(host, 'Could not connect', e) except EOFError as e: _log_connect_error(host, 'EOF error', e)
def connect(state, host): ''' Connect to a single host. Returns the SSH client if succesful. Stateless by design so can be run in parallel. ''' kwargs = _make_paramiko_kwargs(state, host) logger.debug('Connecting to: {0} ({1})'.format(host.name, kwargs)) # Hostname can be provided via SSH config (alias), data, or the hosts name hostname = kwargs.pop( 'hostname', host.data.ssh_hostname or host.name, ) try: # Create new client & connect to the host client = SSHClient() client.set_missing_host_key_policy(MissingHostKeyPolicy()) client.connect(hostname, **kwargs) # Enable SSH forwarding session = client.get_transport().open_session() AgentRequestHandler(session) return client except AuthenticationException: auth_kwargs = {} for key, value in kwargs.items(): if key in ('username', 'password'): auth_kwargs[key] = value continue if key == 'pkey' and value: auth_kwargs['key'] = host.data.ssh_key auth_args = ', '.join('{0}={1}'.format(key, value) for key, value in auth_kwargs.items()) _raise_connect_error(host, 'Authentication error', auth_args) except SSHException as e: _raise_connect_error(host, 'SSH error', e) except gaierror: _raise_connect_error(host, 'Could not resolve hostname', hostname) except socket_error as e: _raise_connect_error(host, 'Could not connect', e) except EOFError as e: _raise_connect_error(host, 'EOF error', e)
def connect(state, host, **kwargs): ''' Connect to a single host. Returns the SSH client if succesful. Stateless by design so can be run in parallel. ''' logger.debug('Connecting to: {0} ({1})'.format(host.name, kwargs)) name = host.name hostname = host.data.ssh_hostname or name try: # Create new client & connect to the host client = SSHClient() client.set_missing_host_key_policy(MissingHostKeyPolicy()) client.connect(hostname, **kwargs) # Enable SSH forwarding session = client.get_transport().open_session() AgentRequestHandler(session) # Log logger.info('{0}{1}'.format( host.print_prefix, click.style('Connected', 'green'), )) return client except AuthenticationException as e: logger.error('Auth error on: {0}, {1}'.format(name, e)) except SSHException as e: logger.error('SSH error on: {0}, {1}'.format(name, e)) except gaierror: if hostname == name: logger.error('Could not resolve {0}'.format(name)) else: logger.error('Could not resolve for {0} (SSH host: {1})'.format( name, hostname)) except socket_error as e: logger.error( 'Could not connect: {0}:{1}, {2}'.format(name, kwargs.get('port', 22), e), ) except EOFError as e: logger.error('EOF error connecting to {0}: {1}'.format(name, e))
def make_tunnel(ssh_user, ssh_password, ssh_host, ssh_port, dst_ip, dst_port, command): client = SSHClient() client.set_missing_host_key_policy(MissingHostKeyPolicy()) client.connect(hostname=ssh_host, username=ssh_user, password=ssh_password, port=ssh_port) transport = client.get_transport() tunnel = transport.open_channel('direct-tcpip', (dst_ip, dst_port), ('127.0.0.1', 0)) yield tunnel tunnel.close() client.close()
parser = argparse.ArgumentParser() parser.add_argument("-c", "--command", help="command to run on remote host (default: {})".format(command)) parser.add_argument("-r", "--remote", help="remote host (default: {})".format(remote)) args = parser.parse_args() if args.command: command = args.command if args.remote: remote = args.remote.strip() # try to open a session ssh_client = SSHClient() ssh_client.set_missing_host_key_policy(MissingHostKeyPolicy()) try: ssh_client.connect(remote, port, user, password) except socket.error: log.error("no SSH connection possible to '{}:{}'!".format(remote, port)) ssh_client.close() sys.exit(1) except AuthenticationException: log.error("wrong username or password!") ssh_client.close() sys.exit(1) # check if we are connected to the target device if not ssh_client.get_transport(): log.error("not connected to host {}".format(remote)) ssh_client.close()