JAVA调用vbScript脚本取得计算机信息小例子

这里主要是记录下java如何调用vbscript取得计算机信息代码小例子,不说概念性东西.

下面的vbs文件,可以直接点击运行。有兴趣的同学可百度了解vbscript资料.

cpu.vbs

Set wmiObj = GetObject("winmgmts:")

For Each cpu in wmiObj.ExecQuery("SELECT * FROM Win32_Processor")
    CALL WScript.Echo ("SysLoadPercentage: " & cpu.LoadPercentage)
Next

disk.vbs

Set wmiObj = GetObject("winmgmts:")

For Each disk in wmiObj.ExecQuery("SELECT * FROM Win32_LogicalDisk WHERE drivetype = 3")
    diskInfo = "LogicalDisk: " & disk.Name & ", " & disk.size & ", " & disk.freespace & ", " & disk.filesystem
    Call WScript.Echo(diskInfo)
Next


io.vbs

Const C_COMMA = ", "

Set wmiObj = GetObject("winmgmts:")
Set refersher = CreateObject("WbemScripting.SWbemRefresher")
Set disks = refersher.AddEnum(wmiObj, "Win32_PerfFormattedData_PerfDisk_LogicalDisk").objectSet

refersher.Refresh
WScript.Sleep 100
refersher.Refresh
For Each disk in disks
    diskIoInfoStr = "DiskIO: " & disk.Name & C_COMMA & disk.DiskBytesPerSec  & C_COMMA & disk.DiskReadBytesPerSec  & C_COMMA & disk.DiskWriteBytesPerSec
    Call WScript.Echo (diskIoInfoStr)
Next

momery.vbs

Set wmiObj = GetObject("winmgmts:")

For Each sys In wmiObj.Execquery("Select * From Win32_OperatingSystem")
    WScript.Echo "TotalPhysicalMemory: " & sys.TotalVisibleMemorySize
    WScript.Echo "FreePhysicalMemory: " & sys.FreePhysicalMemory
Next

process.vbs

Set wmiObj = GetObject("winmgmts:")

For Each sys In wmiObj.Execquery("Select * From Win32_OperatingSystem")
    WScript.Echo "ProcessCount: " & sys.NumberOfProcesses
Next

DiskUsage.java

package com.fei;

import java.io.Serializable;

public class DiskUsage implements Serializable{
    private static final long serialVersionUID = -3383179074110556382L;

    private final String name;
    private final long totalBytes;
    private final long usableBytes;

    public DiskUsage(String name, long totalBytes, long usableBytes) {
        this.name = name;
        this.totalBytes = totalBytes;
        this.usableBytes = usableBytes;
    }

    public String getName() {
        return name;
    }

    public long getTotalBytes() {
        return totalBytes;
    }

    public long getUsedBytes(){
        return getTotalBytes() - getUsableBytes();
    }

    public long getUsableBytes() {
        return usableBytes;
    }

    public double getUsedRatio(){
        return getUsedBytes() * 100.0 / getTotalBytes();
    }

    @Override
    public String toString() {
        return "DiskUsage [name=" + name + ", totalBytes=" + totalBytes + ", usableBytes=" + usableBytes + "]";
    }
}

IORate.java

package com.fei;

import java.io.Serializable;

public class IORate implements Serializable {
    private static final long serialVersionUID = -1196061317002155422L;

    private final String name;
    private final long diskBytesPerSec;
    private final long diskReadBytesPerSec;
    private final long diskWriteBytesPerSec;

    public IORate(String name, long diskBytesPerSec, long diskReadBytesPerSec, long diskWriteBytesPerSec) {
        this.name = name;
        this.diskBytesPerSec = diskBytesPerSec;
        this.diskReadBytesPerSec = diskReadBytesPerSec;
        this.diskWriteBytesPerSec = diskWriteBytesPerSec;
    }
    public String getName() {
        return name;
    }
    public long getDiskBytesPerSec() {
        return diskBytesPerSec;
    }
    public long getDiskReadBytesPerSec() {
        return diskReadBytesPerSec;
    }
    public long getDiskWriteBytesPerSec() {
        return diskWriteBytesPerSec;
    }

