Secure File Transfer Protocol的缩写,安全文件传送协议。
1、连接
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) { } return sftp;
2、操作
//上传文件 try { sftp.cd(directory); File file=new File(uploadFile); sftp.put(new FileInputStream(file), file.getName()); System.out.println("上传成功!"); } catch (Exception e) { e.printStackTrace(); } //下载文件 try { sftp.cd(directory); File file=new File(saveFile); sftp.get(downloadFile, new FileOutputStream(file)); } catch (Exception e) { e.printStackTrace(); } //删除文件 try { sftp.cd(directory); sftp.rm(deleteFile); } catch (Exception e) { e.printStackTrace(); }
3、断开连接(还有session会话、channel对象)//根据项目情况断开连接
if(null != channel ){ System.out.println("断开Channel连接"); channel.disconnect(); } if(null != sftp ){ System.out.println("断开ChannelSftp连接"); sftp.disconnect(); } if(null != sshSession ){ System.out.println("断开Session连接"); sshSession.disconnect(); }
4、测试
public static final String HOST = "x.x.x.x"; public static final int PORT =**; public static final String USERNAME = "**"; public static final String PASSWORD = "***"; public static final String DIRECTORY = "/ent/post_res/"; public static void main(String[] args) { SFTPUploadBean sf = new SFTPUploadBean(); //本地文件 String uploadFile = "G:\\sftp.txt"; //连接 ChannelSftp sftp=sf.connect(HOST, PORT, USERNAME, PASSWORD); //操作 sf.upload(DIRECTORY, uploadFile, sftp); //关闭连接 sf.free(sftp); System.exit(0); }