/***********************************************************************/ private void closeSsh() { ssh.disconnect(); ssh = null; } /***********************************************************************/
/** Disconnect * @param ssh */ public static void disConnect(SshClient ssh) { if(ssh.isConnected()){ ssh.disconnect(); } }
/************************************************************************/ private static SftpClient sshLogin(FTPConfig config, SshClient ssh) throws IOException { ssh.setSocketTimeout(60000); ssh.connect(config.host, new IgnoreHostKeyVerification()); PasswordAuthenticationClient pwd = new PasswordAuthenticationClient(); pwd.setUsername(config.userName); pwd.setPassword(config.password); ssh.authenticate(pwd); SftpClient sftp = ssh.openSftpClient(); return sftp; } /************************************************************************/
/** * Connect. This action simulates all the actions required for a SSH connection * * @param host the hostname of the host you want to connect to * @param port the port of the host you want to connect to * @param username the username required for authentication * @param password the password required for authentication * @return the ssh client you connected to * @throws IOException Signals that an I/O exception has occurred. */ public static SshClient connect(String host, int port,String username,String password) throws IOException { SSH_LOG.info("Connecting to " + host); SshClient ssh = new SshClient(); ssh.connect(host, port, new IgnoreHostKeyVerification()); PasswordAuthenticationClient passwordAuthenticationClient = new PasswordAuthenticationClient(); passwordAuthenticationClient.setUsername(username); passwordAuthenticationClient.setPassword(password); int result = ssh.authenticate(passwordAuthenticationClient); if (result != AuthenticationProtocolState.COMPLETE) { throw new IOException("Login to " + host + ":" + port + " "+ username + "/" + password + " failed"); } SSH_LOG.info("Connected " + host); return ssh; }
@Override public void open() throws IOException { if (ssh.isConnected()) return; /** * SSL connect layer */ ssh.connect( getHost(), getPort(), new LocalKnownHostsKeyVerification(File.createTempFile("xxx", "xxx"))); if (!ssh.isConnected()) { throw new IOException("Unable to connect to " + url); } PasswordAuthenticationClient pwd = new PasswordAuthenticationClient(); pwd.setUsername(getUser()); pwd.setPassword(getPassword()); int result = ssh.authenticate(pwd); if (result == AuthenticationProtocolState.FAILED) { throw new IOException("The authentication failed"); } if (result == AuthenticationProtocolState.PARTIAL) { throw new IOException("The authentication succeeded but another" + "authentication is required"); } if (result == AuthenticationProtocolState.COMPLETE) { System.out.println("The authentication is complete"); } }
/*** * * @param filePattern * @throws IOException */ @SuppressWarnings("unchecked") public void del(String filePattern) throws IOException { final FilenameFilter filter = FileNamePatternUtil.buildFileNameFilterFromWildCard(filePattern); final List<SftpFile> fileContainedWithinWorkingDir = client.ls(); // Retrieve the files that match the given name for (SftpFile file : fileContainedWithinWorkingDir) { if ((file.isFile() && file.canRead()) && filter.accept(null, file.getFilename())) { file.delete(); break; } } }
/***********************************************************************/ public static void sftpUpload(FTPConfig config, File file, String remoteFileName) throws IOException { SshClient ssh = new SshClient(); SftpClient sftp = sshLogin(config, ssh); sftp.mkdirs(remoteFileName.substring(0, remoteFileName.lastIndexOf("/"))); sftp.put(new FileInputStream(file), remoteFileName); sftp.quit(); ssh.disconnect(); } /************************************************************************/
/************************************************************************/ public static File sftpDownload(FTPConfig config, File file, String remoteFileName) throws IOException { SshClient ssh = new SshClient(); SftpClient sftp = sshLogin(config, ssh); sftp.get(remoteFileName, new FileOutputStream(file)); sftp.quit(); ssh.disconnect(); return file; } /***********************************************************************/
/** * Put file to remote host. * * @param host the hostname of the client * @param port the port number the user want to use for connection * @param username the username required for authentication * @param password the password required for authentication * @param localfilePath the localfile path where the file is situated * @param remotePath the remote path where the file is going to be put * @param fileName the file name you want to put * @throws IOException Signals that an I/O exception has occurred. */ @SuppressWarnings("unchecked") public static void putFileToRemoteHost(String host, int port,String username,String password, String localfilePath,String remotePath,String fileName)throws IOException { SftpClient sftp = getSftpClient(host,port, username, password); sftp.lcd(localfilePath); sftp.cd(remotePath); sftp.put(fileName); List<SftpFile> dirContents = sftp.ls(remotePath); Iterator<SftpFile> it = dirContents.iterator(); while(it.hasNext()){ if(it.next().getFilename().equals(fileName)){ SSH_LOG.info("The file " + fileName + " was tranferred successfully to " + remotePath); return; } } SSH_LOG.error("The file " + fileName + " was not tranferred to " + remotePath); }
/** * List the content of the directory specified in the SFTPConfigurationInfo * used to build an instance of this object. Only the file are returned, * directories are ignored, because this is not relevant since this * component does not allow the user to swich from a directory to another. * * @return the list of the files found in the "working directory" specified * the SFTPConnectionInfo object which configures this connection * @throws IOException * if any IO problem occur while sending file or connecting to * server */ public List<String> list() throws IOException { // The list used to store the result of the ls operation final List<String> fileList = new ArrayList<String>(); List<SftpFile> sftpFiles = client.ls(); for (SftpFile file : sftpFiles) { if (file.isFile()) { if (logger.isLoggable(Level.FINE)) { logger.fine("file : " + file.getFilename()); } fileList.add(file.getFilename()); } } return fileList; }
/** * Gets the file from remote host. * * @param host the hostname of the client * @param port the port number the user want to use for connection * @param username the username required for authentication * @param password the password required for authentication * @param remoteFilePath remotePath the remote path from where the file is going to be get * @param localfilePath the local file path where the file is going to be put * @param fileName the name of the file you want to transfer * @return the file from the remote host * @throws IOException Signals that an I/O exception has occurred. */ public static void getFileFromRemoteHost(String host, int port,String username,String password, String remoteFilePath,String localPath,String fileName) throws IOException { SftpClient sftp = getSftpClient(host, port,username, password); sftp.cd(remoteFilePath); sftp.lcd(localPath); sftp.get(fileName); File f = new File(localPath+System.getProperty("file.separator")+fileName); if (!f.exists()){ SSH_LOG.error("The file " + fileName + " was not tranferred to " + localPath); } else{ SSH_LOG.info("The file " + fileName + " was tranferred successfully to " + localPath); } }
private boolean openSession() throws IOException { open(); /** * open a new channel */ session = ssh.openSessionChannel(); /** * emulate a terminal */ session.requestPseudoTerminal("ansi", 132, 24, 132, 24, ""); return session.startShell(); }
/** * Create directory on remote server. * * @param operationName * The remote directory creation is not available for all operation. * @throws IOException * if any IO problem occur while sending file or connecting to server */ public void createRemoteDirectoryIfNeeded(final String operationName) throws IOException { final String directory = this.info.getDirectory(); if (this.info.isCreateFolder() && !StringHelper.isNullOrEmpty(directory) && ((SFTPConstants.MPUT.equalsIgnoreCase(operationName)) || SFTPConstants.PUT.equalsIgnoreCase(operationName))) { // write operation : create all necessary folders try { this.client.cd(directory); } catch (final FileNotFoundException e) { // In principle, this exception occurs when the remote directory does not exist. this.client.mkdirs(directory); } } }
@Override public void destroyObject(final PooledObject<WrappedSftpClient> pooledClient) throws Exception { final WrappedSftpClient client = pooledClient.getObject(); if (client != null) { final SftpClient activeSftpClient = client.getActiveSftpClient(); if (this.logger.isLoggable(Level.FINEST)) { this.logger.finest( "Log out user and disconnect ssh session : [" + this.connectionConfiguration.toString() + "]"); } if (activeSftpClient != null && !activeSftpClient.isClosed()) { activeSftpClient.quit(); } if (client.isConnected()) { client.disconnect(); } } }
/** * Create an SFTP connection to a client * * @param host the hostname of the client * @param port the port the user want to use for connection * @param username the username required for authentication * @param password the password required for authentication * @return the client * @throws IOException Signals that an I/O exception has occurred. */ public static SftpClient getSftpClient(String host,int port, String username,String password) throws IOException { SshClient ssh = connect(host, port,username, password); return ssh.openSftpClient(); }
private boolean openSession() throws IOException { open(); /** * open a new channel */ session = ssh.openSftpChannel(); return session != null; }
@Override public boolean validateObject(final PooledObject<WrappedSftpClient> pooledClient) { this.logger.finest("Validate instance of SFTPClient"); final WrappedSftpClient client = pooledClient.getObject(); if (client == null) { return false; } try { final SftpClient activeSftpClient = client.getActiveSftpClient(); if (activeSftpClient != null && !activeSftpClient.isClosed() && client.isConnected()) { this.logger.finest("SFTPClient is connected"); return true; } } catch (final IOException e) { this.logger.log(Level.WARNING, "An error occurs validating pooled connection. Error skiped", e); } return false; } }
/** * Retrieve the file given by its filename on the SFTP server. * * @param filePattern * name of the file to get from the SFTP server * @return the retrieved file, streamed * @throws IOException * if any IO problem occur while sending file or connecting to * server */ @SuppressWarnings("unchecked") public Document get(final String filePattern) throws IOException { final FilenameFilter filter = FileNamePatternUtil.buildFileNameFilterFromWildCard(filePattern); // Holds the result of the GET operation Document result = null; final List<SftpFile> fileContainedWithinWorkingDir = client.ls(); for (SftpFile file : fileContainedWithinWorkingDir) { if ((file.isFile() && file.canRead()) && filter.accept(null, file.getFilename())) { result = this.getAsDocument(file, client); break; } } // If the file doen't exist if (result == null) { throw new IOException("Can not find the specified resource"); } return result; }
@Override public void close() throws IOException { ssh.disconnect(); super.close(); }
/** * Retrieve the file given by its filename on the SFTP server. * * @param filePattern * name of the file to get from the SFTP server * @return the retrieved file * @throws IOException * if any IO problem occur while sending file or connecting to * server */ @SuppressWarnings("unchecked") public DataHandler getAsAttachment(final String filePattern) throws IOException { final FilenameFilter filter = FileNamePatternUtil.buildFileNameFilterFromWildCard(filePattern); // Holds the result of the GET operation DataHandler retrievedFile = null; // Retrieve all the files from the current directory List<SftpFile> fileContainedWithinWorkingDir = client.ls(); // Retrieve the files that match the given name for (SftpFile file : fileContainedWithinWorkingDir) { if ((file.isFile() && file.canRead()) && filter.accept(null, file.getFilename())) { retrievedFile = this.getAsDataHandler(file, client); break; } } // If the file doen't exist if (retrievedFile == null) { throw new IOException("File not found"); } return retrievedFile; }