M.K.S
M.K.S

Reputation: 79

WMI from centos to remote host

In golang how i can do WMI based monitoring like Windows CPU, Windows memory, Disk monitoring using go library . Below code gives error package command-line-arguments imports github.com/StackExchange/wmi: build constraints exclude all Go files in /go/pkg/mod/github.com/!stack!exchange/[email protected]


import (
    "fmt"
    "github.com/StackExchange/wmi"
    "log"
)

// Define structs to hold the data retrieved from WMI queries
type Win32_Processor struct {
    Name          string
    NumberOfCores uint32
}

type Win32_LogicalDisk struct {
    Name               string
    Size               uint64
    FreeSpace          uint64
    FreeSpaceInPercent uint32
}

type Win32_OperatingSystem struct {
    TotalVisibleMemorySize uint64
    FreePhysicalMemory    uint64
}

func main() {
    // Set the address and authentication credentials for the remote host
    options := wmi.ConnectOptions{
        Username: "xyz", // Specify your username here
        Password: "1234567", // Specify your password here
        Host:     `172.16.2.2`, // Specify the remote host's address here
    }

    // Connect to the remote host
    wmi, err := wmi.DialServer(options)
    if err != nil {
        log.Fatalf("Failed to connect to remote host: %s", err)
    }

    var processors []Win32_Processor
    query := "SELECT * FROM Win32_Processor"
    err = wmi.QueryOverConnection(wmi, query, &processors)
    if err != nil {
        log.Fatalf("Error retrieving CPU info: %s", err)
    } else {
        fmt.Println("CPU Info:")
        for _, processor := range processors {
            fmt.Printf("  - Model: %s, Cores: %d\n", processor.Name, processor.NumberOfCores)
        }
    }

    var logicalDisks []Win32_LogicalDisk
    err = wmi.QueryOverConnection(wmi, "SELECT * FROM Win32_LogicalDisk WHERE DriveType=3", &logicalDisks)
    if err != nil {
        log.Fatalf("Error retrieving disk usage: %s", err)
    } else {
        for _, disk := range logicalDisks {
            fmt.Printf("Disk Usage - Drive: %s, Total: %d GB, Free: %d GB\n", disk.Name, disk.Size/(1024*1024*1024), disk.FreeSpace/(1024*1024*1024))
        }
    }

    var osInfo []Win32_OperatingSystem
    err = wmi.QueryOverConnection(wmi, "SELECT * FROM Win32_OperatingSystem", &osInfo)
    if err != nil {
        log.Fatalf("Error retrieving memory info: %s", err)
    } else {
        for _, os := range osInfo {
            totalMemoryGB := os.TotalVisibleMemorySize / (1024 * 1024)
            freeMemoryGB := os.FreePhysicalMemory / (1024 * 1024)
            fmt.Printf("Memory Info: Total: %d MB, Free: %d MB\n", totalMemoryGB, freeMemoryGB)
        }
    }
}``` 

Upvotes: 0

Views: 50

Answers (0)

Related Questions