public class MySFTP 开区服务器 {
public ChannelSftp connect(String host, int port, String username, String password) { ChannelSftp sftp = null; try { JSch jsch = new JSch(); jsch.getSession(username, host, port); 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) { } return sftp; } public void upload(String directory, String uploadFile, ChannelSftp sftp) { try { sftp.cd(directory); File file = new File(uploadFile); sftp.put(new FileInputStream(file), file.getName()); } catch (Exception e) { e.printStackTrace(); } } public boolean download(String directory, String downloadFile, String saveFile, ChannelSftp sftp) { try { sftp.cd(directory); File file = new File(saveFile); sftp.get(downloadFile, new FileOutputStream(file)); return true; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (SftpException e) { e.printStackTrace(); } return false; } public void delete(String directory, String deleteFile, ChannelSftp sftp) { try { sftp.cd(directory); sftp.rm(deleteFile); } catch (Exception e) { e.printStackTrace(); } } public Vector listFiles(String directory, ChannelSftp sftp) throws SftpException { return sftp.ls(directory); } public static void main(String[] args) { MySFTP sf = new MySFTP(); String host = "ip address"; int port = 22; String username = "******"; String password = "*******"; String directory = "/home/develop/data-two/logs";// String uploadFile = "D:\\weather\\sfpt"; String downloadFile = "2016-9-7_results.log"; String saveFile = "D:\\weather\\sfpt\\bb.log";// String deleteFile = "delete.txt"; ChannelSftp sftp = sf.connect(host, port, username, password);// sf.upload(directory, uploadFile, sftp); boolean download = sf.download(directory, downloadFile, saveFile, sftp); if (download) { sftp.disconnect(); sftp.quit(); }// sf.delete(directory, deleteFile, sftp);// try {// sftp.cd(directory);// sftp.mkdir("ss");// System.out.println("finished");// } catch (Exception e) {// e.printStackTrace();// } }}