Java 使用 jsch 上传远程服务器
Java jsch About 2,520 words添加依赖
新版本依赖
<dependency>
<groupId>com.github.mwiede</groupId>
<artifactId>jsch</artifactId>
<version>2.27.2</version>
</dependency>
老版本依赖
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
相关代码
说明:虽然新版本依赖名称都换掉了,但是代码包依然是com.jcraft.jsch。
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.OutputStream;
@Component
public class JschUtils {
@Value("${jsch.host}")
private String host;
@Value("${jsch.username}")
private String username;
@Value("${jsch.password}")
private String password;
@Value("${jsch.path}")
private String path;
public void upload(byte[] bytes, String filename) throws Exception {
JSch jsch = new JSch();
Session session = jsch.getSession(username, host);
if (session == null) {
throw new RuntimeException("无法连接远程服务器");
}
session.setPassword(password);
session.setConfig("userauth.gssapi-with-mic", "no");
session.setConfig("StrictHostKeyChecking", "no");
session.connect(30000);
Channel channel = session.openChannel("sftp");
channel.connect(1000);
ChannelSftp sftp = (ChannelSftp) channel;
sftp.cd(path);
try (OutputStream outputStream = sftp.put(filename)) {
outputStream.write(bytes);
} finally {
session.disconnect();
channel.disconnect();
}
}
public void delete(String filename) throws Exception {
JSch jsch = new JSch();
Session session = jsch.getSession(username, host);
if (session == null) {
throw new RuntimeException("无法连接远程服务器");
}
session.setPassword(password);
session.setConfig("userauth.gssapi-with-mic", "no");
session.setConfig("StrictHostKeyChecking", "no");
session.connect(30000);
Channel channel = session.openChannel("sftp");
channel.connect(1000);
ChannelSftp sftp = (ChannelSftp) channel;
sftp.cd(path);
try {
sftp.rm(filename);
} finally {
session.disconnect();
channel.disconnect();
}
}
}
开源地址
https://github.com/mwiede/jsch
代码示例
https://github.com/mwiede/jsch/blob/master/examples/Sftp.java
Views: 14 · Posted: 2026-01-10
———         Thanks for Reading         ———
Give me a Star, Thanks:)
https://github.com/fendoudebb/LiteNote扫描下方二维码关注公众号和小程序↓↓↓
Loading...