maven
<!-- https://mvnrepository.com/artifact/org.apache.sshd/sshd-common -->
<dependency>
<groupId>org.apache.sshd</groupId>
<artifactId>sshd-common</artifactId>
<version>2.7.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.sshd/sshd-core -->
<dependency>
<groupId>org.apache.sshd</groupId>
<artifactId>sshd-core</artifactId>
<version>2.7.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.sshd/sshd-scp -->
<dependency>
<groupId>org.apache.sshd</groupId>
<artifactId>sshd-scp</artifactId>
<version>2.7.0</version>
</dependency>
ScpUtil
import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.session.ClientSession;
import org.apache.sshd.scp.client.ScpClient;
import org.apache.sshd.scp.client.ScpClientCreator;
/**
* @author Miracle Luna
* @date 2021/7/19
*/
public class ScpUtil {
public static void scpFile(String localFile, String remoteFile, String host, Integer port,
String username, String password) throws Exception {
long startTime = System.currentTimeMillis();
// 创建 SSH客户端
SshClient client = SshClient.setUpDefaultClient();
// 启动 SSH客户端
client.start();
// 通过主机IP、端口和用户名,连接主机,获取Session
ClientSession session = client.connect(username, host, port).verify().getSession();
// 给Session添加密码
session.addPasswordIdentity(password);
// 校验用户名和密码的有效性
boolean isSuccess = session.auth().verify().isSuccess();
// 认证成功
if (isSuccess) {
long middleTime = System.currentTimeMillis();
System.out.println("连接成功,耗时: " + (middleTime - startTime) / 1000.0 + "秒。");
ScpClientCreator creator = ScpClientCreator.instance();
// 创建 SCP 客户端
ScpClient scpClient = creator.createScpClient(session);
// 添加 ScpClient.Option.Recursive 参数为上传文件夹
scpClient.upload(localFile, remoteFile);
// 释放 SCP客户端
if (scpClient != null) {
scpClient = null;
}
// 关闭 Session
if (session != null && session.isOpen()) {
session.close();
}
// 关闭 SSH客户端
if (client != null && client.isOpen()) {
client.stop();
client.close();
}
} else {
System.err.println("认证失败");
return;
}
long endTime = System.currentTimeMillis();
System.out.println("总耗时 : " + (endTime - startTime) / 1000.0 + "秒。");
}
public static void main(String[] args) throws Exception {
scpFile("/home/测试.md", "/root/测试2.md",
"1.2.3.4", 22, "root", "123");
}
}