当前位置: 首页 > 工具软件 > Apache SSHD > 使用案例 >

使用 Apache sshd sftp 上传文件

宗政燕七
2023-12-01

添加依赖

<dependency>
    <groupId>org.apache.sshd</groupId>
    <artifactId>sshd-core</artifactId>
    <version>2.5.1</version>
</dependency>

<dependency>
    <groupId>org.apache.sshd</groupId>
    <artifactId>sshd-sftp</artifactId>
    <version>2.5.1</version>
</dependency>

使用 SftpFileSystem 来上传文件

try(SshClient client = SshClient.setUpDefaultClient()) {
    client.start();
    try(ClientSession session = client.connect("root", "30.0.0.111", 22).verify().getSession()) {
        session.addPasswordIdentity("123456");
        session.auth().verify();

        try(SftpFileSystem fs = SftpClientFactory.instance().createSftpFileSystem(session)){
            Path remote = fs.getDefaultDir().resolve("/opt/a/bc/test");
            Files.createDirectories(remote); // 创建多层目录
            Files.copy(Paths.get("D:\\test.txt"), remote.resolve("test.txt")); // 将目标文件拷贝至目标目录
        } catch (Exception e) {
            e.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
} catch (Exception e) {
    e.printStackTrace();
}

使用 SftpFileSystem ,可以借助 Files 来操作远程文件。

使用 SftpClient 来上传文件

try(SshClient client = SshClient.setUpDefaultClient()) {
   client.start();
   try(ClientSession session = client.connect("root", "30.0.0.111", 22).verify().getSession()) {
       session.addPasswordIdentity("123456");
       session.auth().verify();

       try(SftpClient sftp = SftpClientFactory.instance().createSftpClient(session)){
           sftp.mkdir("/opt/test");
           SftpClient.CloseableHandle handle = sftp.open("/opt/test/test.txt", SftpClient.OpenMode.Write, SftpClient.OpenMode.Create);
           FileInputStream in = new FileInputStream("D:\\test.txt");
           int buff_size = 1024*1024;
           byte[] src = new byte[buff_size];
           int len;
           long fileOffset = 0L;
           while ((len = in.read(src)) != -1) {
               sftp.write(handle, fileOffset, src, 0, len);
               fileOffset += len;
           }
       } catch (Exception e) {
           e.printStackTrace();
       }
   } catch (Exception e) {
       e.printStackTrace();
   }
} catch (Exception e) {
   e.printStackTrace();
}
 类似资料: