Go中如何获取系统信息?

xic*_*hen 2 go

谁能推荐一个可用于获取系统信息的模块,例如 Python 的psutil

当我尝试时>go get github.com/golang/sys get 'sys',我收到以下信息:

Report Error:
package github.com/golang/sys
        imports github.com/golang/sys
        imports github.com/golang/sys: no buildable Go source files in D:\go_source\src\github.com\golang\sys
Run Code Online (Sandbox Code Playgroud)

这是我的系统环境:

# native compiler windows amd64

GOROOT=D:\Go
#GOBIN=
GOARCH=amd64
GOOS=windows
CGO_ENABLED=1

PATH=c:\mingw64\bin;%GOROOT%\bin;%PATH%

LITEIDE_GDB=gdb64
LITEIDE_MAKE=mingw32-make
LITEIDE_TERM=%COMSPEC%
LITEIDE_TERMARGS=
LITEIDE_EXEC=%COMSPEC%
LITEIDE_EXECOPT=/C
Run Code Online (Sandbox Code Playgroud)

小智 7

这是一个简单的Windows示例,用于提取主机名、平台、CPU 型号、总 RAM 和磁盘容量。首先安装模块:

go get github.com/shirou/gopsutil 
Run Code Online (Sandbox Code Playgroud)

我在安装时遇到了问题,我还必须安装:

go get github.com/StackExchange/wmi
Run Code Online (Sandbox Code Playgroud)

现在运行这段代码:

package main

import (
    "fmt"

    "github.com/shirou/gopsutil/cpu"
    "github.com/shirou/gopsutil/disk"
    "github.com/shirou/gopsutil/host"
    "github.com/shirou/gopsutil/mem"
)

// SysInfo saves the basic system information
type SysInfo struct {
    Hostname string `bson:hostname`
    Platform string `bson:platform`
    CPU      string `bson:cpu`
    RAM      uint64 `bson:ram`
    Disk     uint64 `bson:disk`
}

func main() {
    hostStat, _ := host.Info()
    cpuStat, _ := cpu.Info()
    vmStat, _ := mem.VirtualMemory()
    diskStat, _ := disk.Usage("\\") // If you're in Unix change this "\\" for "/"

    info := new(SysInfo)

    info.Hostname = hostStat.Hostname
    info.Platform = hostStat.Platform
    info.CPU = cpuStat[0].ModelName
    info.RAM = vmStat.Total / 1024 / 1024
    info.Disk = diskStat.Total / 1024 / 1024

    fmt.Printf("%+v\n", info)

}
Run Code Online (Sandbox Code Playgroud)


Von*_*onC 5

您实际上需要做(遵循 godoc):

go get golang.org/x/sys/unix
# or
go get golang.org/x/sys/windows
# or
go get golang.org/x/sys/plan9
Run Code Online (Sandbox Code Playgroud)

(取决于您的操作系统)