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();
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM