jar 包:
jsch-0.1.52.jar
http://central.maven.org/maven2/com/jcraft/jsch/0.1.52/jsch-0.1.52.jar
junit-4.10.jar
http://central.maven.org/maven2/junit/junit/4.10/junit-4.10.jar
slf4j-api-1.4.3.jar 、 slf4j-log4j12-1.4.0.jar、 log4j-1.2.17.jar
SftpUtils.java
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.util.Properties; import java.util.Vector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.jcraft.jsch.Channel; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; import com.jcraft.jsch.SftpException; /** * @ClassName: SftpUtils * @Description: 使用sftp操作远程Linux文件 * @author * @company * @date 2015年11月12日 * @version V1.0 */ public final class SftpUtils { private static final Logger log = LoggerFactory.getLogger(SftpUtils.class); private volatile static SftpUtils instance; private SftpUtils() { } /** 单例模式获取对象SftpUtils的实例 */ public static SftpUtils getInstance() { if (null == instance) { synchronized (SftpUtils.class) { if (null == instance) { instance = new SftpUtils(); } } } return instance; } /** ssh会话 */ private volatile Session sshSession = null; /** * 连接sftp服务器 * * @param host * 主机 * @param port * 端口 * @param username * 用户名 * @param password * 密码 * @return ChannelSftp */ public ChannelSftp connect(String host, int port, String username, String password) throws Exception { log.info("SftpUtils.connect(...),host=" + host); log.info("SftpUtils.connect(...),port=" + port); log.info("SftpUtils.connect(...),username=" + username); log.info("SftpUtils.connect(...),password=" + password); ChannelSftp sftp = null; Channel channel = null; try { JSch jsch = new JSch(); jsch.getSession(username, host, port); sshSession = jsch.getSession(username, host, port); log.info("Session created."); sshSession.setPassword(password); Properties sshConfig = new Properties(); sshConfig.put("StrictHostKeyChecking", "no"); sshSession.setConfig(sshConfig); sshSession.connect(); log.info("Session connected."); channel = sshSession.openChannel("sftp"); channel.connect(); sftp = (ChannelSftp) channel; log.info("Connected to " + host + " success."); } catch (JSchException e) { log.error("Connect to '" + host + "' fail:" + e.getMessage(), e); } catch (Exception e) { log.error("Connect to '" + host + "' fail:" + e.getMessage(), e); } return sftp; } /** * 上传文件 * * @param ip * 远程服务器ip * @param port * 远程服务器sftp端口号 * @param userName * 远程服务器登录名 * @param password * 远程服务器登录密码 * @param directory * 上传到服务器哪个目录 * @param uploadFile * 要上传的本地文件 * @param sftp */ public void upload(String ip, int port, String userName, String password, String directory, String uploadFile) throws Exception { log.info("Into SftpUtils.upload(...)"); log.info("SftpUtils.upload(...),directory=" + directory); log.info("SftpUtils.upload(...),uploadFile=" + uploadFile); FileInputStream is = null; ChannelSftp sftp = null; try { sftp = this.connect(ip, port, userName, password); sftp.cd(directory); File file = new File(uploadFile); is = new FileInputStream(file); sftp.put(is, file.getName()); log.info("sftp Upload file '" + uploadFile + "' success."); } catch (FileNotFoundException e) { log.error("file '" + uploadFile + "' not found!", e); throw e; } catch (Exception e) { log.error("upload file '" + uploadFile + "' fail:" + e.getMessage(), e); throw e; } finally { log.info("End of SftpUtils.upload(...)"); IOUtils.closeStream(is, null); this.disconnectSftp(sftp); this.disconnectSession(sshSession); } } /** * 下载文件 * * @param ip * 远程服务器ip * @param port * 远程服务器sftp端口号 * @param userName * 远程服务器登录名 * @param password * 远程服务器登录密码 * @param directory * 下载目录 * @param downloadFile * 下载的文件名 * @param saveFile * 存在本地的路径 */ public void download(String ip, int port, String userName, String password, String directory, String downloadFile, String saveFile) throws Exception { log.info("Into SftpUtils.download(...)"); log.info("SftpUtils.download(...),directory=" + directory); log.info("SftpUtils.download(...),downloadFile=" + downloadFile); log.info("SftpUtils.download(...),saveFile=" + saveFile); FileOutputStream os = null; ChannelSftp sftp = null; try { sftp = this.connect(ip, port, userName, password); sftp.cd(directory); File file = new File(saveFile); os = new FileOutputStream(file); sftp.get(downloadFile, os); log.info("sftp download file '" + downloadFile + "' success."); } catch (FileNotFoundException e) { log.error("file '" + downloadFile + "' not found!", e); throw e; } catch (Exception e) { log.error("download file '" + downloadFile + "' fail:" + e.getMessage(), e); throw e; } finally { log.info("End of SftpUtils.download(...)"); IOUtils.closeStream(null, os); this.disconnectSftp(sftp); this.disconnectSession(sshSession); } } /** * 删除文件 * * @param ip * 远程服务器ip * @param port * 远程服务器sftp端口号 * @param userName * 远程服务器登录名 * @param password * 远程服务器登录密码 * @param directory * 要删除文件所在目录 * @param deleteFile * 要删除的文件 * @param sftp */ public void delete(String ip, int port, String userName, String password, String directory, String deleteFile) throws Exception { ChannelSftp sftp = null; try { sftp = this.connect(ip, port, userName, password); sftp.cd(directory); sftp.rm(deleteFile); } catch (Exception e) { log.error("Delete file '" + deleteFile + "' fail:" + e.getMessage(), e); throw e; } finally { this.disconnectSftp(sftp); this.disconnectSession(sshSession); } } /** * 列出目录下的文件 * * @param directory * 要列出的目录 * @param sftp * @return Vector * @throws SftpException */ @SuppressWarnings({ "rawtypes" }) public Vector listFiles(String ip, int port, String userName, String password, String directory) throws Exception { ChannelSftp sftp = null; Vector v = null; try { sftp = this.connect(ip, port, userName, password); v = sftp.ls(directory); } catch (Exception e) { log.error("List all files of '" + directory + "' fail:" + e.getMessage(), e); throw e; } finally { this.disconnectSftp(sftp); this.disconnectSession(sshSession); } return v; } public void disconnectSftp(ChannelSftp sftp) { if (null != sftp && sftp.isConnected()) { log.info("Disconnect ChannelSftp."); sftp.disconnect(); sftp.exit(); sftp = null; } } public void disconnectSession(Session sshSession) { if (null != sshSession && sshSession.isConnected()) { log.info("Disconnect Session."); sshSession.disconnect(); sshSession = null; } } public void disconnectChannel(Channel channel) { if (null != channel && channel.isConnected()) { log.info("Disconnect Channel."); channel.disconnect(); channel = null; } } }
测试类(使用 junit 4)
import static org.junit.Assert.fail; import java.util.Iterator; import java.util.Vector; import org.junit.Before; import org.junit.Test; import com.jcraft.jsch.ChannelSftp; import com.techstar.plat.ftp.SftpUtils; public class TestSftpUtils { private static final String host = "10.0.0.166"; private static final int port = 22; // sftp方式默认端口号是22 private static final String username = "root"; private static final String password = "password"; private static final String directory = "/usr/local/"; @Before public void setUp() throws Exception { } @Test public void connect() { /* 测试是否能远程连接linux服务器 */ ChannelSftp sftp = null; try { sftp = SftpUtils.getInstance().connect(host, port, username, password); System.out.println(sftp.isConnected()); } catch (Exception e) { e.printStackTrace(); } finally { SftpUtils.getInstance().disconnectSftp(sftp); } } @Test public void upload() { /* 将本地文件上传到服务器指定的目录下 */ try { String uploadFile = "D:\\shsddata\\SH_20150519_143533_PAS.DT"; SftpUtils.getInstance().upload(host, port, username, password, directory, uploadFile); System.out.println("Upload success!"); } catch (Exception e) { e.printStackTrace(); } } @Test public void download() { try { String downloadFile = "SH_SCADA.DT"; String saveFile = "D:\\shsddata\\SH_SCADA.DT"; SftpUtils.getInstance().download(host, port, username, password, directory, downloadFile, saveFile); System.out.println("download '" + downloadFile + "' success!"); } catch (Exception e) { e.printStackTrace(); } } @Test public void delete() { fail("Not yet implemented"); } @Test public void listFiles() { /* 列出指定目录下的所有文件及文件夹 */ try { String directory = "/opt/tomcat"; Vector v = SftpUtils.getInstance().listFiles(host, port, username, password, directory); if (null != v && !v.isEmpty()) { Iterator it = v.iterator(); while (it.hasNext()) { System.out.println(it.next().toString()); } } else { System.out.println(directory + " no file"); } } catch (Exception e) { e.printStackTrace(); } } private ChannelSftp connectToServer(String host, int port, String username, String password) throws Exception { ChannelSftp sftp = null; try { sftp = SftpUtils.getInstance().connect(host, port, username, password); } catch (Exception e) { throw e; } return sftp; } }
IOUtils.java
import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import java.nio.channels.Channel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class IOUtils { private static final Logger log = LoggerFactory.getLogger(IOUtils.class); public static void closeChannel(Channel channel) { if (null != channel) { try { channel.close(); } catch (IOException e) { log.error(e.getMessage(), e); } channel = null; } } public static void closeReader(Reader reader) { if (null != reader) { try { reader.close(); reader = null; } catch (IOException e) { log.error("close reader faile!", e); } } } public static void closeStream(InputStream is, OutputStream os) { if (null != is) { try { is.close(); is = null; } catch (IOException e) { log.error("close InputStream fail!", e); } } if (null != os) { try { os.close(); os = null; } catch (IOException e) { log.error("close OutputStream fail!", e); } } } public static void closeWriter(Writer writer) { if (null != writer) { try { writer.close(); } catch (IOException e) { log.error("Close Writer fail:" + e.getMessage(), e); } writer = null; } } /** * @Title: writeStrToFile * @deprecated: 将字符串写入制定的文件中 * @param os * 输出流,包含有用户选择的文件路径 * @param str * 字符串 * @param fileName * 文件名称 * @return int 0:失败, 1:成功 * @throws Exception * @author * @date 2014-11-16 */ public static int writeStrToFile(OutputStream os, String str, String fileName) throws Exception { log.info("Write String to file,the str is:\r\n" + str); log.info("Write String to file,the fileName is:" + fileName); int ret = 0; OutputStreamWriter writer = null; try { writer = new OutputStreamWriter(os); writer.write(str); ret = 1; } catch (FileNotFoundException e) { log.error("Write String to File fail:" + e.getMessage(), e); throw e; } catch (IOException e) { log.error("Write String to File fail:" + e.getMessage(), e); throw e; } catch (Exception e) { log.error("Write String to File fail:" + e.getMessage(), e); throw e; } finally { try { if (null != writer) { // 清空缓冲区,否则下一次输出时会重复输出 writer.flush(); writer.close(); } } catch (IOException e) { log.error("Close OutputStreamWriter fail:" + e.getMessage(), e); } closeStream(null, os); } return ret; } }