简体   繁体   English

收集Linux命令输出

[英]Collect Linux command output

I am now on a linux machine. 我现在在Linux机器上。 I have a Java program which would run some linux command, for example ps , top , list or free -m . 我有一个Java程序,它将运行一些linux命令,例如pstoplistfree -m

The way to run a command in Java is as follows: 在Java中运行命令的方式如下:

Process p = Runtime.getRuntime().exec("free -m");

How could I collect the output by Java program? 如何收集Java程序的输出? I need to process the data in the output. 我需要处理输出中的数据。

Use Process.getInputStream() to get an InputStream that represents the stdout of the newly created process. 使用Process.getInputStream()获得一个InputStream ,它表示新创建的进程的标准输出。

Note that starting/running external processes from Java can be very tricky and has quite a few pitfalls. 请注意,从Java启动/运行外部进程可能非常棘手,并且有很多陷阱。

They are described in this excellent article , which also describes ways around them. 这篇出色的文章中对它们进行了描述, 该文章还描述了解决它们的方法。

To collect the output you could do something like 要收集输出,您可以执行以下操作

 Process p = Runtime.getRuntime().exec("my terminal command");

  p.waitFor();
  BufferedReader buf = new BufferedReader(new InputStreamReader(
          p.getInputStream()));
  String line = "";
  String output = "";

  while ((line = buf.readLine()) != null) {
    output += line + "\n";
  }

  System.out.println(output);

This would run your script and then collect the output from the script into a variable. 这将运行您的脚本,然后将脚本的输出收集到一个变量中。 The link in Joachim Sauer's answer has additional examples of doing this. Joachim Sauer的答案中的链接还提供了其他示例。

As for some command need to wait for a while, add p.waitFor(); 至于某些命令需要等待一段时间,请添加p.waitFor();。 if necessary. 如有必要。

public static void main(String[] args) {

        CommandLineHelper obj = new CommandLineHelper();
        String domainName = "google.com";
        //in mac oxs
        String command = "ping -c 3 " + domainName;
        String output = obj.executeCommand(command);
        System.out.println(output);

    }

private String executeCommand(String command) {

        StringBuffer output = new StringBuffer();

        Process p;
        try {

            p = Runtime.getRuntime().exec(command);

            p.waitFor();
            BufferedReader reader = 
                            new BufferedReader(new InputStreamReader(p.getInputStream()));

                        String line = "";           
            while ((line = reader.readLine())!= null) {
                output.append(line + "\n");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return output.toString();

    }

The technicalities of calling an external process are quite involved. 调用外部过程的技术非常复杂。 The jproc library helps abstracting over these by automatically consuming the output of the command and providing the result as a string. jproc库通过自动使用命令的输出并将结果作为字符串提供来帮助抽象这些内容。 The example above would be written like this: 上面的示例将这样写:

String result = ProcBuilder.run("free", "-m");

It also allows to set a timeout, so that your application isn't blocked by an external command that is not terminating. 它还允许设置超时,以便您的应用程序不会被未终止的外部命令阻止。

public String RunLinuxGrepCommand(String command) {
    String line = null;
    String strstatus = "";
    try {

        String[] cmd = { "/bin/sh", "-c", command };
        Process p = Runtime.getRuntime().exec(cmd);
        BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
        while ((line = in.readLine()) != null) {
            strstatus = line;
        }
        in.close();
    } catch (Exception e) {

        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        pw.flush();
        String stackTrace = sw.toString();
        int lenoferrorstr = stackTrace.length();
        if (lenoferrorstr > 500) {
            strstatus = "Error:" + stackTrace.substring(0, 500);
        } else {
            strstatus = "Error:" + stackTrace.substring(0, lenoferrorstr - 1);

        }
    }
    return strstatus;

}

This functioin will give result of any linux command 该功能将给出任何Linux命令的结果

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

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