国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計(jì) > 正文

Java 啟動windows服務(wù)、進(jìn)程,查看某一進(jìn)程、服務(wù)的cpu使用量

2019-11-14 23:55:05
字體:
供稿:網(wǎng)友
java 啟動windows服務(wù)、進(jìn)程,查看某一進(jìn)程、服務(wù)的cpu使用量

  這幾天在做一個模塊,使用Java關(guān)閉重啟Windows Server 2008上的服務(wù)。開始使用的是j-interop。后來leader說,這玩意不行。ms已經(jīng)去掉了administrator的特權(quán),要使用這玩意就需要用setacl.exe對注冊表修改,這exe包,打不開,看不到里面的東西,用起來心慌慌的。

  后面么,發(fā)現(xiàn)當(dāng)你一超級管理員登陸時(shí),windows上打開的cmd能直接運(yùn)行關(guān)閉啟動服務(wù)的命令。就來個曲線救國吧,好在不要求遠(yuǎn)程啟動服務(wù),不然又是一番好忙。

  廢話到此結(jié)束。

  前提條件是,你隨意打開cmd,上面顯示的是“管理員”,如下圖所示,否則,還是有些功能不能實(shí)現(xiàn)。

   代碼如下:

public class WmiServiceUtils {    public static final Logger logger = LoggerFactory.getLogger(WmiServiceUtils.class);    PRivate static List<Map<String, Object>> getAllResult(String[] cmdStr, int flag) throws IOException {        List<Map<String, Object>> list = new ArrayList<>();        Integer index = 1;        Process p = null;        String str = null;        String[] arrStr = new String[2];        Map<String, Object> map = new HashMap<String, Object>();        InputStreamReader isr = null;        BufferedReader br = null;        try {            p = Runtime.getRuntime().exec(cmdStr);            isr = new InputStreamReader(p.getInputStream());            br = new BufferedReader(isr);            while ((str = br.readLine()) != null) {                if (StringUtil.isNotEmpty(str)) {                    if (index % flag == 0) {                        list.add(map);                        map = new HashMap<String, Object>();                    }                    arrStr = str.split("=");                    str = str.endsWith("=") ? "" : arrStr[1];                    map.put(arrStr[0], str);                    index++;                }            }        } catch (IOException e) {            logger.error("獲取進(jìn)程的所有信息失敗!", e);            throw e;        } catch (Exception e) {            logger.error("獲取執(zhí)行結(jié)果失敗!", e);            throw e;        } finally {            try {                if (br != null) {                }                br.close();                if (isr != null) {                    isr.close();                }            } catch (IOException e) {                logger.error("", e);            }            if (p != null) {                p.destroy();            }        }        return list;    }    @SuppressWarnings("unused")    private static String parse2Time(long milliseconds) {        if (milliseconds == 0) {            return "0秒";        }        if (milliseconds / 1000 == 0) {            return "0." + milliseconds + "秒";        }        milliseconds = milliseconds / 1000;        long day = milliseconds / (24 * 3600);        milliseconds = milliseconds % (24 * 3600);        if (milliseconds == 0) {            return day + "天";        }        long hour = milliseconds / (3600);        milliseconds = milliseconds % (3600);        if (milliseconds == 0) {            return day + "天" + hour + "小時(shí)";        }        long minute = milliseconds / (60);        milliseconds = milliseconds % (60);        if (milliseconds == 0) {            return day + "天 " + hour + "小時(shí) " + minute + "分鐘";        } else {            return day + "天 " + hour + "小時(shí) " + minute + "分鐘 " + milliseconds + "秒";        }    }    private static Map<String, Object> printStream(InputStream input) throws IOException { //InputStream input  final Process proc        InputStreamReader isr = new InputStreamReader(input); //proc.getInputStream()        BufferedReader br = new BufferedReader(isr);        Map<String, Object> map = new HashMap<String, Object>();        String str = null;        String[] arrStr = null;        try {            while ((str = br.readLine()) != null) {                if (StringUtil.isNotEmpty(str)) {                    if (str.contains("=")) {                        arrStr = str.split("=");                        str = str.endsWith("=") ? "" : arrStr[1];                        map.put(arrStr[0], str);                    } else {                        map.put(str, null);                    }                }            }        } catch (IOException e) {            logger.error("關(guān)閉文件流失敗!", e);            throw e;        } finally {            try {                if (br != null) {                    br.close();                }                if (isr != null) {                    isr.close();                }                if (input != null) {                    input.close();                }            } catch (IOException e) {                logger.error("關(guān)閉文件流失敗!", e);                throw e;            }        }        return map;    }    private static String printErrorStream(InputStream input) throws IOException {        InputStreamReader reader = new InputStreamReader(input);        BufferedReader br = new BufferedReader(reader);        String msg = "";        String str = "";        try {            while ((str = br.readLine()) != null) {                if (StringUtil.isNotEmpty(str)) {                    msg += str + ",";                }            }            if(msg.endsWith(",")){                msg.substring(0, msg.lastIndexOf(","));            }            return msg;        } catch (IOException e) {            logger.error("讀取錯誤信息失敗!", e);            throw e;        } finally {            try {                if (br != null) {                    br.close();                }                if (reader != null) {                    reader.close();                }                if (input != null) {                    input.close();                }            } catch (IOException e) {                logger.error("關(guān)閉文件流失敗!", e);                throw e;            }        }    }    private static Map<String, Object> execCommand(String[] cmdStr) throws IOException {        Process p = null;        Map<String, Object> map = new HashMap<>();        try {            p = Runtime.getRuntime().exec(cmdStr);            logger.info("執(zhí)行錯誤信息: " + printErrorStream(p.getErrorStream()));            map = printStream(p.getInputStream());        } catch (IOException e) {            logger.error("啟動服務(wù)失敗!", e);            throw e;        } catch (Exception e) {            logger.error("獲取執(zhí)行結(jié)果失敗!", e);            throw e;        } finally {            if (p != null) {                p.destroy();            }        }        return map;    }    /**     * 啟動服務(wù)     * @param serviceName 右鍵 指定服務(wù)項(xiàng)-》屬性 -》服務(wù)名稱     * @return     * @throws IOException      */    public static Map<String, Object> startService(String serviceName) throws IOException {        String[] cmdStr = { "cmd", "/C", " net start " + serviceName };//runAs /user:Administrator        logger.info(Arrays.toString(cmdStr));        try {            return execCommand(cmdStr);        } catch (IOException e) {            logger.error("開啟服務(wù)失敗!", e);            throw e;        }    }    /**     * 關(guān)閉服務(wù)     * @param serviceName 右鍵 指定服務(wù)項(xiàng)-》屬性 -》服務(wù)名稱     * @return     * @throws IOException      */    public static Map<String, Object> stopService(String serviceName) throws IOException {        String[] cmdStr = { "cmd", "/C", "net stop " + serviceName };//runAs /user:Administrator         logger.info(Arrays.toString(cmdStr));        try {            return execCommand(cmdStr);        } catch (IOException e) {            logger.error("關(guān)閉服務(wù)失敗!", e);            throw e;        }    }    /**     * 禁用服務(wù)     * @param serviceName     * @return     * @throws IOException      */    public static Map<String, Object> disableService(String serviceName) throws IOException {        String[] cmdStr = { "cmd", "/C", "sc config " + serviceName + " start= disabled" };//runAs /user:Administrator         logger.info(Arrays.toString(cmdStr));        try {            return execCommand(cmdStr);        } catch (IOException e) {            logger.error("關(guān)閉服務(wù)失敗!", e);            throw e;        }    }    /**     * 啟用服務(wù) --自動     * @param serviceName     * @return     * @throws IOException      */    public static Map<String, Object> enableService(String serviceName) throws IOException {        String[] cmdStr = { "cmd", "/C", "sc config " + serviceName + " start= auto" };//runAs /user:Administrator         logger.info(Arrays.toString(cmdStr));        try {            return execCommand(cmdStr);        } catch (IOException e) {            logger.error("關(guān)閉服務(wù)失敗!", e);            throw e;        }    }    /**     * 啟用服務(wù) --手動     * @param serviceName     * @return     * @throws IOException      */    public static Map<String, Object> demandService(String serviceName) throws IOException {        String[] cmdStr = { "cmd", "/C", "sc config " + serviceName + " start= demand" };//runAs /user:Administrator         logger.info(Arrays.toString(cmdStr));        try {            return execCommand(cmdStr);        } catch (IOException e) {            logger.error("關(guān)閉服務(wù)失敗!", e);            throw e;        }    }    /**     *      * @param serviceName 映像名稱  XXXX.exe     * @return     * @throws IOException      */    public static Map<String, Object> getTaskDetail(String taskName) throws IOException {        String[] cmdStr = { "cmd", "/C", "wmic process where name='" + taskName + "' list full" };        logger.info(Arrays.toString(cmdStr));        try {            return execCommand(cmdStr);        } catch (IOException e) {            logger.error("關(guān)閉服務(wù)失敗!", e);            throw e;        }    }    /**     *      * @param processId PID     * @return     * @throws IOException      */    public static Map<String, Object> getTaskDetail(Integer processId) throws IOException {        String[] cmdStr = { "cmd", "/C", "wmic process where processid='" + processId + "' list full" };// get /format:value        logger.info(Arrays.toString(cmdStr));        try {            return execCommand(cmdStr);        } catch (IOException e) {            logger.error("關(guān)閉服務(wù)失敗!", e);            throw e;        }    }    public static List<Map<String, Object>> getAllTaskDetail() throws IOException {        String[] cmdStr = { "cmd", "/C", "wmic process get /value" };        logger.info(Arrays.toString(cmdStr));        List<Map<String, Object>> list = null;        try {            list = getAllResult(cmdStr, 45);        } catch (IOException e) {            logger.error("獲取所有進(jìn)程信息失敗!", e);            throw e;        }        return list;    }    public static List<Map<String, Object>> getAllService() throws IOException {        String[] cmdStr = { "cmd", "/C", "wmic service get /value" };        logger.info(Arrays.toString(cmdStr));        List<Map<String, Object>> list = null;        try {            list = getAllResult(cmdStr, 25);        } catch (IOException e) {            logger.error("獲取所有服務(wù)信息失敗!", e);            throw e;        }        return list;    }    /**     *      * @param serviceName 右鍵 指定服務(wù)項(xiàng)-》屬性 -》服務(wù)名稱     * @return     * @throws IOException      */    public static Map<String, Object> getServiceDetail(String serviceName) throws IOException {        String[] cmdStr = { "cmd", "/C", "wmic service where name='" + serviceName + "' list full" };        logger.info(Arrays.toString(cmdStr));        try {            return execCommand(cmdStr);        } catch (IOException e) {            logger.error("關(guān)閉服務(wù)失敗!", e);            throw e;        }    }    /**     *      * @param processId PID     * @return     * @throws IOException      */    public static Map<String, Object> getServiceDetail(Integer processId) throws IOException {        String[] cmdStr = { "cmd", "/C", "wmic service where processid='" + processId + "' list full" };        logger.info(Arrays.toString(cmdStr));        try {            return execCommand(cmdStr);        } catch (IOException e) {            logger.error("關(guān)閉服務(wù)失敗!", e);            throw e;        }    }    public static Map<String, Object> createProcess(String taskpath) throws IOException {        String[] cmdStr = { "cmd", "/C", "wmic process call create'" + taskpath + "'" };        try {            return execCommand(cmdStr);        } catch (IOException e) {            logger.error("關(guān)閉服務(wù)失敗!", e);            throw e;        }    }    public static Map<String, Object> deleteProcess(String taskname) throws IOException {        String[] cmdStr = { "cmd", "/C", " wmic process where name='" + taskname + "' delete" };//runAs /user:Administrator        try {            return execCommand(cmdStr);        } catch (IOException e) {            logger.error("關(guān)閉服務(wù)失敗!", e);            throw e;        }    }    /**     * 計(jì)算某進(jìn)程cpu使用率     * @param processName     * @return     * @throws Exception     * @see sysTime:表示該時(shí)間段內(nèi)總的CPU時(shí)間=CPU處于用戶態(tài)和內(nèi)核態(tài)CPU時(shí)間的總和,即sysTime =kerneTimel + userTime(注:這里并不包括idleTime,因?yàn)楫?dāng)CPU處于空閑狀態(tài)時(shí),實(shí)在內(nèi)核模式下運(yùn)行System Idle Process這個進(jìn)程,所以kernelTime實(shí)際上已經(jīng)包含了idleTime);            idleTime:表示在該時(shí)間段內(nèi)CPU處于空閑狀態(tài)的時(shí)間;CPU% = 1 – idleTime / sysTime * 100      */    public static String getCpuRatioForWindows(String processName) throws Exception {        String[] cmdStr = { "cmd", "/C",                "wmic process get Caption,CommandLine,KernelModeTime,ReadOperationCount,ThreadCount,UserModeTime,WriteOperationCount /value" };        try {            List<Map<String, Object>> list1 = getAllResult(cmdStr, 7);            long[] data1 = getCpuTime(list1, processName);            Thread.sleep(1000);            List<Map<String, Object>> list2 = getAllResult(cmdStr, 7);// get(p.getInputStream());            long[] data2 = getCpuTime(list2, processName);            long proctime = data2[2] - data1[2];            long totaltime = data2[1] - data1[1]; // + data2[0] - data1[0]            if(totaltime==0){                return "0%";            }            return Double.valueOf(10000 * proctime * 1.0 / totaltime).intValue()/100.00 + "%";        } catch (Exception e) {            logger.error("獲取CPU占用率失敗!", e);            throw e;        }    }    private static long[] getCpuTime(List<Map<String, Object>> list, String processName) {        long[] data = new long[3];        long idletime = 0;        long kneltime = 0;        long usertime = 0;        long processTime = 0;        String caption = "";        String kmtm = "";        String umtm = "";        for (Map<String, Object> m : list) {            caption = m.get("Caption").toString();            kmtm = m.get("KernelModeTime").toString();            umtm = m.get("UserModeTime").toString();            if (caption.equals("System Idle Process") || caption.equals("System")) {                if (kmtm != null && !kmtm.equals("")) {                    idletime += Long.parseLong(kmtm);                }                if (umtm != null && !umtm.equals("")) {                    idletime += Long.parseLong(umtm);                }            }            if (caption.equals(processName)) {                if (kmtm != null && !kmtm.equals("")) {                    processTime += Long.parseLong(kmtm);                }                if (umtm != null && !umtm.equals("")) {                    processTime += Long.parseLong(umtm);                }            }            if (kmtm != null && !kmtm.equals("")) {                kneltime += Long.parseLong(kmtm);            }            if (umtm != null && !umtm.equals("")) {                usertime += Long.parseLong(umtm);            }        }        data[0] = idletime;        data[1] = kneltime + usertime;        data[2] = processTime;        return data;    }

就這么點(diǎn),這么簡單,完全不需要解釋。

  當(dāng)時(shí)查資料的時(shí)候,借閱了網(wǎng)上眾多大神的博客,論壇什么的,如果其中有內(nèi)容侵犯了你的權(quán)益,請及時(shí)與我聯(lián)系。


發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 浦北县| 明星| 兰西县| 永寿县| 巨野县| 晋城| 四子王旗| 昌吉市| 芦山县| 丽江市| 上饶县| 澄城县| 获嘉县| 昌乐县| 崇文区| 九寨沟县| 商丘市| 达尔| 甘孜| 丰城市| 尚志市| 百色市| 平远县| 镇平县| 汉沽区| 丰原市| 浑源县| 大渡口区| 平邑县| 凤台县| 宝兴县| 泰安市| 景宁| 彭山县| 宁远县| 乃东县| 宁陵县| 荆州市| 海淀区| 三河市| 平阳县|