Java使用sshj远程操作服务器
sshj地址: https://github.com/hierynomus/sshj
pom.xml引入sshj
<!--sshj-->
<dependency>
<groupId>com.hierynomus</groupId>
<artifactId>sshj</artifactId>
<version>0.37.0</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
远程执行命令和发送文件demo
package com.ssh.run.utlis;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.connection.channel.direct.Session;
import net.schmizz.sshj.sftp.SFTPClient;
import net.schmizz.sshj.transport.verification.PromiscuousVerifier;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
public class SSHConnectUtil {
public static void run(String ip, int port, String username, String password, String cmd) throws Exception {
// 创建SSH连接的代码
try (SSHClient sshClient = new SSHClient();) {
Session session = null;
Session.Command exec = null;
try {
sshClient.addHostKeyVerifier(new PromiscuousVerifier());
sshClient.connect(ip, port);
sshClient.authPassword(username, password);
sshClient.useCompression();
sshClient.setConnectTimeout(3000);
session = sshClient.startSession();
session.allocateDefaultPTY();
exec = session.exec(cmd);
// 执行命令
InputStream inputStream = exec.getInputStream();
System.out.println(ip + " 执行命令:" + cmd + "\n" + IOUtils.toString(inputStream, Charset.defaultCharset()));
exec.join();
} catch (IOException e) {
throw new RuntimeException(e);
}finally {
if (exec != null) {
exec.close();
}
if (session != null){
session.close();
}
}
}
}
public static void sftp(String ip, int port, String username, String password, String localPath, String remotePath) throws Exception {
try (SSHClient sshClient = new SSHClient();) {
SFTPClient sftpClient = null;
try {
sshClient.addHostKeyVerifier(new PromiscuousVerifier());
sshClient.connect(ip, port);
sshClient.authPassword(username, password);
sftpClient = sshClient.newSFTPClient();
sftpClient.put(localPath, remotePath);
} catch (IOException e) {
throw new RuntimeException(e);
}finally {
if (sftpClient != null) {
sftpClient.close();
}
}
}
}
}
测试远程执行命令
package com.ssh.run.service;
import com.ssh.run.utlis.SSHConnectUtil;
public class SSHTest {
public static void main(String[] args) throws Exception {
// 使用普通账户登录,然后使用root账户执行命令
SSHConnectUtil.run("192.168.229.128", 22, "zk", "123", "echo '123'|su - root -c \"ls -lh\"");
}
}
运行结果如下图:
测试文件上传至服务器
package com.ssh.run.service;
import com.ssh.run.utlis.SSHConnectUtil;
public class SSHTest {
public static void main(String[] args) throws Exception {
SSHConnectUtil.sftp("192.168.229.128",22, "zk", "123","C:\\Users\\datatech\\Downloads\\240228063042_0001.pdf", "/home/zk/");
SSHConnectUtil.run("192.168.229.128", 22, "zk", "123", "ls -lh /home/zk");
}
}
上传完成后,执行查看命令。
运行结果如下图: