繁体   English   中英

如何从 Java 程序运行 Linux 命令“netstat”?

[英]How do I run the Linux command, “netstat” from a Java program?

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

不幸的是,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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM