java调用SFTP的实现过程
1、引入pom依赖
<!-- sftp-->
<!-- https://mvnrepository.com/artifact/com.jcraft/jsch -->
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>
2、封装工具类
(1)封装工具类
package com.xinghan.keysystem.util.sftp;
import com.alibaba.druid.util.StringUtils;
import com.jcraft.jsch.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import java.io.*;
import java.util.Properties;
import java.util.Vector;
@Component
@Scope("prototype")
public class SftpRootHelper {
private ChannelSftp sftp = null;
private Session sshSession = null;
@Value("${sftpHost}")
public String host;
@Value("${sftpPort}")
public int port;
@Value("${sftpNameRoot}")
public String usernameRoot;
@Value("${sftpPasswordRoot}")
public String passwordRoot;
public SftpRootHelper() {
super();
}
public SftpRootHelper(String username, String password, String host, int port) {
this.usernameRoot = username;
this.passwordRoot = password;
this.host = host;
this.port = port;
}
public ChannelSftp connect() {
JSch jsch = new JSch();
try {
sshSession = jsch.getSession(usernameRoot, host, port);
sshSession.setPassword(passwordRoot);
Properties properties = new Properties();
properties.put("StrictHostKeyChecking", "no");
properties.put("PreferredAuthentications", "password");
sshSession.setConfig(properties);
sshSession.connect();
Channel channel = sshSession.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
} catch (JSchException e) {
throw new RuntimeException("sftp连接失败");
}
return sftp;
}
public boolean downloadFile(String remotePath, String remoteFilename, String localPath, String localFilename)
throws SftpException, IOException, Exception {
FileOutputStream output = null;
boolean success = false;
try {
if (null != remotePath && remotePath.trim() != "") {
sftp.cd(remotePath);
}
File targetFile = new File(localPath);
targetFile.mkdirs();
File localFile = new File(localPath + localFilename);
if (localFile.exists()) {
new File(localPath + localFilename).delete();
System.err.println("文件: " + localPath + localFilename + " 已经存在!");
}
output = new FileOutputStream(localFile);
String file = null;
Vector remoteFilename1 = sftp.ls(remotePath);
for (Object object : remoteFilename1) {
ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) object;
String filename = entry.getFilename();
if (".".equals(filename) || "..".equals(filename)) {
continue;
}
if(filename.contains(remoteFilename)){
file=filename;
break;
}
}
sftp.get(file, output);
success = true;
System.out.println("成功接收文件,本地路径:" + localPath + localFilename);
} catch (SftpException e) {
System.err.println("接收文件时有SftpException异常!");
e.printStackTrace();
return success;
} catch (IOException e) {
System.err.println("接收文件时有I/O异常!");
System.err.println(e.getMessage());
return success;
} finally {
try {
if (null != output) {
output.close();
}
} catch (IOException e) {
System.err.println("关闭文件时出错!");
System.err.println(e.getMessage());
}
}
return success;
}
public String downloadFileOPTK(String remotePath, String remoteFilename,String suffixName, String localPath, String localFilename)
throws SftpException, IOException, Exception {
FileOutputStream output = null;
String success = "false";
try {
if (null != remotePath && remotePath.trim() != "") {
sftp.cd(remotePath);
}
File targetFile = new File(localPath);
targetFile.mkdirs();
File localFile = new File(localPath + localFilename);
if (localFile.exists()) {
new File(localPath + localFilename).delete();
System.err.println("文件: " + localPath + localFilename + " 已经存在!");
}
output = new FileOutputStream(localFile);
String file = null;
Vector remoteFilename1 = sftp.ls(remotePath);
for (Object object : remoteFilename1) {
ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) object;
String filename = entry.getFilename();
if (".".equals(filename) || "..".equals(filename)) {
continue;
}
if(filename.contains(remoteFilename)){
file=filename;
if(file.contains(suffixName)){
file=filename;
break;
}
}
}
sftp.get(file, output);
success = file;
System.out.println("成功接收文件,本地路径:" + localPath + localFilename);
} catch (SftpException e) {
success="false";
System.err.println("接收文件时有SftpException异常!");
e.printStackTrace();
return success;
} catch (IOException e) {
System.err.println("接收文件时有I/O异常!");
System.err.println(e.getMessage());
return success;
} finally {
try {
if (null != output) {
output.close();
}
} catch (IOException e) {
System.err.println("关闭文件时出错!");
System.err.println(e.getMessage());
}
}
return success;
}
public boolean deleteFile(String remotePath, String remoteFilename) throws Exception {
boolean success = false;
try {
if (null != remotePath && remotePath.trim() != "") {
sftp.cd(remotePath);
}
sftp.rm(remoteFilename);
System.err.println("删除远程文件" + remoteFilename + "成功!");
success = true;
} catch (SftpException e) {
System.err.println("删除文件时有SftpException异常!");
e.printStackTrace();
System.err.println(e.getMessage());
return false;
} catch (Exception e) {
System.err.println("删除文件时有异常!");
System.err.println(e.getMessage());
return false;
} finally {
disconnect();
}
return true;
}
public void uploadFile(String remoteFilePath, String uploadFilePath) throws SftpException, FileNotFoundException {
FileInputStream in = null;
connect();
try {
sftp.cd(remoteFilePath);
} catch (SftpException e) {
e.printStackTrace();
try {
String[] dirs = remoteFilePath.split("/");
String tempPath = "";
int index = 0;
mkdirDir(dirs, tempPath, dirs.length, index);
sftp.cd(remoteFilePath);
} catch (SftpException e1) {
e1.printStackTrace();
disconnect();
throw new RuntimeException("ftp创建文件路径失败" + remoteFilePath);
}
}
File file = new File(uploadFilePath);
try {
in = new FileInputStream(file);
sftp.put(in, file.getName());
} catch (FileNotFoundException e) {
throw e;
} catch (SftpException e) {
throw e;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
disconnect();
}
}
public void mkdirDir(String[] dirs, String tempPath, int length, int index) {
index++;
if (index < length) {
tempPath += "/" + dirs[index];
}
try {
sftp.cd(tempPath);
if (index < length) {
mkdirDir(dirs, tempPath, length, index);
}
} catch (SftpException ex) {
try {
sftp.mkdir(tempPath);
sftp.cd(tempPath);
} catch (SftpException e) {
e.printStackTrace();
}
mkdirDir(dirs, tempPath, length, index);
}
}
public void uploadFile(String remoteFilePath, InputStream inputStream, String FileName) throws SftpException {
FileInputStream in = null;
connect();
if (inputStream == null) throw new NullPointerException();
if (FileName == null || StringUtils.isEmpty(FileName)) throw new NullPointerException();
try {
sftp.cd(remoteFilePath);
} catch (SftpException e) {
e.printStackTrace();
try {
sftp.mkdir(remoteFilePath);
sftp.cd(remoteFilePath);
} catch (SftpException e1) {
e1.printStackTrace();
disconnect();
throw new RuntimeException("ftp创建文件路径失败 : " + remoteFilePath);
}
}
try {
sftp.put(inputStream, FileName);
} catch (SftpException e) {
throw e;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
}
disconnect();
}
public void disconnect() {
if (this.sftp != null) {
if (this.sftp.isConnected()) {
this.sftp.disconnect();
this.sftp = null;
}
}
if (this.sshSession != null) {
if (this.sshSession.isConnected()) {
this.sshSession.disconnect();
this.sshSession = null;
}
}
}
}
(2)指定传输路径
package com.xinghan.keysystem.util.sftp;
public class SftpParam {
public static String OP_TK_PGP_FILE = "/input/key/";
public static String CARTIFICATE_FILE = "/input/PKI/";
public static String CSR_FILE = "/output/PKI/";
public static String PGP_KEY_FILE = "/output/key/pgp/";
public static String INPUT = "/input/";
public static String OUTPUT = "/output/";
}
标题3、配置文件加载协议信息,application.yml
##高安全区
sftpNameRoot: rdcenter
sftpPasswordRoot: Ftp666
sftpHost: 10.12.254.105
sftpPort: 22
4、调用方式
@Autowired
private SftpRootHelper sftpRootHelper;
@RequestMapping("/synchronization")
public void synchronization() throws Exception {
sftpRootHelper.connect();
String path = sftpRootHelper.downloadFileOPTK("/"+ordClientCert.getFtp()+ SftpParam.INPUT,ordClientCert.getCustomName(), ".csr",beas+ newPath,fileName + "p10");
sftpRootHelper.deleteFile("/"+ordClientCert.getFtp()+SftpParam.INPUT, path);
}