所需jar包:
ganymed-ssh2-build210.jar
下载地址:
https://mvnrepository.com/artifact/ch.ethz.ganymed/ganymed-ssh2/262
获取远程登录连接:
private static RemoteShellTool remoteShellTool = new RemoteShellTool("172.xxx.xxx.xxx", 62222, "root", "xxxxx", "utf-8");
RemoteShellTool相关代码如下:
package szsti.gasstation.utils; import ch.ethz.ssh2.Connection; import ch.ethz.ssh2.Session; import org.apache.commons.lang.StringUtils; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Date; import java.util.List; public class RemoteShellTool { private Connection conn; private String ipAddr; private int port; private String charset = Charset.defaultCharset().toString(); private String userName; private String password; public RemoteShellTool(String ipAddr, int port, String userName, String password, String charset) { this.ipAddr = ipAddr; this.userName = userName; this.password = password; this.port = port; if (charset != null) { this.charset = charset; } } public boolean login() throws IOException { conn = new Connection(ipAddr, port); conn.connect(); // 连接 boolean res_con=conn.authenticateWithPassword(userName, password); return res_con; // 认证 } public void close() throws IOException { conn.close(); // 断开连接 } /** * * @param cmds * @param isOpen 为null时是查询pid,关闭进程命令,执行完命令去读结果,不为空时是开启,执行完命令直接关闭 * @return */ public String exec(String cmds, String isOpen) { InputStream in = null; String result = ""; try { if (this.login()) { Session session = conn.openSession(); // 打开一个会话 session.requestPTY("bash"); session.execCommand(cmds); in = session.getStdout(); if (StringUtils.isBlank(isOpen)) { result = this.processStdout(in, this.charset); }else{ try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } } session.close(); conn.close(); } } catch (IOException e1) { e1.printStackTrace(); } return result; } public String processStdout(InputStream in, String charset) { byte[] buf = new byte[1024]; StringBuffer sb = new StringBuffer(); try { while (in.read(buf) != -1) { sb.append(new String(buf, charset)); } } catch (IOException e) { e.printStackTrace(); } return sb.toString(); } }
根据传入的进程名通过cmds命令,远程执行,获取相应的返回值:
public static List<String> getPidLinuxCmd(String processName) { String cmd = "ps -ef|grep " + processName + " | grep -v grep"; String result = remoteShellTool.exec(cmd, null); String[] arrs = result.split("\n"); List<String> pids = new ArrayList<>(); for (int i = 0; i < arrs.length - 1; i++) { String thatPid = arrs[i].split("\\s+")[1]; if ("-f".equals(thatPid)) { break; } pids.add(thatPid); } return pids; }
以上示例为根据进程名,获取相应的pid序列号.