xichen
xichen

Reputation: 361

How to get system information in Go?

Can anyone recommend a module which can be used to get system information, like Python's psutil?

When I tried >go get github.com/golang/sys get 'sys', I received the following:

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

This my system environment:

# 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

Upvotes: 5

Views: 22785

Answers (3)

hhsm95
hhsm95

Reputation: 311

This is a simple Windows example to extract the Hostname, Platform, CPU model, total RAM and disk capacity. First install the module:

go get github.com/shirou/gopsutil 

I had problems with the installation and I also had to install:

go get github.com/StackExchange/wmi

Now run this code:

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)

}

Upvotes: 8

Jeff M
Jeff M

Reputation: 375

I know this is an old post, but putting this out there for others who can benefit.

exactly what you're looking for here:

https://github.com/shirou/gopsutil

Upvotes: 4

VonC
VonC

Reputation: 1324208

You would need actually to do (following godoc):

go get golang.org/x/sys/unix
# or
go get golang.org/x/sys/windows
# or
go get golang.org/x/sys/plan9

(depending on your OS)

Upvotes: 5

Related Questions