执行系统命令

/**
     * 获得系统的CPU空闲率
     *
     * @return CPU空闲率
     */
    public static int getIdleCPU()
    {
        // 默认为100%
        int result = DEFAULTRESULT;
        // int FOUR = 4;
        // int SIX = 6;

        String command = BMEConfig.getDefaultConfig().getProperty(
                "cpu.command", CPUDEFAULTCOMMAND);

        if (null == CPU_COMMAND)
        {
            synchronized (LOCK)
            {
                if (null == CPU_COMMAND)
                {

                    CPU_COMMAND = getConfigCommand(command);
                }
            }
        }

        String temp = executeCMD(CPU_COMMAND);

        // 取最后一行的统计数据
        if (null == temp || temp.trim().length() == 0)
        {
            logger
                    .error("get CPU info fail with "
                            + "cmd '"
                            + command
                            + "' in SUSE,AIX or HP. System will use default value 100.");
            return result;
        }
        String[] resultStr = temp.split("##");
        temp = resultStr[resultStr.length - 1];

        String tempTitle = "";

        // 循环判断取出表头
        for (int i = 0; i < resultStr.length; i++)
        {
            if (resultStr[i].indexOf(IDLE) != -1)
            {
                tempTitle = resultStr[i];
                break;
            }
        }

        // 使用匹配任何空白字符,包括空格、制表符、换页符
        String[] splitStr = temp.split("\\s{2,}+");
        String[] splitTempTitle = tempTitle.split("\\s{2,}+");

        for (int i = 0; i < splitTempTitle.length; i++)
        {
            if (IDLE.equalsIgnoreCase(splitTempTitle[i]))
            {
                  //在AIX下,cpu空闲率为0的时候,会显出成“-”,所以此处对“-”进行特殊处理。
                    if("-".equals(splitStr[i]))
                    {
                        return 0;
                    }
                try
                {
                    result = Math.round(Float.parseFloat(splitStr[i]));
                }
                catch (NumberFormatException e)
                {
                    // not supported operation system.
                    logger.error("number format error", e);
                }
            }
        }
        // 不同的操作系统输出的统计数据顺序不一样,需要根据具体的操作系统类型进行获取
        // int osType = getOSType();
        // if (IBM_AIX_5 == osType || HP_IA64_UX_11 == osType)
        // {
        // if (splitStr.length >= FOUR)
        // {
        // try
        // {
        // result = Integer.parseInt(splitStr[FOUR]);
        // }
        // catch (NumberFormatException e)
        // {
        // // not supported operation system.
        // logger.error("number format error", e);
        // }
        // }
        // else
        // {
        // logger.error("get CPU info fail with "
        // + "cmd 'sar -u 2 2' in AIX or HP.");
        // }
        // }
        // else if (HW_ATAE_SUSE_LINUX_9 == osType)
        // {
        // if (splitStr.length >= SIX)
        // {
        // result = Math.round(Float.parseFloat(splitStr[SIX]));
        // }
        // else
        // {
        // logger.error("get CPU info fail with "
        // + "cmd 'sar -u 2 2' in SUSE.");
        // }
        // }
        return result;
    }

 

/**
     * 执行系统命令
     *
     * @param cmd
     *            命令字符串
     * @return 执行系统命令后的输出结果
     */
    public static String executeCMD(String[] cmd)
    {
        //fortify 白名单检测
        if (!checkCmd(cmd))
        {
            logger.error("cannot execute command:" + Arrays.toString(cmd)
                    + "due to this cmd is not in the white list");
            return "";
        }
       
        Process proc = null;
        BufferedReader read = null;
        StringBuffer sb = null;
        InputStreamReader inputStreamReader = null;
        try
        {
            proc = Runtime.getRuntime().exec(cmd);
            inputStreamReader = new InputStreamReader(proc.getInputStream());
            read = new BufferedReader(inputStreamReader);

            // 一般有多行执行结果输出,每行之间使用"##"来分隔
            String line = null;
            sb = new StringBuffer();
            while ((line = read.readLine()) != null)
            {
                sb.append(line);
                sb.append("##");
            }
        }
        catch (Exception e)
        {
            logger.error("Execute command failed.", e);
            // e.printStackTrace();
            return "";
        }
        finally
        {
            if (proc != null)
            {
                try
                {
                    proc.waitFor();
                }
                catch (Exception e)
                {
                    logger.error("Wait for failed.", e);
                }

                try
                {
                    proc.getInputStream().close();
                }
                catch (Exception e)
                {
                    logger.error("Get input stream failed.", e);
                }

                try
                {
                    proc.getOutputStream().close();
                }
                catch (Exception e)
                {
                    logger.error("Get output stream failed.", e);
                }

                try
                {
                    proc.getErrorStream().close();
                }
                catch (Exception e)
                {
                    logger.error("Get error stream failed.", e);
                }

                try
                {
                    proc.destroy();
                }
                catch (Exception e)
                {
                    logger.error("Destroy failed.", e);
                    // e.printStackTrace();
                }
            }
            if (read != null)
            {
                try
                {
                    read.close();

                }
                catch (Exception e)
                {
                    logger.error("Close read failed.", e);
                }
            }
            if (null != inputStreamReader)
            {

                try
                {
                    inputStreamReader.close();

                }
                catch (Exception e)
                {
                    logger.error("Close inputStreamReader failed.", e);
                }
            }
        }

        return sb.toString();
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值