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

JAVA:使用apache sshd库往sftp服务器上传文件

鞠通
2023-12-01

官网:https://mina.apache.org/sshd-project/

GitHub:https://github.com/apache/mina-sshd

API JavaDocs:https://mina.apache.org/sshd-project/apidocs/index.html

maven依赖

<!-- 这个依赖可以不添加,因为下面的sftp依赖会自动下载本依赖 -->
<!-- https://mvnrepository.com/artifact/org.apache.sshd/sshd-core -->
<dependency>
  <groupId>org.apache.sshd</groupId>
  <artifactId>sshd-core</artifactId>
  <version>2.3.0</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.sshd/sshd-sftp -->
<dependency>
    <groupId>org.apache.sshd</groupId>
    <artifactId>sshd-sftp</artifactId>
    <version>2.3.0</version>
</dependency>

采用<用户名+密码>方式的上传代码

import java.io.FileInputStream;
import java.io.IOException;
import java.util.EnumSet;

import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.session.ClientSession;
import org.apache.sshd.client.subsystem.sftp.SftpClient;
import org.apache.sshd.client.subsystem.sftp.SftpClientFactory;

public void uploadSFTP(String localPath, String remotePath) throws IOException {
  SshClient client = SshClient.setUpDefaultClient();
  client.start();
  ClientSession session = client.connect("user", "10.10.20.20", 22).verify().getSession();
  session.addPasswordIdentity("password");
  session.auth().verify();

  SftpClientFactory factory = SftpClientFactory.instance();
  SftpClient sftp = factory.createSftpClient(session);

  SftpClient.CloseableHandle handle = sftp.open(remotePath,
      EnumSet.of(SftpClient.OpenMode.Write, SftpClient.OpenMode.Create));
  FileInputStream in = new FileInputStream(localPath);
  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;
  }

  in.close();
  sftp.close(handle);

  session.close(false);
  client.stop();
}
 类似资料: