java代码实现liunx服务器(cpu、mem(内存)、jvm、堆/非堆、磁盘、服务器、java虚拟机)监控

废话不多说 直接贴代码。。。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;
import java.lang.management.OperatingSystemMXBean;
import java.lang.management.RuntimeMXBean;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class ServerStateUtils {

    private static final Log logger = LogFactory.getLog(ServerStateUtils.class);
    // cpu、mem(物理内存)、swap(交换分区)命令
    public static final String CPU_MEM_SWAP_SHELL = "top -b -n 1";
    // 系统磁盘命令
    public static final String FILES_SHELL = "df -hl";
    public static final String[] COMMANDS = { CPU_MEM_SWAP_SHELL, FILES_SHELL };
    // liunx 行分隔符
    public static final String LINE_SEPARATOR = System.getProperty("line.separator");

    /**
     * 获取服务器相关信息 cpu、内存、服务器信息、java虚拟机信息、堆/非堆
     * 
     * @return
     */
    public static Map<String, Map<String, String>> getServerStateInfo() {
        String osName = System.getProperty("os.name");
        if (osName.toLowerCase().startsWith("linux")) {
            return disposeResultMessage();
        }
        return null;
    }

    /**
     * 直接在本地执行 shell
     * 
     * @param commands
     *            执行的脚本
     * @return 执行结果信息
     */
    private static Map<String, String> runLocalShell(String[] commands) {
        Runtime runtime = Runtime.getRuntime();
        Map<String, String> map = new HashMap<>();
        StringBuilder stringBuffer;
        BufferedReader reader = null;
        Process process;
        try {
            for (String command : commands) {
                stringBuffer = new StringBuilder();
                process = runtime.exec(command);
                InputStream inputStream = process.getInputStream();
                reader = new BufferedReader(new InputStreamReader(inputStream));
                String buf;
                while ((buf = reader.readLine()) != null) {
                    // 舍弃PID 进程信息
                    if (buf.contains("PID")) {
                        break;
                    }
                    stringBuffer.append(buf.trim()).append(LINE_SEPARATOR);
                }
                // 每个命令存储自己返回数据-用于后续对返回数据进行处理
                map.put(command, stringBuffer.toString());
            }
        } catch (IOException e) {
            logger.error("获取liunx服务器基本信息异常:" + e.getMessage());
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                logger.error("获取liunx服务器基本信息过程中读取流关闭异常:" + e.getMessage());
            }
        }
        return map;
    }

    /**
     * 处理 shell 返回的信息
     * 
     * 具体处理过程以服务器返回数据格式为准 不同的Linux 版本返回信息格式不同
     *
     * @param result
     *            shell 返回的信息
     * @return 最终处理后的信息
     */
    private static Map<String, Map<String, String>> disposeResultMessage() {
        Map<String, String> result = runLocalShell(COMMANDS);
        if (result == null || result.size() < 1) {
            return null;
        }
        Map<String, Map<String, String>> resultMap = new HashMap<>();
        for (String command : COMMANDS) {
            String commandResult = result.get(command);
            if (null == commandResult) {
                continue;
            }
            if (CPU_MEM_SWAP_SHELL.equals(command)) {
                String[] strings = commandResult.split(LINE_SEPARATOR);
                for (String line : strings) {
                    Map<String, String> map = new HashMap<>();
                    // 转大写处理
                    line = line.toUpperCase();
                    line = line.replaceAll("\\s+", "");
                    if (line.contains("CPU(S):")) {
                        logger.info("cpu:"+line);
                        // cpu数据结果格式化:Cpu(s): 0.0%us, 0.0%sy, 0.0%ni,100.0%id, 0.0%wa, 0.0%hi, 0.0%si,0.0%st
                        //用户空间占用CPU百分比,内核空间占用CPU百分比,户进程空间内改变过优先级的进程占用CPU百分比,空闲CPU百分比
                        //等待输入输出的CPU时间百分比,等待输入输出的CPU时间百分比,硬件中断,软件中断,实时
                        List<String> keysList = new ArrayList<>();
                        keysList.add("US");
                        keysList.add("SY");
                        keysList.add("NI");
                        keysList.add("ID");
                        keysList.add("WA");
                        keysList.add("HI");
                        keysList.add("SI");
                        keysList.add("ST");
                        String[] cpus = line.split(":")[1].split(",");
                        for (String value : cpus) {
                            for (int i = 0; i < keysList.size(); i++) {
                                String itemKey = keysList.get(i);
                                if(!value.contains(itemKey))continue;
                                String new_value = value.replace(itemKey, "").trim();
                                String keyLower = itemKey.toLowerCase();
                                map.put(keyLower, new_value);
                            }
                        }
                        map.put("count", Integer.toString(Runtime.getRuntime().availableProcessors()));
                        resultMap.put("cpu", map);
                    } else if (line.contains("MEM:")) {
                        logger.info("mem/swap:" + line);
                        // mem数据结果格式化:Mem: 32826948k total, 1360332k used, 31466616k free, 135952k
                        // 内存总计
                        String mem = line.split(":")[1].replaceAll("\\.", ",");
                        String[] mems = mem.split(",");
                        List<String> keysList = new ArrayList<>();
                        keysList.add("TOTAL");
                        keysList.add("USED");
                        keysList.add("FREE");
                        keysList.add("BUFFERS");
                        keysList.add("BUFF/CACHE");
                        for (String value : mems) {
                            for (int i = 0; i < keysList.size(); i++) {
                                String itemKey = keysList.get(i);
                                if(!value.contains(itemKey))continue;
                                String new_value = value.replace(itemKey, "").trim();
                                if (!new_value.contains("k")) new_value = new_value + "k";
                                String keyLower = itemKey.toLowerCase();
                                String new_value_unit = disposeUnit(new_value);
                                if(keyLower.contains("buffers") || keyLower.contains("buff/cache")) {
                                    map.put("buffers", new_value_unit);
                                }else {
                                    map.put(keyLower, new_value_unit);
                                }
                            }
                        }
                        resultMap.put("mem", map);
                    }
                }
            } else if (FILES_SHELL.equals(command)) {
                logger.info("disk:" + commandResult);
                String[] strings = commandResult.split(LINE_SEPARATOR);
                BigDecimal size = new BigDecimal(0);
                BigDecimal used = new BigDecimal(0);
                for (int i = 0; i < strings.length - 1; i++) {
                    if (i == 0)
                        continue;
                    String ss = strings[i].replaceAll("\\s+", ",");
                    String[] strs = ss.split(",");
                    if (strs.length == 1)
                        continue;
                    size = size.add(disposeUnitConvertG(strs[1]));
                    used = used.add(disposeUnitConvertG(strs[2]));
                }
                Map<String, String> map = new HashMap<>();
                // 磁盘总大小
                map.put("total", disposeUnit(size + "g"));
                // 磁盘已使用
                map.put("used", disposeUnit(used + "g"));
                // 磁盘空闲
                map.put("free", disposeUnit((size.subtract(used)) + "g"));
                resultMap.put("disk", map);
            }
        }
        // ===================jvm================

        Runtime jvm = Runtime.getRuntime();
        Map<String, String> map = new HashMap<>();
        // jvm 可以使用的总内存 以字节(B)为单位
        String total = String.valueOf(jvm.totalMemory()/1024);
        if (!total.contains("k"))
            total = total + "k";
        map.put("total", disposeUnit(total));
        // jvm 空闲的内存
        String free = String.valueOf(jvm.freeMemory()/1024);
        if (!free.contains("k"))
            free = free + "k";
        map.put("free", disposeUnit(free));
        // jvm 已使用的内存
        String used = String.valueOf((jvm.totalMemory() - jvm.freeMemory())/1024);
        if (!used.contains("k"))
            used = used + "k";
        map.put("used", disposeUnit(used));
        logger.info("jvm:" + map.toString());
        resultMap.put("jvm", map);

        // ===================system================
        map = new HashMap<>();
        OperatingSystemMXBean system = ManagementFactory.getOperatingSystemMXBean();
        // 操作系统类型
        map.put("type", system.getName());
        // 操作系统架构
        map.put("arch", system.getArch());
        // 操作系统版本
        map.put("version", system.getVersion());
        // 服务器名称
        String hostname = "localhost.unknow";
        try {
            hostname = InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException e) {
            logger.error("获取服务器名称异常:"+e.getMessage());
        }
        map.put("name", hostname);
        map.put("ip", getLinuxLocalIp());
        resultMap.put("system", map);

        // ===================java================
        map = new HashMap<>();
        RuntimeMXBean mxBean = ManagementFactory.getRuntimeMXBean();
        // java 的名称
        map.put("name", System.getProperty("java.vm.name"));
        map.put("vendor",System.getProperty("java.vendor"));
        // java 的安装路径
        map.put("home", System.getProperty("java.home"));
        // java 的版本
        map.put("version",System.getProperty("java.version"));
        // java 启动时间
        map.put("startTime", DateUtils.getDateString(new Date(mxBean.getStartTime())));
        // java 运行时间
        map.put("runTime", DateUtils.secToTime(Integer.valueOf(mxBean.getUptime() + "")));
        resultMap.put("java", map);
        // 堆与非堆
        MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
        // 堆
        map = new HashMap<>();
        MemoryUsage heap = memoryMXBean.getHeapMemoryUsage();
        logger.info("Heap Memory Usage:"+heap);
        // 初始大小
        Long heapInit = heap.getInit();
        if(heapInit<0) {
            heapInit = 0L;
        }else {
            heapInit = heapInit / 1024;
        }
        map.put("heapInit", disposeUnit(heapInit + "k"));
        // 已用内存
        Long heapUsed = heap.getUsed();
        if(heapUsed<0) {
            heapUsed = 0L;
        }else {
            heapUsed = heapUsed / 1024;
        }
        map.put("heapUsed", disposeUnit(heapUsed + "k"));
        // 最大内存
        Long heapMax = heap.getMax();
        if(heapMax<0) {
            heapMax = 0L;
        }else {
            heapMax = heapMax / 1024;
        }
        map.put("heapMax", disposeUnit(heapMax + "k"));
        // 可用内存
        Long heapFree = heapMax - heapUsed;
        if(heapFree<0) {
            heapFree = 0L;
        }
        map.put("heapFree", disposeUnit(heapFree + "k"));
        resultMap.put("heap", map);
        
        // 非堆
        map = new HashMap<>();
        MemoryUsage nonHeap = memoryMXBean.getNonHeapMemoryUsage();
        logger.info("Non-Heap Memory Usage:"+nonHeap);
        // 初始大小
        Long noHeapInit = nonHeap.getInit();
        if(noHeapInit<0) {
            noHeapInit = 0L;
        }else {
            noHeapInit = noHeapInit / 1024;
        }
        map.put("noHeapInit", disposeUnit(noHeapInit + "k"));
        // 已用内存
        Long noHeapUsed = nonHeap.getUsed();
        if(noHeapUsed<0) {
            noHeapUsed = 0L;
        }else {
            noHeapUsed = noHeapUsed / 1024;
        }
        map.put("noHeapUsed", disposeUnit(noHeapUsed + "k"));
        // 最大内存
        Long noHeapMax = nonHeap.getMax();
        if(noHeapMax<0) {
            noHeapMax = 0L;
        }else {
            noHeapMax = noHeapMax / 1024;
        }
        map.put("noHeapMax", disposeUnit(noHeapMax + "k"));
        // 可用内存
        Long notheapfree = noHeapMax - noHeapUsed;
        if(notheapfree<0) {
            notheapfree = 0L;
        }
        map.put("noHeapFree", disposeUnit(notheapfree + "k"));
        resultMap.put("noheap", map);
        return resultMap;
    }

    /**
     * 处理单位转换
     * 
     * @param s
     *            带单位的数据字符串
     * 
     * @return 以K/KB/M/G/T为单位处理后的数值
     */
    private static String disposeUnit(String s) {
        BigDecimal bg = new BigDecimal(0);
        try {
            s = s.toUpperCase();
            String lastIndex = s.substring(s.length() - 1);
            String num = s.substring(0, s.length() - 1);
            BigDecimal size = new BigDecimal(1024);
            bg = new BigDecimal(num);
            if ("K".equals(lastIndex) || "KB".equals(lastIndex)) {
                if (bg.compareTo(size) == 1 || bg.compareTo(size) == 0) {
                    s = (bg.divide(size)) + "m";
                    return disposeUnit(s);
                }
                s = bg.setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue() + "KB";
                return s;
            } else if ("M".equals(lastIndex)) {
                if (bg.compareTo(size) == 1 || bg.compareTo(size) == 0) {
                    s = (bg.divide(size)) + "g";
                    return disposeUnit(s);
                }
                s = bg.setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue() + "M";
                return s;
            } else if ("G".equals(lastIndex)) {
                if (bg.compareTo(size) == 1 || bg.compareTo(size) == 0) {
                    s = (bg.divide(size).setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue()) + "T";
                    return s;
                }
                return bg.setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue() + "G";
            }
        } catch (NumberFormatException e) {
            logger.error("获取服务器内存大小单位转换异常:" + e.getMessage());
            return bg + "k";
        }
        return bg + "k";
    }

    /**
     * 处理单位转换 K/KB/M/T 最终转换为G 处理
     *
     * @param s
     *            带单位的数据字符串
     * @return 以G 为单位处理后的数值
     */
    private static BigDecimal disposeUnitConvertG(String s) {
        BigDecimal bg = new BigDecimal(0);
        try {
            s = s.toUpperCase();
            String lastIndex = s.substring(s.length() - 1);
            String num = s.substring(0, s.length() - 1);
            if (num.length() == 0)
                return bg;
            bg = new BigDecimal(num);
            BigDecimal size = new BigDecimal(1024);
            if (lastIndex.equals("G")) {
                return bg.setScale(3, BigDecimal.ROUND_HALF_UP);
            } else if (lastIndex.equals("T")) {
                return bg.multiply(size).setScale(3, BigDecimal.ROUND_HALF_UP);
            } else if (lastIndex.equals("M")) {
                return bg.divide(size).setScale(3, BigDecimal.ROUND_HALF_UP);
            } else if (lastIndex.equals("K") || lastIndex.equals("KB")) {
                size = size.multiply(size).setScale(3, BigDecimal.ROUND_HALF_UP);
                return bg.divide(size).setScale(3, BigDecimal.ROUND_HALF_UP);
            }
        } catch (NumberFormatException e) {
            logger.error("获取服务器磁盘大小统一转换成G异常:" + e.getMessage());
            return bg;
        }
        return bg;
    }
    
    /**
     * 获取Linux下的IP地址
     *
     * @return IP地址
     * @throws SocketException
     */
    private static String getLinuxLocalIp(){
        String ip = "";
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                String name = intf.getName();
                if (!name.contains("docker") && !name.contains("lo")) {
                    for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                        InetAddress inetAddress = enumIpAddr.nextElement();
                        if (!inetAddress.isLoopbackAddress()) {
                            String ipaddress = inetAddress.getHostAddress().toString();
                            if (!ipaddress.contains("::") && !ipaddress.contains("0:0:") && !ipaddress.contains("fe80")) {
                                ip = ipaddress;
                                System.out.println(ipaddress);
                            }
                        }
                    }
                }
            }
        } catch (SocketException ex) {
            logger.error("获取服务器ip异常:"+ex.getMessage());
            ip = "127.0.0.1";
        }
        return ip;
    }
}

