ch.ethz.ganymed
ganymed-ssh2
262
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;
import java.io.*;
import java.util.Locale;
/**
* @className: ExecUtil
* @desc: SSH远程指令执行
* @author: wan.tao
* @date: 2023-09-22
* @Version 1.0
*/
@Slf4j
@Component
public class SshExecUtil {
/**
* 消费异常处理器
* @return
*/
public static Connection getConnection(String host,String username,String password) {
Connection conn = null;
try {
conn = new Connection(host);
conn.connect();
if (!conn.authenticateWithPassword(username, password)) {
throw new RuntimeException("用户名或密码错误!");
}
}catch (Exception e){
e.printStackTrace();
}
return conn;
}
/**
* 执行远程linux命令行
* @param cmd
* @return
* @throws IOException
*/
public static String remoteExec(String cmd,String host,String username,String password) throws IOException {
//登录,获取连接
Connection conn = getConnection(host,username,password);
Session session = null;
BufferedReader br = null;
InputStream is = null;
StringBuffer res = new StringBuffer();
try {
// 开启会话
session = conn.openSession();
// 执行命令
session.execCommand(cmd, "UTF-8");
// 处理输出内容
is = new StreamGobbler(session.getStdout());
br = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = br.readLine()) != null) {
res.append(line+"\r\n");
}
} finally {
//关闭资源
try {
if (is != null) {
is.close();
}
if (br != null) {
br.close();
}
if (session != null) {
session.close();
}
if (conn != null) {
conn.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return res.toString();
}
/**
* 执行本机linux命令行,与ganymed-ssh2依赖无关,JDK自带功能
*/
public static String exec(String command) {
String osName = System.getProperty("os.name");
try {
/*系统命令不支持的操作系统Windows XP, 2000 2003 7 8 9 10 11*/
if (osName.toLowerCase(Locale.ROOT).indexOf("win") != -1) {
throw new RuntimeException("不支持的操作系统:" + osName);
}
Runtime rt = Runtime.getRuntime();
Process process = rt.exec(command);
LineNumberReader br = new LineNumberReader(
new InputStreamReader(
process.getInputStream()));
StringBuffer sb = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
return sb.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public class Test{
@Test
public void test1() throws IOException {
String s = SshExecUtil .remoteExec("ifconfig", "192.168.1.10", "root", "root");
System.out.println(s);
}
}
其他真的很简单QAQ!
github
http://127.0.0.1:8888/132d042c-3b1a-4c45-9044-b7897c3de788