Recently, I encountered the need to upload files to Linux servers during redevelopment, and now I have sorted out the code notes.
This connection method takes into account concurrency problem, and when creating an FTP connection, each connection object is stored in
ThreadLocal<Ftp> to ensure that each thread has no effect on the opening and closing of FTP.
package com.test.utils;import java.io.BufferedInputStream;import java.io.File;import java.io.FileFilter;import java.io.FileInputStream;import java.io.InputStream;import java.util.ArrayList;import java.util.Date;import java.util.List;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import com.jcraft.jsch.ChannelSftp;import com.jcraft.jsch.JSch;import com.jcraft.jsch.Session;public class Ftp { //Print log log private static final Log logger = LogFactory.getLog(Ftp.class); private static Date last_push_date = null; private Session sshSession; private ChannelSftp channel; private static ThreadLocal<Ftp> sftpLocal = new ThreadLocal<Ftp>(); private Ftp(String host, int port, String username, String password) throws Exception { JSch jsch = new JSch(); jsch.getSession(username, host, port); //Get session sshSession = jsch.getSession(username, host, port); sshSession.setPassword(password); //Modify the value of GSSAPIAuthentication in the server /etc/ssh/sshd_config to yes to no, which solves the user's inability to log in remotely sshSession.setConfig("userauth.gssapi-with-mic", "no"); //Set properties for the session object. When accessing the server for the first time, you do not need to enter yes sshSession.setConfig("StrictHostKeyChecking", "no"); sshSession.connect(); //Get the sftp channel channel = (ChannelSftp)sshSession.openChannel("sftp"); channel.connect(); logger.info("Connected ftp successfully!" + sshSession); } /** * Is it connected* * @return */ private boolean isConnected() { return null != channel && channel.isConnected(); } /** * Get the sftp client stored in the local thread* * @return * @throws Exception */ public static Ftp getSftpUtil(String host, int port, String username, String password) throws Exception { //Get the local thread Ftp sftpUtil = sftpLocal.get(); if (null == sftpUtil || !sftpUtil.isConnected()) { //Prevent the new connection to prevent the local thread and implement concurrent processing sftpLocal.set(new Ftp(host, port, username, password)); } return sftpLocal.get(); } /** * Release the sftp client that stores the local thread*/ public static void release() { if (null != sftpLocal.get()) { sftpLocal.get().closeChannel(); logger.info("Close connection" + sftpLocal.get().sshSession); sftpLocal.set(null); } } /** * Close channel* * @throws Exception */ public void closeChannel() { if (null != channel) { try { channel.disconnect(); } catch (Exception e) { logger.error("Exception occurred when closing the SFTP channel:", e); } } if (null != sshSession) { try { sshSession.disconnect(); } catch (Exception e) { logger.error("SFTP close session exception:", e); } } } /** * @param directory The directory for uploading ftp* @param uploadFile Local file directory* */ public void upload(String directory, String uploadFile) throws Exception { try {<br> //Execute list display ls Command channel.ls(directory);<br> //Execute the drive letter switching cd command channel.cd(directory); List<File> files = getFiles(uploadFile, new ArrayList<File>()); for (int i = 0; i < files.size(); i++) { File file = files.get(i); InputStream input = new BufferedInputStream(new FileInputStream(file)); channel.put(input, file.getName()); try { if (input != null) input.close(); } catch (Exception e) { e.printStackTrace(); logger.error(file.getName() + "Exception when closing the file...Exception!" + e.getMessage()); } if (file.exists()) { boolean b = file.delete(); logger.info(file.getName() + "File uploaded! Delete ID:" + b); } } } } catch (Exception e) { logger.error("[subdirectory is being created]:",e); //Create subdirectory channel.mkdir(directory); } } //Get file public List<File> getFiles(String realpath, List<File> files) { File realFile = new File(realpath); if (realFile.isDirectory()) { File[] subfiles = realFile.listFiles(new FileFilter() { @Override public boolean accept(File file) { if (null == last_push_date ) { return true; } else { long modifyDate = file.lastModified(); return modifyDate > last_push_date.getTime(); } } }); for (File file : subfiles) { if (file.isDirectory()) { getFiles(file.getAbsolutePath(), files); } else { files.add(file); } if (null == last_push_date) { last_push_date = new Date(file.lastModified()); } else { long modifyDate = file.lastModified(); if (modifyDate > last_push_date.getTime()) { last_push_date = new Date(modifyDate); } } } } return files; }}Summarize
The above is the Java remote connection to Linux server, execute commands and upload files introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message. The editor will reply to everyone in time!