psutil是一个跨平台进程和系统监控的Python库,而gopsutil是其Go语言版本的实现。本文介绍了它的基本使用。
Go语言部署简单、性能好的特点非常适合做一些诸如采集系统信息和监控的服务,本文介绍的gopsutil库是知名Python库:psutil的一个Go语言版本的实现。

安装

  1. go get github.com/shirou/gopsutil

使用

CPU

采集CPU相关信息。

  1. import "github.com/shirou/gopsutil/cpu"
  2. // cpu info
  3. func getCpuInfo() {
  4. cpuInfos, err := cpu.Info()
  5. if err != nil {
  6. fmt.Printf("get cpu info failed, err:%v", err)
  7. }
  8. for _, ci := range cpuInfos {
  9. fmt.Println(ci)
  10. }
  11. // CPU使用率
  12. for {
  13. percent, _ := cpu.Percent(time.Second, false)
  14. fmt.Printf("cpu percent:%v\n", percent)
  15. }
  16. }

获取CPU负载信息:

  1. import "github.com/shirou/gopsutil/load"
  2. func getCpuLoad() {
  3. info, _ := load.Avg()
  4. fmt.Printf("%v\n", info)
  5. }

Memory

  1. import "github.com/shirou/gopsutil/mem"
  2. // mem info
  3. func getMemInfo() {
  4. memInfo, _ := mem.VirtualMemory()
  5. fmt.Printf("mem info:%v\n", memInfo)
  6. }

Host

  1. import "github.com/shirou/gopsutil/host"
  2. // host info
  3. func getHostInfo() {
  4. hInfo, _ := host.Info()
  5. fmt.Printf("host info:%v uptime:%v boottime:%v\n", hInfo, hInfo.Uptime, hInfo.BootTime)
  6. }

Disk

  1. import "github.com/shirou/gopsutil/disk"
  2. // disk info
  3. func getDiskInfo() {
  4. parts, err := disk.Partitions(true)
  5. if err != nil {
  6. fmt.Printf("get Partitions failed, err:%v\n", err)
  7. return
  8. }
  9. for _, part := range parts {
  10. fmt.Printf("part:%v\n", part.String())
  11. diskInfo, _ := disk.Usage(part.Mountpoint)
  12. fmt.Printf("disk info:used:%v free:%v\n", diskInfo.UsedPercent, diskInfo.Free)
  13. }
  14. ioStat, _ := disk.IOCounters()
  15. for k, v := range ioStat {
  16. fmt.Printf("%v:%v\n", k, v)
  17. }
  18. }

net IO

  1. import "github.com/shirou/gopsutil/net"
  2. func getNetInfo() {
  3. info, _ := net.IOCounters(true)
  4. for index, v := range info {
  5. fmt.Printf("%v:%v send:%v recv:%v\n", index, v, v.BytesSent, v.BytesRecv)
  6. }
  7. }

net

获取本机IP的两种方式

  1. func GetLocalIP() (ip string, err error) {
  2. addrs, err := net.InterfaceAddrs()
  3. if err != nil {
  4. return
  5. }
  6. for _, addr := range addrs {
  7. ipAddr, ok := addr.(*net.IPNet)
  8. if !ok {
  9. continue
  10. }
  11. if ipAddr.IP.IsLoopback() {
  12. continue
  13. }
  14. if !ipAddr.IP.IsGlobalUnicast() {
  15. continue
  16. }
  17. return ipAddr.IP.String(), nil
  18. }
  19. return
  20. }

或:

  1. // Get preferred outbound ip of this machine
  2. func GetOutboundIP() string {
  3. conn, err := net.Dial("udp", "8.8.8.8:80")
  4. if err != nil {
  5. log.Fatal(err)
  6. }
  7. defer conn.Close()
  8. localAddr := conn.LocalAddr().(*net.UDPAddr)
  9. fmt.Println(localAddr.String())
  10. return localAddr.IP.String()
  11. }