Calling shell commands and execute shell scripts in java

Calling shell commands and execute shell scripts in java

  1. Enter the command sudo bash script automatically

    man sudo

    -S The -S (stdin) option causes sudo to read the password from
    the standard input instead of the terminal device. The
    password must be followed by a newline character.

    Used as a standard input pipe

    echo "password" |sudo -S

    This would avoid an interactive shell, so that the application in the script.

  2. java call shell script

        public static String bashCommand(String command) {
            Process process = null;
            String stringBack = null;
            List<String> processList = new ArrayList<String>();
            try {
                process = Runtime.getRuntime().exec(command);
                BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
                String line = "";
                while ((line = input.readLine()) != null) {
                    processList.add(line);
                }
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            for (String line : processList) {
                stringBack += line;
                stringBack +="\n";
            }
            return stringBack;
        }

    But I found a problem, that is, if the project packaged into a jar package if (item is a desktop software), resources within the jar package can not be directly referenced externally, for example: if a script on the resource under, obtained by getResoures path, then perform "bash <the script path>" can not run, because the script file is in a jar. I think the solution is to be executed when the script first by getClass (). GetClassLoader (). GetResource ( ) .OpenStream (); obtain input stream, and then create a file, the original file is written script to a new file (the file at this time is outside the jar package) through the stream, and then perform a new file, deleted after execution .

    And make things happen one: some command in a shell there is indeed a return value, but always with the above function returns null, but then I thought of awkward, is to write a shell script, the command returns the value assignment to a variable, then this variable echo:

    #!/bin/bash
    ip=$(ifconfig | grep "inet 192*")
    echo $ip

Guess you like

Origin www.cnblogs.com/jiading/p/12317729.html