更新、更全的《Go從入門到放棄》的更新網站,更有python、go、人工智能教學等着你:http://www.javashuo.com/article/p-mxrjjcnn-hn.htmlpython
psutil
是一個跨平臺進程和系統監控的Python庫,而gopsutil
是其Go語言版本的實現。本文介紹了它的基本使用。git
Go語言部署簡單、性能好的特色很是適合作一些諸如採集系統信息和監控的服務,本文介紹的gopsutil庫是知名Python庫:psutil的一個Go語言版本的實現。github
go get github.com/shirou/gopsutil
採集CPU相關信息。bash
import "github.com/shirou/gopsutil/cpu" // cpu info func getCpuInfo() { cpuInfos, err := cpu.Info() if err != nil { fmt.Printf("get cpu info failed, err:%v", err) } for _, ci := range cpuInfos { fmt.Println(ci) } // CPU使用率 for { percent, _ := cpu.Percent(time.Second, false) fmt.Printf("cpu percent:%v\n", percent) } }
獲取CPU負載信息:oop
import "github.com/shirou/gopsutil/load" func getCpuLoad() { info, _ := load.Avg() fmt.Printf("%v\n", info) }
import "github.com/shirou/gopsutil/mem" // mem info func getMemInfo() { memInfo, _ := mem.VirtualMemory() fmt.Printf("mem info:%v\n", memInfo) }
import "github.com/shirou/gopsutil/host" // host info func getHostInfo() { hInfo, _ := host.Info() fmt.Printf("host info:%v uptime:%v boottime:%v\n", hInfo, hInfo.Uptime, hInfo.BootTime) }
import "github.com/shirou/gopsutil/disk" // disk info func getDiskInfo() { parts, err := disk.Partitions(true) if err != nil { fmt.Printf("get Partitions failed, err:%v\n", err) return } for _, part := range parts { fmt.Printf("part:%v\n", part.String()) diskInfo, _ := disk.Usage(part.Mountpoint) fmt.Printf("disk info:used:%v free:%v\n", diskInfo.UsedPercent, diskInfo.Free) } ioStat, _ := disk.IOCounters() for k, v := range ioStat { fmt.Printf("%v:%v\n", k, v) } }
import "github.com/shirou/gopsutil/net" func getNetInfo() { info, _ := net.IOCounters(true) for index, v := range info { fmt.Printf("%v:%v send:%v recv:%v\n", index, v, v.BytesSent, v.BytesRecv) } }
func GetLocalIP() (ip string, err error) { addrs, err := net.InterfaceAddrs() if err != nil { return } for _, addr := range addrs { ipAddr, ok := addr.(*net.IPNet) if !ok { continue } if ipAddr.IP.IsLoopback() { continue } if !ipAddr.IP.IsGlobalUnicast() { continue } return ipAddr.IP.String(), nil } return }
或:性能
// Get preferred outbound ip of this machine func GetOutboundIP() string { conn, err := net.Dial("udp", "8.8.8.8:80") if err != nil { log.Fatal(err) } defer conn.Close() localAddr := conn.LocalAddr().(*net.UDPAddr) fmt.Println(localAddr.String()) return localAddr.IP.String() }