JAVA获取服务器信息(JSP版本)

JAVA获取服务器信息
获取服务器CPU、内存、磁盘、java环境等硬件、软件信息
两种方式,一种是用sigar,另一种是用oshi
oshi方式
<%@ page import="oshi.util.FormatUtil" %>
<%@ page import="oshi.hardware.*" %>
<%@ page import="oshi.util.Util" %>
<%@ page import="java.util.Arrays" %>
<%@ page import="java.util.List" %>
<%@ page import="oshi.software.os.*" %>
<%@ page import="oshi.SystemInfo" %>
<%@ page import="java.io.IOException" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>oshi_systeminfo</title>
</head>
<body>

    <%
        out.println("Initializing System...");
        out.println("<br/>");
        SystemInfo si = new SystemInfo();

        HardwareAbstractionLayer hal = si.getHardware();
        OperatingSystem os = si.getOperatingSystem();

        out.println("os--------------------------------->" + os);
        out.println("<hr/>");

        out.println("Checking computer system...");
        out.println("<br/>");
        printComputerSystem(out,hal.getComputerSystem());
        out.println("<hr/>");

        out.println("Checking Processor...");
        out.println("<br/>");
        printProcessor(out,hal.getProcessor());
        out.println("<hr/>");

        out.println("Checking Memory...");
        out.println("<br/>");
        printMemory(out,hal.getMemory());
        out.println("<hr/>");

        out.println("Checking CPU...");
        out.println("<br/>");
        printCpu(out,hal.getProcessor());
        out.println("<hr/>");

        out.println("Checking Processes...");
        out.println("<br/>");
        printProcesses(out,os, hal.getMemory());
        out.println("<hr/>");

        out.println("Checking Sensors...");
        out.println("<br/>");
        printSensors(out,hal.getSensors());
        out.println("<hr/>");

        out.println("Checking Power sources...");
        out.println("<br/>");
        printPowerSources(out,hal.getPowerSources());
        out.println("<hr/>");

        out.println("Checking Disks...");
        out.println("<br/>");
        printDisks(out,hal.getDiskStores());
        out.println("<hr/>");

        out.println("Checking File System...");
        out.println("<br/>");
        printFileSystem(out,os.getFileSystem());
        out.println("<hr/>");

        out.println("Checking Network interfaces...");
        out.println("<br/>");
        printNetworkInterfaces(out,hal.getNetworkIFs());
        out.println("<hr/>");

        out.println("Checking Network parameterss...");
        out.println("<br/>");
        printNetworkParameters(out,os.getNetworkParams());
        out.println("<hr/>");

        // hardware: displays
        out.println("Checking Displays...");
        out.println("<br/>");
        printDisplays(out,hal.getDisplays());
        out.println("<hr/>");

        // hardware: USB devices
        out.println("Checking USB Devices...");
        out.println("<br/>");
        printUsbDevices(out,hal.getUsbDevices(true));
    %>

    <%!
        private static void _out (javax.servlet.jsp.JspWriter _jspx_out,Object msg) throws IOException {
            _jspx_out.println(msg);
            _jspx_out.println("<br/>");
        }
    %>

    <%!
        private static void printComputerSystem(javax.servlet.jsp.JspWriter _jspx_out,final ComputerSystem computerSystem) throws IOException {
            _out(_jspx_out,"manufacturer: " + computerSystem.getManufacturer());
            _out(_jspx_out,"model: " + computerSystem.getModel());
            _out(_jspx_out,"serialnumber: " + computerSystem.getSerialNumber());
            final Firmware firmware = computerSystem.getFirmware();
            _out(_jspx_out,"firmware:");
            _out(_jspx_out,"  manufacturer: " + firmware.getManufacturer());
            _out(_jspx_out,"  name: " + firmware.getName());
            _out(_jspx_out,"  description: " + firmware.getDescription());
            _out(_jspx_out,"  version: " + firmware.getVersion());
            _out(_jspx_out,"  release date: " + (firmware.getReleaseDate() == null ? "unknown"
                    : firmware.getReleaseDate() == null ? "unknown" : FormatUtil.formatDate(firmware.getReleaseDate())));
            final Baseboard baseboard = computerSystem.getBaseboard();
            _out(_jspx_out,"baseboard:");
            _out(_jspx_out,"  manufacturer: " + baseboard.getManufacturer());
            _out(_jspx_out,"  model: " + baseboard.getModel());
            _out(_jspx_out,"  version: " + baseboard.getVersion());
            _out(_jspx_out,"  serialnumber: " + baseboard.getSerialNumber());
        }
    %>

    <%!
        private static void printProcessor(javax.servlet.jsp.JspWriter _jspx_out,CentralProcessor processor) throws IOException {
            _out(_jspx_out,processor);
            _out(_jspx_out," " + processor.getPhysicalPackageCount() + " physical CPU package(s)");
            _out(_jspx_out," " + processor.getPhysicalProcessorCount() + " physical CPU core(s)");
            _out(_jspx_out," " + processor.getLogicalProcessorCount() + " logical CPU(s)");

            _out(_jspx_out,"Identifier: " + processor.getIdentifier());
            _out(_jspx_out,"ProcessorID: " + processor.getProcessorID());
        }
    %>

    <%!
        private static void printMemory(javax.servlet.jsp.JspWriter _jspx_out,GlobalMemory memory) throws IOException {
            _out(_jspx_out,"Memory: " + FormatUtil.formatBytes(memory.getAvailable()) + "/"
                    + FormatUtil.formatBytes(memory.getTotal()));
            _out(_jspx_out,"Swap used: " + FormatUtil.formatBytes(memory.getSwapUsed()) + "/"
                    + FormatUtil.formatBytes(memory.getSwapTotal()));
        }
    %>

    <%!
        private static void printCpu(javax.servlet.jsp.JspWriter _jspx_out,CentralProcessor processor) throws IOException {
            _out(_jspx_out,"Uptime: " + FormatUtil.formatElapsedSecs(processor.getSystemUptime()));
            _out(_jspx_out,
                    "Context Switches/Interrupts: " + processor.getContextSwitches() + " / " + processor.getInterrupts());

            long[] prevTicks = processor.getSystemCpuLoadTicks();
            _out(_jspx_out,"CPU, IOWait, and IRQ ticks @ 0 sec:" + Arrays.toString(prevTicks));
            // Wait a second...
            Util.sleep(1000);
            long[] ticks = processor.getSystemCpuLoadTicks();
            _out(_jspx_out,"CPU, IOWait, and IRQ ticks @ 1 sec:" + Arrays.toString(ticks));
            long user = ticks[CentralProcessor.TickType.USER.getIndex()] - prevTicks[CentralProcessor.TickType.USER.getIndex()];
            long nice = ticks[CentralProcessor.TickType.NICE.getIndex()] - prevTicks[CentralProcessor.TickType.NICE.getIndex()];
            long sys = ticks[CentralProcessor.TickType.SYSTEM.getIndex()] - prevTicks[CentralProcessor.TickType.SYSTEM.getIndex()];
            long idle = ticks[CentralProcessor.TickType.IDLE.getIndex()] - prevTicks[CentralProcessor.TickType.IDLE.getIndex()];
            long iowait = ticks[CentralProcessor.TickType.IOWAIT.getIndex()] - prevTicks[CentralProcessor.TickType.IOWAIT.getIndex()];
            long irq = ticks[CentralProcessor.TickType.IRQ.getIndex()] - prevTicks[CentralProcessor.TickType.IRQ.getIndex()];
            long softirq = ticks[CentralProcessor.TickType.SOFTIRQ.getIndex()] - prevTicks[CentralProcessor.TickType.SOFTIRQ.getIndex()];
            long steal = ticks[CentralProcessor.TickType.STEAL.getIndex()] - prevTicks[CentralProcessor.TickType.STEAL.getIndex()];
            long totalCpu = user + nice + sys + idle + iowait + irq + softirq + steal;

            _out(_jspx_out,String.format(
                    "User: %.1f%% Nice: %.1f%% System: %.1f%% Idle: %.1f%% IOwait: %.1f%% IRQ: %.1f%% SoftIRQ: %.1f%% Steal: %.1f%%%n",
                    100d * user / totalCpu, 100d * nice / totalCpu, 100d * sys / totalCpu, 100d * idle / totalCpu,
                    100d * iowait / totalCpu, 100d * irq / totalCpu, 100d * softirq / totalCpu, 100d * steal / totalCpu));
            _out(_jspx_out,String.format("CPU load: %.1f%% (counting ticks)%n", processor.getSystemCpuLoadBetweenTicks() * 100));
            _out(_jspx_out,String.format("CPU load: %.1f%% (OS MXBean)%n", processor.getSystemCpuLoad() * 100));
            double[] loadAverage = processor.getSystemLoadAverage(3);
            _out(_jspx_out,"CPU load averages:" + (loadAverage[0] < 0 ? " N/A" : String.format(" %.2f", loadAverage[0]))
                    + (loadAverage[1] < 0 ? " N/A" : String.format(" %.2f", loadAverage[1]))
                    + (loadAverage[2] < 0 ? " N/A" : String.format(" %.2f", loadAverage[2])));
            // per core CPU
            StringBuilder procCpu = new StringBuilder("CPU load per processor:");
            double[] load = processor.getProcessorCpuLoadBetweenTicks();
            for (double avg : load) {
                procCpu.append(String.format(" %.1f%%", avg * 100));
            }
            _out(_jspx_out,procCpu.toString());
        }
    %>

    <%!
        private static void printProcesses(javax.servlet.jsp.JspWriter _jspx_out,OperatingSystem os, GlobalMemory memory) throws IOException {
            _out(_jspx_out,"Processes: " + os.getProcessCount() + ", Threads: " + os.getThreadCount());
            // Sort by highest CPU
            List<OSProcess> procs = Arrays.asList(os.getProcesses(5, OperatingSystem.ProcessSort.CPU));

            _out(_jspx_out,"   PID  %CPU %MEM       VSZ       RSS Name");
            for (int i = 0; i < procs.size() && i < 5; i++) {
                OSProcess p = procs.get(i);
                _out(_jspx_out,String.format(" %5d %5.1f %4.1f %9s %9s %s%n", p.getProcessID(),
                        100d * (p.getKernelTime() + p.getUserTime()) / p.getUpTime(),
                        100d * p.getResidentSetSize() / memory.getTotal(), FormatUtil.formatBytes(p.getVirtualSize()),
                        FormatUtil.formatBytes(p.getResidentSetSize()), p.getName()));
            }
        }
    %>

    <%!
        private static void printSensors(javax.servlet.jsp.JspWriter _jspx_out,Sensors sensors) throws IOException {
            _out(_jspx_out,"Sensors:");
            _out(_jspx_out,String.format(" CPU Temperature: %.1f°C%n", sensors.getCpuTemperature()));
            _out(_jspx_out," Fan Speeds: " + Arrays.toString(sensors.getFanSpeeds()));
            _out(_jspx_out,String.format(" CPU Voltage: %.1fV%n", sensors.getCpuVoltage()));
        }
    %>

    <%!
        private static void printPowerSources(javax.servlet.jsp.JspWriter _jspx_out,PowerSource[] powerSources) throws IOException {
            StringBuilder sb = new StringBuilder("Power: ");
            if (powerSources.length == 0) {
                sb.append("Unknown");
            } else {
                double timeRemaining = powerSources[0].getTimeRemaining();
                if (timeRemaining < -1d) {
                    sb.append("Charging");
                } else if (timeRemaining < 0d) {
                    sb.append("Calculating time remaining");
                } else {
                    sb.append(String.format("%d:%02d remaining", (int) (timeRemaining / 3600),
                            (int) (timeRemaining / 60) % 60));
                }
            }
            for (PowerSource pSource : powerSources) {
                sb.append(String.format("%n %s @ %.1f%%", pSource.getName(), pSource.getRemainingCapacity() * 100d));
            }
            _out(_jspx_out,sb.toString());
        }
    %>

    <%!
        private static void printDisks(javax.servlet.jsp.JspWriter _jspx_out,HWDiskStore[] diskStores) throws IOException {
            _out(_jspx_out,"Disks:");
            for (HWDiskStore disk : diskStores) {
                boolean readwrite = disk.getReads() > 0 || disk.getWrites() > 0;
                _out(_jspx_out,String.format(" %s: (model: %s - S/N: %s) size: %s, reads: %s (%s), writes: %s (%s), xfer: %s ms%n",
                        disk.getName(), disk.getModel(), disk.getSerial(),
                        disk.getSize() > 0 ? FormatUtil.formatBytesDecimal(disk.getSize()) : "?",
                        readwrite ? disk.getReads() : "?", readwrite ? FormatUtil.formatBytes(disk.getReadBytes()) : "?",
                        readwrite ? disk.getWrites() : "?", readwrite ? FormatUtil.formatBytes(disk.getWriteBytes()) : "?",
                        readwrite ? disk.getTransferTime() : "?"));
                HWPartition[] partitions = disk.getPartitions();
                if (partitions == null) {
                    continue;
                }
                for (HWPartition part : partitions) {
                    _out(_jspx_out,String.format(" |-- %s: %s (%s) Maj:Min=%d:%d, size: %s%s%n", part.getIdentification(),
                            part.getName(), part.getType(), part.getMajor(), part.getMinor(),
                            FormatUtil.formatBytesDecimal(part.getSize()),
                            part.getMountPoint().isEmpty() ? "" : " @ " + part.getMountPoint()));
                }
            }
        }
    %>

    <%!
        private static void printFileSystem(javax.servlet.jsp.JspWriter _jspx_out,FileSystem fileSystem) throws IOException {
            _out(_jspx_out,"File System:");

            _out(_jspx_out,String.format(" File Descriptors: %d/%d%n", fileSystem.getOpenFileDescriptors(),
                    fileSystem.getMaxFileDescriptors()));

            OSFileStore[] fsArray = fileSystem.getFileStores();
            for (OSFileStore fs : fsArray) {
                long usable = fs.getUsableSpace();
                long total = fs.getTotalSpace();
                _out(_jspx_out,String.format(
                        " %s (%s) [%s] %s of %s free (%.1f%%) is %s "
                                + (fs.getLogicalVolume() != null && fs.getLogicalVolume().length() > 0 ? "[%s]" : "%s")
                                + " and is mounted at %s%n",
                        fs.getName(), fs.getDescription().isEmpty() ? "file system" : fs.getDescription(), fs.getType(),
                        FormatUtil.formatBytes(usable), FormatUtil.formatBytes(fs.getTotalSpace()), 100d * usable / total,
                        fs.getVolume(), fs.getLogicalVolume(), fs.getMount()));
            }
        }
    %>

    <%!
        private static void printNetworkInterfaces(javax.servlet.jsp.JspWriter _jspx_out,NetworkIF[] networkIFs) throws IOException {
            _out(_jspx_out,"Network interfaces:");
            for (NetworkIF net : networkIFs) {
                _out(_jspx_out,String.format(" Name: %s (%s)%n", net.getName(), net.getDisplayName()));
                _out(_jspx_out,String.format("   MAC Address: %s %n", net.getMacaddr()));
                _out(_jspx_out,String.format("   MTU: %s, Speed: %s %n", net.getMTU(), FormatUtil.formatValue(net.getSpeed(), "bps")));
                _out(_jspx_out,String.format("   IPv4: %s %n", Arrays.toString(net.getIPv4addr())));
                _out(_jspx_out,String.format("   IPv6: %s %n", Arrays.toString(net.getIPv6addr())));
                boolean hasData = net.getBytesRecv() > 0 || net.getBytesSent() > 0 || net.getPacketsRecv() > 0
                        || net.getPacketsSent() > 0;
                _out(_jspx_out,String.format("   Traffic: received %s/%s%s; transmitted %s/%s%s %n",
                        hasData ? net.getPacketsRecv() + " packets" : "?",
                        hasData ? FormatUtil.formatBytes(net.getBytesRecv()) : "?",
                        hasData ? " (" + net.getInErrors() + " err)" : "",
                        hasData ? net.getPacketsSent() + " packets" : "?",
                        hasData ? FormatUtil.formatBytes(net.getBytesSent()) : "?",
                        hasData ? " (" + net.getOutErrors() + " err)" : ""));
            }
        }
    %>

    <%!
        private static void printNetworkParameters(javax.servlet.jsp.JspWriter _jspx_out,NetworkParams networkParams) throws IOException {
            _out(_jspx_out,"Network parameters:");
            _out(_jspx_out,String.format(" Host name: %s%n", networkParams.getHostName()));
            _out(_jspx_out,String.format(" Domain name: %s%n", networkParams.getDomainName()));
            _out(_jspx_out,String.format(" DNS servers: %s%n", Arrays.toString(networkParams.getDnsServers())));
            _out(_jspx_out,String.format(" IPv4 Gateway: %s%n", networkParams.getIpv4DefaultGateway()));
            _out(_jspx_out,String.format(" IPv6 Gateway: %s%n", networkParams.getIpv6DefaultGateway()));
        }
    %>

    <%!
        private static void printDisplays(javax.servlet.jsp.JspWriter _jspx_out,Display[] displays) throws IOException {
            _out(_jspx_out,"Displays:");
            int i = 0;
            for (Display display : displays) {
                _out(_jspx_out," Display " + i + ":");
                _out(_jspx_out,display.toString());
                i++;
            }
        }
    %>

    <%!
        private static void printUsbDevices(javax.servlet.jsp.JspWriter _jspx_out,UsbDevice[] usbDevices) throws IOException {
            _out(_jspx_out,"USB Devices:");
            for (UsbDevice usbDevice : usbDevices) {
                _out(_jspx_out,usbDevice.toString());
            }
        }
    %>

