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