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