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

錯誤的方法:

//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();
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章