以上就是相关java代码,有需要的拿去。。。我只是代码的搬运工

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
可以使用 Java 的 SSH 客户端库来连接 Linux 服务器。以下是一个简单的示例代码: ```java import com.jcraft.jsch.*; public class SSHConnection { public static void main(String[] args) { String host = "your_server_ip"; String user = "your_username"; String password = "your_password"; try { JSch jsch = new JSch(); Session session = jsch.getSession(user, host, 22); session.setPassword(password); session.setConfig("StrictHostKeyChecking", "no"); // 忽略主机密钥检查 session.connect(); // 执行命令 ChannelExec channel = (ChannelExec) session.openChannel("exec"); channel.setCommand("ls -l"); channel.connect(); System.out.println("Command Output:"); System.out.println(getOutput(channel)); // 关闭连接 channel.disconnect(); session.disconnect(); } catch (JSchException e) { e.printStackTrace(); } } private static String getOutput(ChannelExec channel) throws JSchException { StringBuilder output = new StringBuilder(); byte[] buffer = new byte[1024]; while (channel.getExitStatus() == -1) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } while (channel.getInputStream().available() > 0) { int len = channel.getInputStream().read(buffer); output.append(new String(buffer, 0, len)); } while (channel.getExtInputStream().available() > 0) { int len = channel.getExtInputStream().read(buffer); output.append(new String(buffer, 0, len)); } } return output.toString(); } } ``` 在上面的代码中,我们使用 JSch 库来建立 SSH 连接。首先,我们创建一个 `JSch` 实例,然后使用 `getSession` 方法创建一个连接会话。我们设置用户名、主机名和端口号(默认是 22)。接下来,我们设置密码并连接到服务器。如果你不想每次连接时都检查主机密钥,可以使用 `setConfig` 方法来禁用它。 在连接成功后,我们可以使用 `ChannelExec` 类来执行命令。在上面的代码中,我们执行了一个简单的 `ls -l` 命令,并将输出打印到控制台。在执行完命令后,我们必须关闭连接。 最后,我们定义了一个 `getOutput` 方法来获取命令的输出。该方法循环读取输入流和错误流,并将它们转换为字符串。注意,我们必须等待命令执行完成后才能读取输出。 请注意,当连接到远程服务器时,为了保证安全,你应该使用密钥而不是密码进行身份验证。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值