在java中调用shell命令和执行shell脚本

在java中调用shell命令和执行shell脚本

  1. bash脚本自动输入sudo命令

    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.

    使用管道作为标准输入

    echo "password" |sudo -S

    这样就能避免和shell交互,从而应用在脚本中了。

  2. java调用shell脚本

        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我发现了一个问题,就是如果将项目打包成jar包的话(项目是一个桌面软件),jar包内的资源不能直接被外部引用,例如:如果把一个脚本放在resource下,通过getResoures来获得path,然后执行“bash <该脚本的path> ”就无法运行,因为此时这个脚本文件是在jar包内的。我想到的解决办法就是要执行脚本时先通过getClass().getClassLoader().getResource( ).openStream();获得输入流,然后创建一个文件,将原脚本的文件通过流写入到新文件(此时这个文件是在jar包外的),然后执行新文件,执行完后删除掉。

    并且发生了一个使事情:有的命令在shell中确实是有返回值的,但是用上面的函数返回的却总是null,后来我想了个笨办法,就是写一个shell脚本,将命令返回值赋值给一个变量,再echo这个变量:

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

猜你喜欢

转载自www.cnblogs.com/jiading/p/12317729.html