    @Override
    public String toString() {
        return "IORate [name=" + name + ", diskBytesPerSec="
                + diskBytesPerSec + ", diskReadBytesPerSec="
                + diskReadBytesPerSec + ", diskWriteBytesPerSec="
                + diskWriteBytesPerSec + "]";
    }
}

ExecutorUtil.java

package com.fei;

import static java.text.MessageFormat.format;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.Executor;
import org.apache.commons.exec.PumpStreamHandler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class ExecutorUtil {

    private static Log log = LogFactory.getLog(ExecutorUtil.class);

    public static List<String> syncExecute(String cmd) {
        Executor executor = new DefaultExecutor();
        CommandLine commandLine = CommandLine.parse(cmd);
        ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        executor.setStreamHandler(new PumpStreamHandler(outputStream, errorStream));
        try {
            executor.setExitValues(null);
            int x = executor.execute(commandLine);
            log.debug("exitValue: " + x);
            String cmdOutput = outputStream.toString();
            return lineToStringArray(cmdOutput);
        }
        catch (Throwable e) {
            String errorStreamMessage = errorStream.toString();
            String exceptionMessage = format("执行命令\"{0}\"发生异常\"{1}\",命令行输出:\"{2}\"", cmd, e.getMessage(), errorStreamMessage);
            log.error(exceptionMessage, e);
            throw new Error(exceptionMessage);
        }
    }

    private static List<String> lineToStringArray(String str) throws IOException {
        List<String> lines = new ArrayList<String>();

        BufferedReader br = new BufferedReader(new StringReader(str));
        String line = br.readLine();
        while (line != null) {
            if(line != null){
                log.debug(line);
                lines.add(line);
            }

            line = br.readLine();
        }
        br.close();

        return lines;
    }
}

Monitor.java

package com.fei;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;



public class Monitor {

	public static void main(String[] args) {

		System.out.println("========硬盘情况=========");
		System.out.println(Arrays.deepToString(getDiskUsages().toArray() ));
		System.out.println("========CPU使用率========");
		System.out.println(Arrays.deepToString(getLoadPercentages().toArray()));
		System.out.println("========硬盘IO速度========");
		System.out.println(Arrays.deepToString(getDiskIORates().toArray()));
		System.out.println("========进程数===========");
		System.out.println(getProcessCount());
		System.out.println("=========总内存==========");
		System.out.println(getTotalPhysicalMemory());
		System.out.println("=========可用内存=========");
		System.out.println(getFreePhysicalMemory());
	}
	
	private static String getVbScriptPath(String fileName){
		String path = Monitor.class.getResource("").getPath()+fileName;
		return path.substring(1);
	}
	private static List<String> runVbScript(String fileName) {
		String filePath = getVbScriptPath(fileName);
        try {
            return ExecutorUtil.syncExecute("cscript.exe " + filePath+ " //NOLOGO");
        }
        catch (Throwable ex) {
            ex.printStackTrace();
            throw new Error(ex.getMessage());
        }
    }
	private static  List<DiskUsage> getDiskUsages() {

        List<DiskUsage> usages = new ArrayList<DiskUsage>();

        for(String line : runVbScript("disk.vbs")){
            if (line.startsWith("LogicalDisk:")) {
                line = line.replace("LogicalDisk:", "");
                String[] ss = line.split(",");
                if (ss[1] != null) {
                    long totalBytes = Long.parseLong(ss[1].trim());
                    long freeBytes = Long.parseLong(ss[2].trim());
                    DiskUsage usage = new DiskUsage(ss[0].trim(), totalBytes, freeBytes);
                    usages.add(usage);
                }
            }
        }

        return usages;
    }

	private static  List<Integer> getLoadPercentages() {
        List<Integer> percentages = new ArrayList<Integer>();

        for(String line : runVbScript("cpu.vbs")){
            if (line.startsWith("SysLoadPercentage:")) {
                line = line.replace("SysLoadPercentage:", "");
                if (line == null || "".equals(line.trim())) {
                    line = "0";
                }
                Integer percentage = Integer.valueOf(line.trim());
                percentages.add(percentage);
            }
        }

        return percentages;
    }

