[Switch] java connects to a remote host through SSH and uploads and downloads files

 There are many ways for Java to connect to a remote host. What I share with you here is to connect to a remote host through ssh, using the jsch jar package, and the resources are here.

    Friends who don't know what ssh is can look for relevant information on the Internet. Here is a simple explanation: SSH is the abbreviation of Secure Shell (Secure Shell Protocol), which is formulated by the Network Working Group of the IETF. Security protocol based on application layer and transport layer. SSH provides support for server authentication, data confidentiality, information integrity, etc. at the transport layer, and provides client authentication for the server. Using the SSH protocol can effectively prevent information leakage during remote management. All transmitted data can be encrypted through SSH, and it can also prevent DNS spoofing and IP spoofing.

    The following is a sftp help class written by myself. There are errors or unreasonable improvements in the code. I hope to point out and learn and grow together:

package com.app.pt.backup.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Vector;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.app.common.util.FileUtil;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;

/**
 * SFTP helper class
 * @author wangbailin
 *
 */
public class SFTPUtil {
	
	private static Log log = LogFactory.getLog(SFTPUtil.class);
	
	/**
	 * Connect to sftp server
	 * @param host remote host ip address
	 * @param port sftp connection port, null is the default port
	 * @param user username
	 * @param password password
	 * @return
	 * @throws JSchException
	 */
	public static Session connect(String host, Integer port, String user, String password) throws JSchException{
		Session session = null;
		try {
			JSch jsch = new JSch();
			if(port != null){
				session = jsch.getSession(user, host, port.intValue());
			}else{
				session = jsch.getSession(user, host);
			}
			session.setPassword(password);
			//Set the prompt when logging in for the first time, optional value: (ask | yes | no)
			session.setConfig("StrictHostKeyChecking", "no");
			//30 seconds connection timeout
			session.connect(30000);
		} catch (JSchException e) {
			e.printStackTrace ();
			System.out.println("SFTPUitl got connection error");
			throw e;
		}
		return session;
	}
	
	/**
	 * sftp upload file (folder)
	 * @param directory
	 * @param uploadFile
	 * @param sftp
	 * @throws Exception
	 */
	public static void upload(String directory, String uploadFile, ChannelSftp sftp) throws Exception{
		System.out.println("sftp upload file [directory] : "+directory);
		System.out.println("sftp upload file [uploadFile] : "+ uploadFile);
		File file = new File(uploadFile);
		if(file.exists()){
			//It's a bit opportunistic here, because ChannelSftp can't interpret the file path of the remote linux host, which is helpless
			try {
				Vector content = sftp.ls(directory);
				if(content == null){
					sftp.mkdir(directory);
				}
			} catch (SftpException e) {
				sftp.mkdir(directory);
			}
			// enter the target path
			sftp.cd(directory);
			if(file.isFile()){
				InputStream ins = new FileInputStream(file);
				// Chinese name
				sftp.put(ins, new String(file.getName().getBytes(),"UTF-8"));
				//sftp.setFilenameEncoding("UTF-8");
			}else{
				File[] files = file.listFiles();
				for (File file2 : files) {
					String dir = file2.getAbsolutePath();
					if(file2.isDirectory()){
						String str = dir.substring(dir.lastIndexOf(file2.separator));
						directory = FileUtil.normalize(directory + str);
					}
					upload(directory,dir,sftp);
				}
			}
		}
	}
	
	/**
	 * sftp download file (folder)
	 * @param directory Download file parent directory
	 * @param srcFile full path to download file
	 * @param saveFile save file path
	 * @param sftp ChannelSftp
	 * @throws UnsupportedEncodingException
	 */
	public static void download(String directory,String srcFile, String saveFile, ChannelSftp sftp) throws UnsupportedEncodingException {
		Vector conts = null;
		try{
			conts = sftp.ls (srcFile);
		} catch (SftpException e) {
			e.printStackTrace ();
			log.debug("ChannelSftp sftp listing file error",e);
		}
		File file = new File(saveFile);
		if(!file.exists()) file.mkdir();
		//document
		if(srcFile.indexOf(".") > -1){
			try {
				sftp.get(srcFile, saveFile);
			} catch (SftpException e) {
				e.printStackTrace ();
				log.debug("ChannelSftp sftp download file error",e);
			}
		}else{
		//folder (path)
			for (Iterator iterator = conts.iterator(); iterator.hasNext();) {
				LsEntry obj = (LsEntry) iterator.next ();
				String filename = new String(obj.getFilename().getBytes(),"UTF-8");
				if(!(filename.indexOf(".") > -1)){
					directory = FileUtil.normalize(directory + System.getProperty("file.separator") + filename);
					srcFile = directory;
					saveFile = FileUtil.normalize(saveFile + System.getProperty("file.separator") + filename);
				}else{
					//Scan to skip directly to the file name ".."
					String[] arrs = filename.split("\\.");
					if((arrs.length > 0) && (arrs[0].length() > 0)){
						srcFile = FileUtil.normalize(directory + System.getProperty("file.separator") + filename);
					}else{
						continue;
					}
				}
				download(directory, srcFile, saveFile, sftp);
			}
		}
	}
}

  Use the sftp helper class to upload or download:

ChannelSftp sftp = null;
Session session = null;
try {
	session = SFTPUtil.connect(host, port, username, password);
	Channel channel = session.openChannel("sftp");
	channel.connect();
	sftp = (ChannelSftp) channel;
	SFTPUtil.upload(destDir, srcfile.getAbsolutePath(), sftp);
} catch (Exception e) {
	e.printStackTrace ();
	logger.debug(e);
	return UtilMisc.toMap("flag","failure","msg","An error occurred in the backup file to the remote host");
}finally{
	if(sftp != null)sftp.disconnect();
	if(session != null)session.disconnect();
}

 (From: http://blog.csdn.net/wangbailin2009/article/details/20232999 )

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326929074&siteId=291194637