java Runtime.getRuntime().exec 調用系統指令碼/命令注意事項

來源:互聯網
上載者:User

錯誤的方法:

//CPUID
private static final String cpuid="dmidecode -t processor | grep 'ID' | head -1";

Process p = Runtime.getRuntime().exec(puid);

原因:不會被再次解析,管道符失效

 

正確的辦法:

linux下:

String[] command = { "/bin/sh", "-c", (puid };

Process ps = Runtime.getRuntime().exec(command );

windows下:

String[] command = { "cmd", "/c", (puid };

Process ps = Runtime.getRuntime().exec(command );

 

 

 

linux還有一種方法:

命令【ehco】就是向標準輸出裝置輸出引號中的內容。這裡將使用管道命令”|“將【echo】命令的輸出作為【openssl】命令的輸入。

在Java程式中調用Shell命令

    /**     * 資料加密處理     *      * @param data 要加密的資料     * @param commonKey 加密口令檔案名稱     * @return 加密資料     */    public static final synchronized String encryption(String data, String commonKey){        // 加密後的資料定義        String encryptionData = "";                    try {            // 加密命令            String encryption = "echo -E \"{0}\" | openssl aes-128-cbc -e -kfile {1} -base64";                        // 替換命令中預留位置            encryption = MessageFormat.format(encryption, data, commonKey);                        String[] sh = new String[]{"/bin/sh", "-c", encryption};                        // Execute Shell Command            ProcessBuilder pb = new ProcessBuilder(sh);                        Process p = pb.start();                        encryptionData = getShellOut(p);        } catch (Exception e) {            throw new EncryptionException(e);        }                return encryptionData;    }

在Java程式中捕獲Shell命令的輸出資料流,並讀取加密資料

    /**     * 讀取輸出資料流資料     *      * @param p 進程     * @return 從輸出資料流中讀取的資料     * @throws IOException     */    public static final String getShellOut(Process p) throws IOException{                StringBuilder sb = new StringBuilder();        BufferedInputStream in = null;        BufferedReader br = null;                try {                        in = new BufferedInputStream(p.getInputStream());            br = new BufferedReader(new InputStreamReader(in));            String s;                        while ((s = br.readLine()) != null) {                // 追加分行符號                sb.append(ConstantUtil.LINE_SEPARATOR);                                sb.append(s);            }                    } catch (IOException e) {            throw e;        } finally {            br.close();            in.close();        }                return sb.toString();    }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.