pom依赖
ch.ethz.ganymed ganymed-ssh2 262
工具类
package com.ruoyi.system.common.utils;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
public class SSHToolUtil {
private Connection conn;
private String ipAddr;
private Charset charset = StandardCharsets.UTF_8;
private String userName;
private String password;
public SSHToolUtil(String ipAddr, String userName, String password) {
this.ipAddr = ipAddr;
this.userName = userName;
this.password = password;
if (charset != null) {
this.charset = charset;
}
}
private boolean login() {
conn = new Connection(ipAddr);
try {
// System.out.println("登录");
// 连接
conn.connect();
// 认证
return conn.authenticateWithPassword(userName, password);
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public StringBuilder exec(String cmds) throws IOException {
InputStream in = null;
StringBuilder result = new StringBuilder();
try {
if (this.login()) {
// System.out.println("333");
// 打开一个会话
Session session = conn.openSession();
session.execCommand(cmds);
in = session.getStdout();
result = this.processStdout(in, this.charset);
conn.close();
}
} finally {
if (null != in) {
in.close();
}
}
return result;
}
public StringBuilder processStdout(InputStream in, Charset charset) throws FileNotFoundException {
byte[] buf = new byte[1024];
StringBuilder sb = new StringBuilder();
// OutputStream os = new FileOutputStream("./data.txt");
try {
int length;
while ((length = in.read(buf)) != -1) {
// os.write(buf, 0, c);
sb.append(new String(buf, 0, length));
}
} catch (IOException e) {
e.printStackTrace();
}
return sb;
}
}
简单调用
SSHToolUtil sshToolUtil = new SSHToolUtil(url, user, pass); List



