在centos 7上测试了一下,比较简单粗暴.代码如下
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
/**
* Created by nicholas on 11/19/2016.
*/
public class GetProcessInfo {
private static final String[] SHELL = {"sh", "-c", "lsof -Pnl +M -i4 | grep sshd"};
private static final String KEY = "(LISTEN)";
private static String runCommand(String[] shell) throws IOException, InterruptedException {
String result = "";
Process pos = Runtime.getRuntime().exec(shell);
pos.waitFor();
InputStreamReader ir = new InputStreamReader(pos.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
String ln = "";
while ((ln = input.readLine()) != null) {
String temp = ln.toString();
if (temp.contains(KEY)) {
result = temp;
}
}
input.close();
ir.close();
return result;
}
public static int getPort() throws IOException, InterruptedException {
String result = runCommand(SHELL);
if ("".equals(result)) {
System.out.println("get sshd services fail....");
return 0;
}
String[] split = result.split(":")[1].split(" ");
int port = Integer.valueOf(split[0]);
return port;
}
public static void main(String[] args) throws IOException, InterruptedException {
System.out.println("sshd port = " + getPort());
}
}