一:pom.xml
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
二:工具方法
@Slf4j
@Component("prototype")
public class SftpService {
private ChannelSftp sftp;
private Session session;
public void upload(String host, int port, String username, String password, String privateKey, String dir, String fileName) {
try {
login(host, port, username, password, privateKey);
upload(dir, fileName);
logout();
} catch (Exception e) {
log.error("upload error", e);
}
}
public void upload(String dir, String fileName) throws SftpException {
try {
sftp.cd(dir);
} catch (SftpException e) {
sftp.mkdir(dir);
sftp.cd(dir);
}
sftp.put(fileName, dir);
log.info("sftp upload success dir={}, fileName={}", dir, fileName);
}
public void download(String host, int port, String username, String password, String privateKey,
String remotePath, String remoteFileName, String localPath, String localFileName) {
boolean success = false;
try {
login(host, port, username, password, privateKey);
sftp.get(remotePath + remoteFileName, localPath + localFileName);
logout();
success = true;
} catch (Exception e) {
log.error("download error", e);
}
}
private void login(String host, int port, String username, String password, String privateKey) throws JSchException {
JSch jSch = new JSch();
if (privateKey != null) {
jSch.addIdentity(privateKey);
}
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session = jSch.getSession(username, host, port);
session.setConfig(config);
if (password != null) {
session.setPassword(password);
}
session.connect();
log.info("session connected: host={}, port={}, username={}", host, port, username);
sftp = (ChannelSftp)session.openChannel("sftp");
sftp.connect();
log.info("sftp channel connected: host={}, port={}, username={}", host, port, username);
}
private void logout() {
if (sftp != null && sftp.isConnected()) {
sftp.disconnect();
log.info("channelSftp disconnect", sftp);
}
if (session != null && session.isConnected()) {
session.disconnect();
log.info("session disconnect", session);
}
}
}