官网:https://mina.apache.org/sshd-project/
GitHub:https://github.com/apache/mina-sshd
API JavaDocs:https://mina.apache.org/sshd-project/apidocs/index.html
<!-- 这个依赖可以不添加,因为下面的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();
}