How to execute shell command in Java?

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

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 at Advance!

+4
source share
1 answer

Not a very friendly question to Stackoverflow, since I'm not sure if you are asking about running Shell or ipconfig commands in general.

If the first case is here: Yes, you can use Runtime.getRuntime.exec(). Related answers (in Stackoverflow):

  1. Running shell commands from Java
  2. Want to invoke a Linux shell command from Java

, , , , "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");
}

, , 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;

ProcessBuilder, : Oracle ProcessBuilder

+14

Source: https://habr.com/ru/post/1538261/


All Articles