
/** * 通过SSH连接到FE Leader节点执行grep命令检测Full GC日志 * * ssh.privateKey和ssh.publicKey环境执行命令 * ssh-keygen -t rsa -b 2048 -m PEM -f id_rsa生成 * * 公钥和私钥必须配对公钥提前需要追加到StarRocks集群的/root/.ssh/authorized_keys文件中才能实现免密登录 */ 公钥要提前添加到ECS上 chattr -i /root/.ssh/authorized_keys KEY AUTH/root/.ssh/authorized_keys if grep -qF -- $KEY $AUTH; then echo 已存在跳过追加: $AUTH else echo $KEY $AUTH echo 已追加到: $AUTH fipackage org.example; import com.jcraft.jsch.ChannelExec; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class App { public static void main(String[] args) { String user root; String host ; int port 22; try { JSch jsch new JSch(); // 直接提供私钥内容更安全不存储文件 String privateKey ; jsch.addIdentity(key-name, privateKey.getBytes(), null, null); Session session jsch.getSession(user, host, port); // 禁用密码认证强制使用密钥 //session.setConfig(PreferredAuthentications, publickey); session.setConfig(StrictHostKeyChecking, no); // 仅测试用生产环境应验证 session.connect(); System.out.println(Connected!); // 执行命令示例 ChannelExec channel (ChannelExec) session.openChannel(exec); channel.setCommand(cat /root/testSSH20260904.log); // 3. 获取命令输出流关键读取命令执行结果 InputStream inputStream channel.getInputStream(); // 启动通道执行命令 channel.connect(); // 4. 读取输出内容 BufferedReader reader new BufferedReader(new InputStreamReader(inputStream)); String line; StringBuilder output new StringBuilder(); System.out.println( 命令执行输出开始 ); while ((line reader.readLine()) ! null) { output.append(line).append(\n); System.out.println(line); // 实时打印每行输出 } System.out.println( 命令执行输出结束 ); // 5. 检查命令执行状态0成功非0失败 int exitStatus channel.getExitStatus(); if (exitStatus 0) { System.out.println(\n命令执行成功退出状态码 exitStatus); } else { System.err.println(\n命令执行失败退出状态码 exitStatus); // 读取错误输出如命令不存在、文件无权限等 InputStream errorStream channel.getErrStream(); BufferedReader errorReader new BufferedReader(new InputStreamReader(errorStream)); String errorLine; StringBuilder errorOutput new StringBuilder(); while ((errorLine errorReader.readLine()) ! null) { errorOutput.append(errorLine).append(\n); } System.err.println(错误信息 errorOutput); } channel.disconnect(); session.disconnect(); } catch (JSchException e) { e.printStackTrace(); } catch (IOException e) { throw new RuntimeException(e); } } }