	private static  List<IORate> getDiskIORates() {
        List<IORate> rates = new ArrayList<IORate>();

        for(String line : runVbScript("io.vbs")){
            if(line.startsWith("DiskIO:")){
                String[] ss = line.replace("DiskIO:", "").split(",");
                if (ss[1] != null) {
                    IORate rate = new IORate(ss[0].trim(),
                            Long.valueOf(ss[1].trim()),
                            Long.valueOf(ss[2].trim()),
                            Long.valueOf(ss[3].trim()));
                    rates.add(rate);
                }
            }
        }
        return rates;
    }

	private static int getProcessCount() {
        for(String line : runVbScript("process.vbs")){
            if (line.startsWith("ProcessCount:")) {
                line = line.replace("ProcessCount:", "").trim();

                return Integer.valueOf(line);
            }
        }
        return -1;
    }

	private static long getTotalPhysicalMemory() {
        for(String line : runVbScript("memory.vbs")){
            if (line.startsWith("TotalPhysicalMemory:")) {
                line = line.replace("TotalPhysicalMemory:", "").trim();

                return Long.valueOf(line) * 1024;
            }
        }
        return -1;
	 }

	private static long getFreePhysicalMemory() {
        for(String line : runVbScript("memory.vbs")){
            if (line.startsWith("FreePhysicalMemory:")) {
                line = line.replace("FreePhysicalMemory:", "").trim();
                return Long.valueOf(line) * 1024;
            }
        }

        return -1;
    }
}

运行结果图:



这里主要取了CPU、内存等几个信息,大家利用WMI的API或者借助JSEDIT获取到更多的信息。下面列出了常用信息的类:
Win32_Processor                        // CPU 处理器

Win32_PhysicalMemory                   // 物理内存

Win32_Keyboard                         // 键盘

Win32_PointingDevice                   // 点输入设备,如鼠标

Win32_DiskDrive                        // 硬盘驱动器

Win32_CDROMDrive                       // 光盘驱动器

Win32_BaseBoard                        // 主板

Win32_BIOS                             // BIOS 芯片

Win32_ParallelPort                     // 并口

Win32_SerialPort                       // 串口

Win32_SoundDevice                      // 多媒体设置

Win32_USBController                    // USB 控制器

Win32_NetworkAdapter                   // 网络适配器

Win32_NetworkAdapterConfiguration      // 网络适配器设置

Win32_Printer                          // 打印机

Win32_PrinterConfiguration             // 打印机设置

Win32_PrintJob                         // 打印机任务

Win32_TCPIPPrinterPort                 // 打印机端口

Win32_POTSModem                        // MODEM

Win32_POTSModemToSerialPort            // MODEM 端口

Win32_DesktopMonitor                   // 显示器

Win32_VideoController                  // 显卡细节。

Win32_VideoSettings                    // 显卡支持的显示模式。

Win32_TimeZone                         // 时区

Win32_SystemDriver                     // 驱动程序

Win32_DiskPartition                    // 磁盘分区

Win32_LogicalDisk                      // 逻辑磁盘

Win32_LogicalMemoryConfiguration       // 逻辑内存配置

Win32_PageFile                         // 系统页文件信息

Win32_PageFileSetting                  // 页文件设置

Win32_BootConfiguration                // 系统启动配置

Win32_OperatingSystem                  // 操作系统信息

Win32_StartupCommand                   // 系统自动启动程序

Win32_Service                          // 系统安装的服务

Win32_Group                            // 系统管理组

Win32_GroupUser                        // 系统组帐号

Win32_UserAccount                      // 用户帐号

Win32_Process                          // 系统进程

Win32_Thread                           // 系统线程

Win32_Share                            // 共享

Win32_NetworkClient                    // 已安装的网络客户端

Win32_NetworkProtocol                  // 已安装的网络协议


展开阅读全文

没有更多推荐了,返回首页