admin管理员组

文章数量:1530018

引入pom

<dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.46</version> <!-- 请根据实际情况检查最新版本 -->
        </dependency>


import cn.hncht.plug.core.exception.DefaultException; //自己定义异常
import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;


import java.io.*;
import java.math.BigDecimal;
import java.util.*;


@Slf4j
public class LinuxServerInfo {

    public static void main(String[] args) {
        String host = "服务器ip";
        int port = 22;
        String username = "服务器账号";
        String password = "服务器密码";

        try {
            // 创建JSch对象
            JSch jsch = new JSch();
            // 创建会话
            Session session = jsch.getSession(username, host, port);
            session.setConfig("StrictHostKeyChecking", "no");
            session.setPassword(password);
            // 连接
            try {
                session.connect();
            }catch (Exception e){
                throw new DefaultException("连接失败!");
            }
            // 获取服务器信息
//            String serverName = executeCommand(session, "hostname");
//            String memoryUsage = executeCommand(session, "free | awk 'NR==2 {print $3/$2*100}'");
            String diskUsage = executeCommand(session, "df -h | awk '$NF==\"/\"{print $5}'");
            double jvmUsage = getJVMUsage();
            String jvmUsageStr = String.format("%.0f", jvmUsage)  + "%";
            Map<String,Object> getMemoryRate=getMemoryRate(session);
            String cpuUsage = cpuUsage(session);
            Map<String,Object> getdisk=getDisk(session);
            Map<String,Object> netUsage=getNetworkDownUp(session);
            // 打印结果
//            System.out.println("Server Name: " + serverName);
//            System.out.println("Internal IP: " + internalIP);
            System.out.println("CPU Usage: " + cpuUsage + "%");
//            System.out.println("Memory Usage: " + memoryUsage + "%");
            System.out.println("Disk Usage: " + diskUsage);
            System.out.println("JVM Usage: " + jvmUsageStr);
            System.out.println("getMemoryRate: " + getMemoryRate.toString());
            System.out.println("getdisk: " + getdisk.toString());
            System.out.println("netUsage: " + netUsage.toString());

            // 关闭会话
            session.disconnect();

        } catch (JSchException e) {
            e.printStackTrace();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static Map<String,Object> getServerDiskAndMemory(String ip,String userName,String pwd) throws JSchException {
        // 创建JSch对象
        JSch jsch = new JSch();
        // 创建会话
        Session session = jsch.getSession(userName, ip, 22);
        session.setConfig("StrictHostKeyChecking", "no");
        session.setPassword(pwd);
        // 连接
        try {
            session.connect();
        }catch (Exception e){
            throw new DefaultException("连接失败!");
        }
        Map<String,Object> getdisk=getDisk(session);
        Map<String,Object> getMemoryRate=getMemoryRate(session);
        Map<String,Object> map=new HashMap<>();
        long disk=0l;
        if(getdisk.get("vda1Map")!=null){
            Map<String,Object> vad1= (Map<String, Object>) getdisk.get("vda1Map");
            long vad1Disk= Long.parseLong(String.valueOf(vad1.get("vda1-size")).replace("G","")) ;
            disk=disk+vad1Disk;
        }
        if(getdisk.get("vdb1Map")!=null){
            Map<String,Object> vad1= (Map<String, Object>) getdisk.get("vdb1Map");
            long vdb1Disk= Long.parseLong(String.valueOf(vad1.get("vdb1-size")).replace("G",""));
            disk=disk+vdb1Disk;
        }
        String memory= String.valueOf(getMemoryRate.get("allMemory")) ;
        map.put("disk",disk+"G");
        map.put("memory",memory);
        return map;
    }


    // 执行Shell命令并获取输出
    public static String executeCommand(Session session, String command) throws JSchException {
        StringBuilder output = new StringBuilder();
        try {
            // 创建通道
            Channel channel = session.openChannel("exec");
            ((ChannelExec) channel).setCommand(command);
            // 获取输入流
            InputStream inputStream = channel.getInputStream();
            // 连接通道
            channel.connect();
            // 读取命令输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = reader.readLine()) != null) {
                output.append(line).append("\n");
            }
            // 关闭通道
            channel.disconnect();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return output.toString().trim();
    }

    // 获取JVM使用率
    public static double getJVMUsage() {
        Runtime runtime = Runtime.getRuntime();
        double totalMemory = runtime.totalMemory();
        double freeMemory = runtime.freeMemory();
        double maxMemory = runtime.maxMemory();
        double jvmUsage = ((totalMemory - freeMemory) / maxMemory) * 100;
        return jvmUsage;
    }


    // 执行Shell命令并获取输出
    public static List<String> executeCommandList(Session session, String command) throws JSchException {
        StringBuilder output = new StringBuilder();
        List<String> logContent = new ArrayList<String>();
        try {
            // 创建通道
            Channel channel = session.openChannel("exec");
            ((ChannelExec) channel).setCommand(command);
            // 获取输入流
            InputStream inputStream = channel.getInputStream();
            // 连接通道
            channel.connect();
            // 读取命令输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            while (true) {
                String line = null;
                try {
                    line = reader.readLine();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (line == null) {
                    break;
                }
                logContent.add(line);
            }
            // 关闭通道
            channel.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return logContent;
    }


    /**
     * 获取服务器内存
     * @param session
     * @return
     * @throws JSchException
     */
    public static Map<String,Object> getMemoryRate(Session session) throws JSchException {
        String shell = String.format("%s", "free"); // 多个命令用“;”隔开
        Map<String,Object> map=new HashMap<>();
        List<String> listResult = executeCommandList(session,shell);
        // 打印shell命令执行后的结果
        for (int i = 0; i < listResult.size(); i++) {
            System.out.println(listResult.get(i));
        }
        // 提取内存数据(第二行)
        List<String> mem = Arrays.asList(listResult.get(1).split("\\s+"));
        Integer usedMemory = Integer.valueOf(mem.get(2));
        Integer allMemory = Integer.valueOf(mem.get(1));
        System.out.println(String.format("usedMemory=%s;allMemory=%s", usedMemory, allMemory));

        // 计算内存使用率(已使用内存/总内存)
        BigDecimal rounded = new BigDecimal((float) usedMemory / allMemory).setScale(2, BigDecimal.ROUND_HALF_UP);
        System.out.println(String.format("内存使用率=%s%s", rounded.multiply(new BigDecimal(100)), "%"));
        map.put("usedMemory",usedMemory / 1024 / 1024);
        map.put("allMemory",allMemory / 1024 / 1024);
        map.put("memoryUsage",String.format("%s%s",  rounded.multiply(new BigDecimal(100)), "%"));
        return map;
    }

    /**
     * 获取服务器百分比
     * @param session
     * @return
     * @throws JSchException
     */
    public static String cpuUsage(Session session) throws JSchException {
        String a=executeCommand(session, "top -bn1 | grep 'Cpu(s)' | awk '{print $2 + $4}'");
        return a;
    }

    /**
     * 获取硬盘
     * @param session
     * @return
     * @throws JSchException
     */
    public static Map<String,Object> getDisk(Session session) throws JSchException {
        String shell = String.format("%s", "df -h"); // 多个命令用“;”隔开
        Map<String,Object> map=new HashMap<>();
        List<String> listResult = executeCommandList(session,shell);
        String vda1=null;
        String vdb1=null;
        // 打印shell命令执行后的结果
        for (int i = 0; i < listResult.size(); i++) {
            System.out.println(listResult.get(i));
            if(listResult.get(i).contains("/dev/vda1")){
                vda1=listResult.get(i);
            }
            if(listResult.get(i).contains("/dev/vdb1")){
                vdb1=listResult.get(i);
            }
        }
        List<String> vda1List=new ArrayList<>();
        List<String> vdb1List=new ArrayList<>();
        if(vda1!=null){
            vda1List= Arrays.asList(vda1.split("\\s+"));
        }
        if(vdb1!=null){
            vdb1List= Arrays.asList(vdb1.split("\\s+"));
        }
        if(vda1List.size()>0){
            Map<String,Object> vda1Map=new HashMap<>();
            vda1Map.put("vda1-size",vda1List.get(1));
            vda1Map.put("vda1-used",vda1List.get(2));
            vda1Map.put("vda1-use",vda1List.get(4));
            map.put("vda1Map",vda1Map);
        }else {
            map.put("vda1Map",null);
        }
        if(vdb1List.size()>0){
            Map<String,Object> vdb1Map=new HashMap<>();
            vdb1Map.put("vdb1-size",vdb1List.get(1));
            vdb1Map.put("vdb1-used",vdb1List.get(2));
            vdb1Map.put("vdb1-use",vdb1List.get(4));
            map.put("vdb1Map",vdb1Map);
        }else {
            map.put("vdb1Map",null);
        }
        return map;
    }

    /**
     * 获取带宽上行下行
     * @param session
     * @return
     * @throws Exception
     */
    public static long[] readInLine(Session session) throws Exception {
        Map<String,Object> map=new HashMap<>();
        String rxPercent = "";
        String txPercent = "";
        long arr[] = new long[2];
        String shell = String.format("%s", "ifconfig"); // 多个命令用“;”隔开
        Channel channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(shell);
        // 获取输入流
        InputStream inputStream = channel.getInputStream();
        // 连接通道
        channel.connect();
        // 读取命令输出
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        long rx = 0, tx = 0;
        String line = null;
        //RX packets:4171603 errors:0 dropped:0 overruns:0 frame:0
        //TX packets:4171603 errors:0 dropped:0 overruns:0 carrier:0
        while ((line = reader.readLine()) != null) {
            if (line.indexOf("RX packets") >= 0) {
                rx += Long.parseLong(line.substring(line.indexOf("RX packets") + 11, line.indexOf(" ", line.indexOf("RX packets") + 11)));
            } else if (line.indexOf("TX packets") >= 0) {
                tx += Long.parseLong(line.substring(line.indexOf("TX packets") + 11, line.indexOf(" ", line.indexOf("TX packets") + 11)));
            }
        }
        arr[0] = rx;
        arr[1] = tx;
        return arr;
    }

    public static Map<String, Object> getNetworkDownUp(Session session) throws Exception {
        Map<String, Object> result = new HashMap<>();
        String rxPercent = "";
        String txPercent = "";
        long result1[] = readInLine(session);
        Thread.sleep(1000);
        long result2[] = readInLine(session);
        // 上行速率(kB/s)
        rxPercent = formatNumber((result2[0] - result1[0]) / (1024.0 * (1000 / 1000)));
        // 下行速率(kB/s)
        txPercent = formatNumber((result2[1] - result1[1]) / (1024.0 * (1000 / 1000)));
        result.put("rxPercent", rxPercent);
        // 上行速率
        result.put("txPercent", txPercent);
        return result;
    }


    public static String formatNumber(double f) {
        return new Formatter().format("%.2f", f).toString();
    }


}


本文标签: 服务器基本信息带宽内存硬盘