在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
    


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM