日韩黑丝制服一区视频播放|日韩欧美人妻丝袜视频在线观看|九九影院一级蜜桃|亚洲中文在线导航|青草草视频在线观看|婷婷五月色伊人网站|日本一区二区在线|国产AV一二三四区毛片|正在播放久草视频|亚洲色图精品一区

分享

【Java】+獲取Linux服務(wù)器的CPU、內(nèi)存使用率

 三十的狼 2020-08-06
復(fù)制代碼
package com.alipay.ipay.gn.commontool;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import com.alipay.ipay.gn.commontool.file.ZgxFileUtil;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.log4j.Logger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;


/**
 * @author 
 * @version 1.0
 * @time 2019/7/15 20:28
 * <p>
 * 類功能說明:
 * 1、連接服務(wù)器
 * 2、執(zhí)行Linux日志查詢命令,返回查詢后的日志字符串(以行為單位)
 */
public class LogAuto {
    private static Logger log;
    private Session ssh;
    private String hostName;
    private String userName;
    private String password;
    private int port;

    /**
     * 連接服務(wù)器
     *
     * @param hostname 服務(wù)器IP
     * @param port     端口
     * @param username 賬號(hào)
     * @param password 密碼
     */
    public LogAuto(String hostname, int port, String username, String password) {
        this.hostName = hostname;
        this.port = port;
        this.userName = username;
        this.password = password;
        this.log = ZgxLoggerUtil.getLoger(LogAuto.class);
    }

    /**
     * 通過Linux命令查詢?nèi)罩緝?nèi)容
     *
     * @param command Linux日志查詢命令
     * @return 返回根據(jù)命令查出的日志內(nèi)容
     */
    public List<String> execCom(String command) {
        Connection conn = new Connection(this.hostName, this.port);
        createConnection(conn);
        List<String> logContent = new ArrayList<String>();
        try {
            ssh.execCommand(command);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //將Terminal屏幕上的文字全部打印出來
        InputStream is = new StreamGobbler(ssh.getStdout());
        BufferedReader brs = new BufferedReader(new InputStreamReader(is));
        while (true) {
            String line = null;
            try {
                line = brs.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (line == null) {
                break;
            }
//            System.out.println(line);
            logContent.add(line);
        }

        return logContent;
    }

    private void createConnection(Connection connection) {
        //創(chuàng)建連接
        try {
            connection.connect();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            connection.authenticateWithPassword(this.userName, this.password);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //創(chuàng)建與服務(wù)器的會(huì)話節(jié)點(diǎn)
        try {
            setSsh(connection.openSession());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void setSsh(Session ssh) {
        this.ssh = ssh;
    }

    private Session getSsh() {
        return ssh;
    }

    /**
     * 功能:獲取指定服務(wù)器在當(dāng)前時(shí)間的內(nèi)存使用率
     *
     * @param logAuto
     * @return 返回使用率(百分比)
     */
    public static double getMemoryRate(LogAuto logAuto) {
        String shell = String.format("%s", "free"); // 多個(gè)命令用“;”隔開
        List<String> listResult = logAuto.execCom(shell);
        // 打印shell命令執(zhí)行后的結(jié)果
        for (int i = 0; i < listResult.size(); i++) {
            System.out.println(listResult.get(i));
        }

        // 提取內(nèi)存數(shù)據(jù)(第二行)
        List<String> mem = ZgxStringUtil.splitString(listResult.get(1), " ");
        Integer usedMemory = Integer.valueOf(mem.get(2));
        Integer allMemory = Integer.valueOf(mem.get(1));
        log.info(String.format("usedMemory=%s;allMemory=%s", usedMemory, allMemory));

        // 計(jì)算內(nèi)存使用率(已使用內(nèi)存/總內(nèi)存)
        double f1 = new BigDecimal((float) usedMemory / allMemory).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() * 100;
        log.info(String.format("內(nèi)存使用率=%s%s", f1, "%"));
        return f1;
    }

    private static Pair getCpuData(LogAuto logAuto) {
        String shell = String.format("%s", "cat /proc/stat"); // 多個(gè)命令用“;”隔開
        List<String> listResult = logAuto.execCom(shell);
        // 打印shell命令執(zhí)行后的結(jié)果
        for (int i = 0; i < listResult.size(); i++) {
            System.out.println(listResult.get(i));
        }

        // 提取CPU數(shù)據(jù)(第一行)
        List<String> mem = ZgxStringUtil.splitString(listResult.get(0), " ");
        mem.remove(0);
        Long allTime1 = 0L;
        for (int i = 0; i < mem.size(); i++) {
            allTime1 += Long.valueOf(mem.get(i));
        }
        System.out.println(String.format("CPU使用總時(shí)間=%s;idle=%s", allTime1, mem.get(3)));

        return Pair.of(allTime1, mem.get(3));
    }

    /**
     * 功能:獲取指定服務(wù)器在當(dāng)前時(shí)間的CPU使用率
     *
     * @param logAuto
     * @return 返回使用率(百分比)
     */
    public static double getCpuRate(LogAuto logAuto) {
        Pair cpuData1 = getCpuData(logAuto);
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Pair cpuData2 = getCpuData(logAuto);

        // step1 計(jì)算兩次的cpu總時(shí)間
        Long allTime = Long.valueOf(cpuData2.getLeft().toString()) - Long.valueOf(cpuData1.getLeft().toString());
        // step2 計(jì)算兩次的cpu剩余時(shí)間
        Long idle = Long.valueOf(cpuData2.getRight().toString()) - Long.valueOf(cpuData1.getRight().toString());
        // step3 計(jì)算兩次的cpu使用時(shí)間
        Long used = allTime - idle;
        // step4 計(jì)算cpu使用率(cpu使用率 = 使用時(shí)間 / 總時(shí)間 * 100%)
        double f1 = new BigDecimal((float) used / allTime).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() * 100;
        log.info(String.format("CPU使用率=%s%s", f1, "%"));

        return f1;
    }

    public static void main(String[] args) {
        LogAuto logAuto = new LogAuto("服務(wù)器IP", 端口號(hào), "賬號(hào)", "密碼");
        getMemoryRate(logAuto);
        getCpuRate(logAuto);

        String[] header = {"時(shí)間,CPU使用率,內(nèi)存使用率"};
        List<String[]> content = new ArrayList<>();
        // 每分鐘獲取一次服務(wù)器CPU、內(nèi)存使用率(獲取30次)
        for (int i = 0; i < 30; i++) {
            String[] data = {ZgxDateUtil.getNowDate("yyyy-MM-dd HH:mm:ss")
                    , String.valueOf(getCpuRate(logAuto))
                    , String.valueOf(getMemoryRate(logAuto))};
            content.add(data);
            ZgxFileUtil.writeCsv("服務(wù)器性能數(shù)據(jù).csv", header, content);
            try {
                Thread.sleep(1000 * 60);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
復(fù)制代碼

    本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評(píng)論

    發(fā)表

    請(qǐng)遵守用戶 評(píng)論公約

    類似文章 更多