一、导入maven依赖:
<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>build210</version>
</dependency>
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>
2.Demo示例:
package com.igenetech.manage.utils;
import com.jcraft.jsch.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Date;
public class UploadFileUtil {
//jsonArray是要写入的内容,使用时可忽略,换成自己的参数。。
public static void upLoadToIgenetech(String content, String fileName){
String dPath="/usr/demo/";
JSch jsch = new JSch();
Session session = null;
try {
//用户名、ip地址、端口号
session = jsch.getSession("username", "192.168.1.100", 22);
} catch (JSchException e) {
e.printStackTrace();
}
// 设置登陆主机的密码
session.setPassword("password");// 设置密码
// 设置第一次登陆的时候提示,可选值:(ask | yes | no)
session.setConfig("StrictHostKeyChecking", "no");
// 设置登陆超时时间
try {
session.connect(300000);
} catch (JSchException e) {
e.printStackTrace();
}
Channel channel = null;
try {
channel = (Channel) session.openChannel("sftp");
channel.connect(10000000);
ChannelSftp sftp = (ChannelSftp) channel;
String lastPath = DateTimeUtils.format(new Date(), "yyyyMM");
try {
sftp.cd(dPath+lastPath);
} catch (SftpException e) {
sftp.mkdir(dPath+lastPath);
sftp.cd(dPath+lastPath);
}
OutputStream o = null;
File file = new File(dPath+lastPath + "/" + fileName);
o = sftp.put(file.getName());File(dPath+lastPath+"/"+fileName));
o.write(content.toString().getBytes("UTF-8"));
o.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
session.disconnect();
channel.disconnect();
}
}
}