</body>
</html>

sigar方式

1,该方式需要在服务器上放库文件,即Windows需要dll文件,Linux需要so文件
2,Windows(32位):sigar-x86-winnt.dll
Windows(64位):sigar-amd64-winnt.dll
Linux(32位):libsigar-x86-linux.so
Linux(64位):libsigar-amd64-linux.so

3,System.getProperty(“java.library.path”)可以确定dll或so文件应该放的位置

<%@ page import="java.util.Properties" %>
<%@ page import="java.net.InetAddress" %>
<%@ page import="java.util.Map" %>
<%@ page import="org.hyperic.sigar.*" %>
<%@ page import="org.apache.commons.lang3.exception.ExceptionUtils" %>
<%@ page import="java.io.IOException" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>sigar_systeminfo</title>
</head>
<body>

    <%
        try {
            // System信息,从jvm获取
            property(out);
            out.println("<hr/>");
            // cpu信息
            cpu(out);
            out.println("<hr/>");
            // 内存信息
            memory(out);
            out.println("<hr/>");
            // 操作系统信息
            os(out);
            out.println("<hr/>");
            // 用户信息
            who(out);
            out.println("<hr/>");
            // 文件系统信息
            file(out);
            out.println("<hr/>");
            // 网络信息
            net(out);
            out.println("<hr/>");
            // 以太网信息
            ethernet(out);
            out.println("<hr/>");
        } catch (Exception e) {
            e.printStackTrace();
            out.println("<hr/>");
            out.println(ExceptionUtils.getStackTrace(e));
        }
    %>

    <%!
        private static void _out (javax.servlet.jsp.JspWriter _jspx_out,Object msg) throws IOException {
            _jspx_out.println(msg);
            _jspx_out.println("<br/>");
        }
    %>

    <%!
        private static void property(javax.servlet.jsp.JspWriter _jspx_out) throws IOException {
            Runtime r = Runtime.getRuntime();
            Properties props = System.getProperties();
            InetAddress addr;
            addr = InetAddress.getLocalHost();
            String ip = addr.getHostAddress();
            Map<String, String> map = System.getenv();
            String userName = map.get("USERNAME");// 获取用户名
            String computerName = map.get("COMPUTERNAME");// 获取计算机名
            String userDomain = map.get("USERDOMAIN");// 获取计算机域名
            _out(_jspx_out,"用户名:    " + userName);
            _out(_jspx_out,"计算机名:    " + computerName);
            _out(_jspx_out,"计算机域名:    " + userDomain);
            _out(_jspx_out,"本地ip地址:    " + ip);
            _out(_jspx_out,"本地主机名:    " + addr.getHostName());
            _out(_jspx_out,"JVM可以使用的总内存:    " + r.totalMemory());
            _out(_jspx_out,"JVM可以使用的剩余内存:    " + r.freeMemory());
            _out(_jspx_out,"JVM可以使用的处理器个数:    " + r.availableProcessors());
            _out(_jspx_out,"Java的运行环境版本:    " + props.getProperty("java.version"));
            _out(_jspx_out,"Java的运行环境供应商:    " + props.getProperty("java.vendor"));
            _out(_jspx_out,"Java供应商的URL:    " + props.getProperty("java.vendor.url"));
            _out(_jspx_out,"Java的安装路径:    " + props.getProperty("java.home"));
            _out(_jspx_out,"Java的虚拟机规范版本:    " + props.getProperty("java.vm.specification.version"));
            _out(_jspx_out,"Java的虚拟机规范供应商:    " + props.getProperty("java.vm.specification.vendor"));
            _out(_jspx_out,"Java的虚拟机规范名称:    " + props.getProperty("java.vm.specification.name"));
            _out(_jspx_out,"Java的虚拟机实现版本:    " + props.getProperty("java.vm.version"));
            _out(_jspx_out,"Java的虚拟机实现供应商:    " + props.getProperty("java.vm.vendor"));
            _out(_jspx_out,"Java的虚拟机实现名称:    " + props.getProperty("java.vm.name"));
            _out(_jspx_out,"Java运行时环境规范版本:    " + props.getProperty("java.specification.version"));
            _out(_jspx_out,"Java运行时环境规范供应商:    " + props.getProperty("java.specification.vender"));
            _out(_jspx_out,"Java运行时环境规范名称:    " + props.getProperty("java.specification.name"));
            _out(_jspx_out,"Java的类格式版本号:    " + props.getProperty("java.class.version"));
            _out(_jspx_out,"Java的类路径:    " + props.getProperty("java.class.path"));
            _out(_jspx_out,"加载库时搜索的路径列表:    " + props.getProperty("java.library.path"));
            _out(_jspx_out,"默认的临时文件路径:    " + props.getProperty("java.io.tmpdir"));
            _out(_jspx_out,"一个或多个扩展目录的路径:    " + props.getProperty("java.ext.dirs"));
            _out(_jspx_out,"操作系统的名称:    " + props.getProperty("os.name"));
            _out(_jspx_out,"操作系统的构架:    " + props.getProperty("os.arch"));
            _out(_jspx_out,"操作系统的版本:    " + props.getProperty("os.version"));
            _out(_jspx_out,"文件分隔符:    " + props.getProperty("file.separator"));
            _out(_jspx_out,"路径分隔符:    " + props.getProperty("path.separator"));
            _out(_jspx_out,"行分隔符:    " + props.getProperty("line.separator"));
            _out(_jspx_out,"用户的账户名称:    " + props.getProperty("user.name"));
            _out(_jspx_out,"用户的主目录:    " + props.getProperty("user.home"));
            _out(_jspx_out,"用户的当前工作目录:    " + props.getProperty("user.dir"));
        }
    %>

    <%!
        private static void memory(javax.servlet.jsp.JspWriter _jspx_out) throws SigarException, IOException {
            Sigar sigar = new Sigar();
            Mem mem = sigar.getMem();
            // 内存总量
            _out(_jspx_out,"内存总量:    " + mem.getTotal() / 1024L + "K av");
            // 当前内存使用量
            _out(_jspx_out,"当前内存使用量:    " + mem.getUsed() / 1024L + "K used");
            // 当前内存剩余量
            _out(_jspx_out,"当前内存剩余量:    " + mem.getFree() / 1024L + "K free");
            Swap swap = sigar.getSwap();
            // 交换区总量
            _out(_jspx_out,"交换区总量:    " + swap.getTotal() / 1024L + "K av");
            // 当前交换区使用量
            _out(_jspx_out,"当前交换区使用量:    " + swap.getUsed() / 1024L + "K used");
            // 当前交换区剩余量
            _out(_jspx_out,"当前交换区剩余量:    " + swap.getFree() / 1024L + "K free");
        }
    %>

    <%!
        private static void cpu(javax.servlet.jsp.JspWriter _jspx_out) throws SigarException, IOException {
            Sigar sigar = new Sigar();
            CpuInfo infos[] = sigar.getCpuInfoList();
            CpuPerc cpuList[] = null;
            cpuList = sigar.getCpuPercList();
            for (int i = 0; i < infos.length; i++) {// 不管是单块CPU还是多CPU都适用
                CpuInfo info = infos[i];
                _out(_jspx_out,"第" + (i + 1) + "块CPU信息");
                _out(_jspx_out,"CPU的总量MHz:    " + info.getMhz());// CPU的总量MHz
                _out(_jspx_out,"CPU生产商:    " + info.getVendor());// 获得CPU的卖主,如:Intel
                _out(_jspx_out,"CPU类别:    " + info.getModel());// 获得CPU的类别,如:Celeron
                _out(_jspx_out,"CPU缓存数量:    " + info.getCacheSize());// 缓冲存储器数量
                printCpuPerc(cpuList[i],_jspx_out);
            }
        }
    %>

    <%!
        private static void printCpuPerc(CpuPerc cpu,javax.servlet.jsp.JspWriter _jspx_out) throws IOException {
            _out(_jspx_out,"CPU用户使用率:    " + CpuPerc.format(cpu.getUser()));// 用户使用率
            _out(_jspx_out,"CPU系统使用率:    " + CpuPerc.format(cpu.getSys()));// 系统使用率
            _out(_jspx_out,"CPU当前等待率:    " + CpuPerc.format(cpu.getWait()));// 当前等待率
            _out(_jspx_out,"CPU当前错误率:    " + CpuPerc.format(cpu.getNice()));//
            _out(_jspx_out,"CPU当前空闲率:    " + CpuPerc.format(cpu.getIdle()));// 当前空闲率
            _out(_jspx_out,"CPU总的使用率:    " + CpuPerc.format(cpu.getCombined()));// 总的使用率
        }
    %>

    <%!
        private static void os(javax.servlet.jsp.JspWriter _jspx_out) throws IOException {
            OperatingSystem OS = OperatingSystem.getInstance();
            // 操作系统内核类型如: 386、486、586等x86
            _out(_jspx_out,"操作系统:    " + OS.getArch());
            _out(_jspx_out,"操作系统CpuEndian():    " + OS.getCpuEndian());//
            _out(_jspx_out,"操作系统DataModel():    " + OS.getDataModel());//
            // 系统描述
            _out(_jspx_out,"操作系统的描述:    " + OS.getDescription());
            // 操作系统类型
            // _out(_jspx_out,"OS.getName():    " + OS.getName());
            // _out(_jspx_out,"OS.getPatchLevel():    " + OS.getPatchLevel());//
            // 操作系统的卖主
            _out(_jspx_out,"操作系统的卖主:    " + OS.getVendor());
            // 卖主名称
            _out(_jspx_out,"操作系统的卖主名:    " + OS.getVendorCodeName());
            // 操作系统名称
            _out(_jspx_out,"操作系统名称:    " + OS.getVendorName());
            // 操作系统卖主类型
            _out(_jspx_out,"操作系统卖主类型:    " + OS.getVendorVersion());
            // 操作系统的版本号
            _out(_jspx_out,"操作系统的版本号:    " + OS.getVersion());
        }
    %>

    <%!
        private static void who(javax.servlet.jsp.JspWriter _jspx_out) throws SigarException, IOException {
            Sigar sigar = new Sigar();
            Who who[] = sigar.getWhoList();
            if (who != null && who.length > 0) {
                for (int i = 0; i < who.length; i++) {
                    // _out(_jspx_out,"当前系统进程表中的用户名" + String.valueOf(i));
                    Who _who = who[i];
                    _out(_jspx_out,"用户控制台:    " + _who.getDevice());
                    _out(_jspx_out,"用户host:    " + _who.getHost());
                    // _out(_jspx_out,"getTime():    " + _who.getTime());
                    // 当前系统进程表中的用户名
                    _out(_jspx_out,"当前系统进程表中的用户名:    " + _who.getUser());
                }
            }
        }
    %>

    <%!
        private static void file(javax.servlet.jsp.JspWriter _jspx_out) throws Exception {
            Sigar sigar = new Sigar();
            FileSystem fslist[] = sigar.getFileSystemList();
            for (int i = 0; i < fslist.length; i++) {
                _out(_jspx_out,"分区的盘符名称" + i);
                FileSystem fs = fslist[i];
                // 分区的盘符名称
                _out(_jspx_out,"盘符名称:    " + fs.getDevName());
                // 分区的盘符名称
                _out(_jspx_out,"盘符路径:    " + fs.getDirName());
                _out(_jspx_out,"盘符标志:    " + fs.getFlags());//
                // 文件系统类型,比如 FAT32、NTFS
                _out(_jspx_out,"盘符类型:    " + fs.getSysTypeName());
                // 文件系统类型名,比如本地硬盘、光驱、网络文件系统等
                _out(_jspx_out,"盘符类型名:    " + fs.getTypeName());
                // 文件系统类型
                _out(_jspx_out,"盘符文件系统类型:    " + fs.getType());
                FileSystemUsage usage = null;
                usage = sigar.getFileSystemUsage(fs.getDirName());
                switch (fs.getType()) {
                    case 0: // TYPE_UNKNOWN :未知
                        break;
                    case 1: // TYPE_NONE
                        break;
                    case 2: // TYPE_LOCAL_DISK : 本地硬盘
                        // 文件系统总大小
                        _out(_jspx_out,fs.getDevName() + "总大小:    " + usage.getTotal() + "KB");
                        // 文件系统剩余大小
                        _out(_jspx_out,fs.getDevName() + "剩余大小:    " + usage.getFree() + "KB");
                        // 文件系统可用大小
                        _out(_jspx_out,fs.getDevName() + "可用大小:    " + usage.getAvail() + "KB");
                        // 文件系统已经使用量
                        _out(_jspx_out,fs.getDevName() + "已经使用量:    " + usage.getUsed() + "KB");
                        double usePercent = usage.getUsePercent() * 100D;
                        // 文件系统资源的利用率
                        _out(_jspx_out,fs.getDevName() + "资源的利用率:    " + usePercent + "%");
                        break;
                    case 3:// TYPE_NETWORK :网络
                        break;
                    case 4:// TYPE_RAM_DISK :闪存
                        break;
                    case 5:// TYPE_CDROM :光驱
                        break;
                    case 6:// TYPE_SWAP :页面交换
                        break;
                }
                _out(_jspx_out,fs.getDevName() + "读出:    " + usage.getDiskReads());
                _out(_jspx_out,fs.getDevName() + "写入:    " + usage.getDiskWrites());
            }
            return;
        }
    %>

    <%!
        private static void net(javax.servlet.jsp.JspWriter _jspx_out) throws Exception {
            Sigar sigar = new Sigar();
            String ifNames[] = sigar.getNetInterfaceList();
            for (int i = 0; i < ifNames.length; i++) {
                String name = ifNames[i];
                NetInterfaceConfig ifconfig = sigar.getNetInterfaceConfig(name);
                _out(_jspx_out,"网络设备名:    " + name);// 网络设备名
                _out(_jspx_out,"IP地址:    " + ifconfig.getAddress());// IP地址
                _out(_jspx_out,"子网掩码:    " + ifconfig.getNetmask());// 子网掩码
                if ((ifconfig.getFlags() & 1L) <= 0L) {
                    _out(_jspx_out,"!IFF_UP...skipping getNetInterfaceStat");
                    continue;
                }
                NetInterfaceStat ifstat = sigar.getNetInterfaceStat(name);
                _out(_jspx_out,name + "接收的总包裹数:" + ifstat.getRxPackets());// 接收的总包裹数
                _out(_jspx_out,name + "发送的总包裹数:" + ifstat.getTxPackets());// 发送的总包裹数
                _out(_jspx_out,name + "接收到的总字节数:" + ifstat.getRxBytes());// 接收到的总字节数
                _out(_jspx_out,name + "发送的总字节数:" + ifstat.getTxBytes());// 发送的总字节数
                _out(_jspx_out,name + "接收到的错误包数:" + ifstat.getRxErrors());// 接收到的错误包数
                _out(_jspx_out,name + "发送数据包时的错误数:" + ifstat.getTxErrors());// 发送数据包时的错误数
                _out(_jspx_out,name + "接收时丢弃的包数:" + ifstat.getRxDropped());// 接收时丢弃的包数
                _out(_jspx_out,name + "发送时丢弃的包数:" + ifstat.getTxDropped());// 发送时丢弃的包数
            }
        }
    %>

    <%!
        private static void ethernet(javax.servlet.jsp.JspWriter _jspx_out) throws SigarException, IOException {
            Sigar sigar = null;
            sigar = new Sigar();
            String[] ifaces = sigar.getNetInterfaceList();
            for (int i = 0; i < ifaces.length; i++) {
                NetInterfaceConfig cfg = sigar.getNetInterfaceConfig(ifaces[i]);
                if (NetFlags.LOOPBACK_ADDRESS.equals(cfg.getAddress()) || (cfg.getFlags() & NetFlags.IFF_LOOPBACK) != 0
                        || NetFlags.NULL_HWADDR.equals(cfg.getHwaddr())) {
                    continue;
                }
                _out(_jspx_out,cfg.getName() + "IP地址:" + cfg.getAddress());// IP地址
                _out(_jspx_out,cfg.getName() + "网关广播地址:" + cfg.getBroadcast());// 网关广播地址
                _out(_jspx_out,cfg.getName() + "网卡MAC地址:" + cfg.getHwaddr());// 网卡MAC地址
                _out(_jspx_out,cfg.getName() + "子网掩码:" + cfg.getNetmask());// 子网掩码
                _out(_jspx_out,cfg.getName() + "网卡描述信息:" + cfg.getDescription());// 网卡描述信息
                _out(_jspx_out,cfg.getName() + "网卡类型" + cfg.getType());//
            }
        }
    %>

</body>
</html>

效果

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

另外,可以通过System.getProperties()获取到java环境所有信息
<%@ page import="org.apache.commons.lang3.SystemUtils" %>
<%@ page import="java.util.Properties" %>
<%@ page import="java.util.Map" %>
<%@ page import="java.util.Set" %>
<%@ page import="org.springframework.util.ObjectUtils" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>context</title>
</head>
<body>

    <%
        String realPath = application.getRealPath("/");
        out.println("realPath---------->" + realPath);
        out.println("<br/>");

        Properties properties = System.getProperties();
        Set<Map.Entry<Object, Object>> entries = properties.entrySet();
        for (Map.Entry<Object, Object> entry : entries) {
            String key = ObjectUtils.getDisplayString(entry.getKey());
            String value = ObjectUtils.getDisplayString(entry.getValue());
            out.println(key + "---------->" + value);
            out.println("<br/>");
        }
    %>

</body>
</html>

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值