package com.supan.sftp; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.Properties; import java.util.Vector; import junit.framework.TestCase; import com.jcraft.jsch.Channel; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.JSch; import com.jcraft.jsch.Session; import com.jcraft.jsch.SftpATTRS; import com.jcraft.jsch.SftpException; import com.jcraft.jsch.ChannelSftp.LsEntry; public class SftpTest extends TestCase { public ChannelSftp connect(String host, int port, String username, String password) { ChannelSftp sftp = null; try { JSch jsch = new JSch(); Session sshSession = jsch.getSession(username, host, port); System.out.println("Session created. "); sshSession.setPassword(password); Properties sshConfig = new Properties(); sshConfig.put("StrictHostKeyChecking", "no"); sshSession.setConfig(sshConfig); sshSession.connect(); System.out.println("Session connected."); System.out.println("Opening Channel."); Channel channel = sshSession.openChannel("sftp"); channel.connect(); sftp = (ChannelSftp) channel; System.out.println("Connected to " + host + "."); } catch (Exception e) { e.printStackTrace(); } return sftp; } /** * 下載文件 * @param directory下載目錄 * @param downloadFile下載的文件 * @param saveFile存在本地的路徑 * @param sftp */ public void download(String directory, String downloadFile, String saveFile, ChannelSftp sftp) { try { sftp.cd(directory); File file = new File(saveFile); FileOutputStream fileOutputStream =new FileOutputStream(file); sftp.get(downloadFile, fileOutputStream ); fileOutputStream.close(); fileOutputStream=null; file =null; } catch (Exception e) { e.printStackTrace(); } } /** * 上傳文件 * @param directory上傳的目錄 * @param uploadFile要上傳的文件 * @param sftp */ public void upload(String directory, String uploadFile, ChannelSftp sftp) { try { sftp.cd(directory); File file = new File(uploadFile); FileInputStream fileInputStream = new FileInputStream(file); sftp.put(fileInputStream, file.getName()); fileInputStream.close(); fileInputStream=null; } catch (Exception e) { e.printStackTrace(); } } public void testSftp() { ChannelSftp channelSftp = connect("192.168.159.128",22,"root","supanccy"); download("ssh-3.2.9.1","FAQ","c://FAQ",channelSftp); } public void testAllPfiles() { ChannelSftp channelSftp = connect("192.168.159.128",22,"root","supanccy"); // channelSftp.cd("ssh-3.2.9.1"); try { Vector<LsEntry> filelist = channelSftp.ls("ssh-3.2.9.1"); for(LsEntry entry : filelist) { System.out.println(entry.getFilename()); SftpATTRS attrs = entry.getAttrs(); //获取读取权限 System.out.println(attrs.getPermissionsString()); //获取时间戳1 System.out.println(attrs.getMtimeString()); //获取事件戳 System.out.println(attrs.getAtimeString()); System.out.println("**************"); } } catch (SftpException e) { e.printStackTrace(); } } }