【问题标题】:How do I run the Linux command, “netstat” from a Java program?如何从 Java 程序运行 Linux 命令“netstat”?
【发布时间】:2020-02-04 21:47:27
【问题描述】:

我有一个用 Java 编写的客户端-服务器项目,它们通过套接字连接。我无法弄清楚如何从我的 Java 代码的服务器端运行“netstat”。

【问题讨论】:

标签: java linux server-side serversocket


【解决方案1】:

不幸的是,java 中没有直接可用的 netstat 等效项。

您可以使用进程 API 生成一个新进程并检查输出。

我将使用以下 q/a 中的示例:https://stackoverflow.com/a/5711150/1688441

我已将其更改为调用netstat。生成进程后,您还必须读取输出并对其进行解析。

Runtime rt = Runtime.getRuntime();
String[] commands = {"netstat", ""};
Process proc = rt.exec(commands);

BufferedReader stdInput = new BufferedReader(new 
     InputStreamReader(proc.getInputStream()));

BufferedReader stdError = new BufferedReader(new 
     InputStreamReader(proc.getErrorStream()));

// Read the output from the command
System.out.println("Here is the standard output of the command:\n");
String s = null;
while ((s = stdInput.readLine()) != null) {
    System.out.println(s);
}

// Read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
    System.out.println(s);
}

来源:https://stackoverflow.com/a/5711150/1688441

【讨论】:

  • 这在一般情况下不起作用。您要么需要合并流,要么在单独的线程中同时读取它们。
  • @user207421 你是对的!只要进程在运行第一个while循环就会阻塞另一个。我会更新这个。
猜你喜欢
  • 2011-04-11
  • 2013-07-22
  • 2020-07-06
  • 1970-01-01
  • 2012-08-27
  • 2012-04-10
  • 2013-01-14
  • 2012-07-20
  • 1970-01-01
相关资源
最近更新 更多