Java利用JSch进行SFTP进行SSH连接远程服务器进行目录创建与上传文件,ChannelSftp
Maven依赖
<dependency>
<groupId>com.github.mwiede</groupId>
<artifactId>jsch</artifactId>
<version>0.2.23</version>
</dependency>
测试代码
public void sftpTest() {
Session session = null;
//打开SFTP通道
ChannelSftp channel = null;
try {
JSch jsch = new JSch();
session = jsch.getSession("root", "zym.test.com", 29620);
session.setPassword("V6LbAzgKrD5q");//远程密码
session.setConfig("StrictHostKeyChecking", "no"); // 禁用严格主机密钥检查
session.connect();
//打开SFTP通道
channel = (ChannelSftp) session.openChannel("sftp");
channel.connect();
//查看服务器当前目录内容
Vector<ChannelSftp.LsEntry> entries = channel.ls("/root/autodl-tmp/ComfyUI/input");
System.out.println("entries = " + entries);
String remotePath = "/root/autodl-tmp/ComfyUI/input/video";
//上传前目录video目录内容查看
Vector<ChannelSftp.LsEntry> beforeDir = channel.ls(remotePath);
System.out.println("beforeDir = " + beforeDir);
//远程目录创建,如存在则忽略
mkDirs(channel, remotePath);
//将本地视频上传到远程服务
channel.put("C:\\Users\\EDY\\Desktop\\11月21日-1.mp4", remotePath + "/11月21日-1.mp4", ChannelSftp.OVERWRITE);
//上传后目录查看
Vector<ChannelSftp.LsEntry> afterDir = channel.ls(remotePath);
System.out.println("afterDir = " + afterDir);
} catch (JSchException | SftpException e) {
e.printStackTrace();
} finally {
if (channel != null) channel.disconnect();//关闭通道
if (session != null) session.disconnect();//关闭会话
}
}
/**
* 创建目录
*
* @param channel 打开的SFTP通道
* @param path 路径格式例如:/root/autodl-tmp/ComfyUI/input/video
*/
private void mkDirs(ChannelSftp channel, String path) throws SftpException {
String[] dirs = path.split("/");
StringBuilder currentPath = new StringBuilder();
for (String dir : dirs) {
if (dir.isEmpty()) continue; // 处理路径开头为"/"的情况
currentPath.append("/").append(dir);
try {
channel.lstat(currentPath.toString()); // 检查目录是否存在
} catch (SftpException e) {
if (e.id == ChannelSftp.SSH_FX_NO_SUCH_FILE) {
channel.mkdir(currentPath.toString()); //创建不存在的层级目录
}
}
}
}
运行效果
1、/root/autodl-tmp/ComfyUI/input目录内容的查看
2、上传前查看目录内容
3、上传后查看目录内容