如何在Java中执行shell命令?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23322740/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 21:54:25  来源:igfitidea点击:

How to execute shell command in Java?

javashell

提问by hdraven

I was thinking if I could send a shell to execute Client-Server ipconfig. Is that possible?

我在想是否可以发送一个 shell 来执行 Client-Server ipconfig。那可能吗?

This is my code in Local:

这是我在本地的代码:

class Comando {
    public static void main(String args[]) {

        String s = null;

        try {

            // Determinar en qué SO estamos
            String so = System.getProperty("os.name");
            String comando;
            // Comando para Linux
            if (so.equals("Linux"))
                comando = "ifconfig";
            // Comando para Windows
            else
                comando = "ipconfig";

            // Ejcutamos el comando
            Process p = Runtime.getRuntime().exec(comando);

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

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

            // Leemos la salida del comando
            System.out.println("ésta es la salida standard del comando:\n");
            while ((s = stdInput.readLine()) != null) {
                System.out.println(s);
            }

            // Leemos los errores si los hubiera
            System.out
                    .println("ésta es la salida standard de error del comando (si la hay):\n");
            while ((s = stdError.readLine()) != null) {
                System.out.println(s);
            }

            System.exit(0);
        } catch (IOException e) {
            System.out.println("Excepción: ");
            e.printStackTrace();
            System.exit(-1);
        }
    }
}

Thank You in Advance!

先感谢您!

采纳答案by ambodi

Not a very Stackoverflow friendly question, since I am not sure if you are asking about Shell command execution, or ipconfig in general.

不是一个非常适合 Stackoverflow 的问题,因为我不确定您是在询问 Shell 命令执行还是一般的 ipconfig。

If the first is the case here: Yep, you can use Runtime.getRuntime.exec(). Related Answers (In Stackoverflow):

如果这里是第一种情况:是的,您可以使用Runtime.getRuntime.exec(). 相关答案(在 Stackoverflow 中):

  1. Executing shell commands from Java
  2. Want to invoke a linux shell command from Java
  1. 从 Java 执行 shell 命令
  2. 想要从 Java 调用 linux shell 命令

Moreover to the answers provided there, here is my example on how you do it with "host -t a" command for DNS lookups. I would generally recommend to read through the list you get and append them in an String for logging purposes.

除了那里提供的答案之外,这里是我的示例,说明如何使用“host -t a”命令进行 DNS 查找。我通常建议通读您获得的列表并将它们附加到字符串中以进行记录。

p = Runtime.getRuntime().exec("host -t a " + domain);
p.waitFor();

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

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

The other solution which herausuggested was to use ProcessBuilderand execute the command from there. For this you need to use Java SE 7 upwards. Here is an example that starts a process with a modified working directory and environment, and redirects standard output and error to be appended to a log file:

herau建议的另一个解决方案是ProcessBuilder从那里使用和执行命令。为此,您需要向上使用 Java SE 7。这是一个示例,该示例使用修改后的工作目录和环境启动进程,并将标准输出和错误重定向到附加到日志文件中:

 ProcessBuilder pb =
   new ProcessBuilder("myCommand", "myArg1", "myArg2");
 Map<String, String> env = pb.environment();
 env.put("VAR1", "myValue");
 env.remove("OTHERVAR");
 env.put("VAR2", env.get("VAR1") + "suffix");
 pb.directory(new File("myDir"));
 File log = new File("log");
 pb.redirectErrorStream(true);
 pb.redirectOutput(Redirect.appendTo(log));
 Process p = pb.start();
 assert pb.redirectInput() == Redirect.PIPE;
 assert pb.redirectOutput().file() == log;
 assert p.getInputStream().read() == -1;

If you wanna know more about ProcessBuilder, read through the documentation: Oracle Documentation on Class ProcessBuilder

如果您想了解有关 ProcessBuilder 的更多信息,请通读文档:Oracle 类 ProcessBuilder 文档