GO語言使用gopsutil包進行機器信息採集

GO語言自己擁有極強的性能,很是適合作一些後端的數據採集管理以及運維繫統。git

其中會面臨對當前系統信息的採集,我在這裏使用的是GO的工具包 gopsutilgithub

貼出一套測試代碼,拋磚引玉:後端

import (
    "fmt"
    "time"

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

func collet() {
    v, _ := mem.VirtualMemory()
    c, _ := cpu.Info()
    cc, _ := cpu.Percent(time.Second, false)
    d, _ := disk.Usage("/")
    n, _ := host.Info()
    nv, _ := net.IOCounters(true)
    boottime, _ := host.BootTime()
    btime := time.Unix(int64(boottime), 0).Format("2006-01-02 15:04:05")

    fmt.Printf("        Mem       : %v MB  Free: %v MB Used:%v Usage:%f%%\n", v.Total/1024/1024, v.Available/1024/1024, v.Used/1024/1024, v.UsedPercent)
    if len(c) > 1 {
        for _, sub_cpu := range c {
            modelname := sub_cpu.ModelName
            cores := sub_cpu.Cores
            fmt.Printf("        CPU       : %v   %v cores \n", modelname, cores)
        }
    } else {
        sub_cpu := c[0]
        modelname := sub_cpu.ModelName
        cores := sub_cpu.Cores
        fmt.Printf("        CPU       : %v   %v cores \n", modelname, cores)

    }
    fmt.Printf("        Network: %v bytes / %v bytes\n", nv[0].BytesRecv, nv[0].BytesSent)
    fmt.Printf("        SystemBoot:%v\n", btime)
    fmt.Printf("        CPU Used    : used %f%% \n", cc[0])
    fmt.Printf("        HD        : %v GB  Free: %v GB Usage:%f%%\n", d.Total/1024/1024/1024, d.Free/1024/1024/1024, d.UsedPercent)
    fmt.Printf("        OS        : %v(%v)   %v  \n", n.Platform, n.PlatformFamily, n.PlatformVersion)
    fmt.Printf("        Hostname  : %v  \n", n.Hostname)
}

代碼中還包含CPU使用率採集,可用內存採集以及網絡數據包收發採集,目前網絡數據採集尚不穩定。網絡

相關文章
相關標籤/搜索