一、JSch 简介
JSch 是SSH2的一个纯Java实现。它允许你连接到一个sshd 服务器,使用端口转发,X11转发,文件传输等等。你可以将它的功能集成到你自己的 程序中。同时该项目也提供一个J2ME版本用来在手机上直连SSHD服务器。
二、java利用jcraft实现文件上传与下载
第一步:这里使用maven管理项目,所以需要引入maven支持,添加maven依赖

<!-- https://mvnrepository.com/artifact/com.jcraft/jsch -->
<dependency><groupId>com.jcraft</groupId><artifactId>jsch</artifactId><version>0.1.54</version>
</dependency>

第二步:写一个类sshconfiguration,作用是存储要登录机器的host,port,username.pwd,其实这里也可以使用一个配置文件来管理

public class SshConfiguration {private String host;private int    port;private String userName;private String password;getter AND setter(shenglve不写)
}

第三步:写一个类sshutil,实现上传下载

public class SshUtil {private ChannelSftp channelSftp;private ChannelExec channelExec;private Session session=null;private int timeout=60000;public SshUtil(SshConfiguration conf) throws JSchException {System.out.println("try connect to  "+conf.getHost()+",username: "+conf.getUserName()+",password: "+conf.getPassword()+",port: "+conf.getPort());JSch jSch=new JSch(); //创建JSch对象session=jSch.getSession(conf.getUserName(), conf.getHost(), conf.getPort());//根据用户名,主机ip和端口获取一个Session对象session.setPassword(conf.getPassword()); //设置密码Properties config=new Properties();config.put("StrictHostKeyChecking", "no");session.setConfig(config);//为Session对象设置propertiessession.setTimeout(timeout);//设置超时session.connect();//通过Session建立连接}public void download(String src,String dst) throws JSchException, SftpException{//src linux服务器文件地址,dst 本地存放地址channelSftp=(ChannelSftp) session.openChannel("sftp");channelSftp.connect();channelSftp.get(src, dst);channelSftp.quit();}public void upLoad(String src,String dst) throws JSchException,SftpException{//src 本机文件地址。 dst 远程文件地址channelSftp=(ChannelSftp) session.openChannel("sftp");channelSftp.connect();channelSftp.put(src, dst);channelSftp.quit();}public void close(){session.disconnect();}
} 

第四,测试

public static void main(String[] args){SshConfiguration configuration=new SshConfiguration();configuration.setHost("172.17.1.232");configuration.setUserName("root");configuration.setPassword("root275858");configuration.setPort(22);try{
//            SshUtil sshUtil=new SshUtil(configuration);
//            sshUtil.download("/home/cafintech/Logs/metaData/meta.log","D://meta.log");
//            sshUtil.close();
//            System.out.println("文件下载完成");SshUtil sshUtil=new SshUtil(configuration);sshUtil.upLoad("D://meta.log","/home/cafintech/");sshUtil.close();System.out.println("文件上传完成");}catch(Exception e){e.printStackTrace();}}
}