錯誤的方法:
//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(); }