第三方包下载

$ github.com/shirou/gopsutil

获取内存方面的信息

package main

import (
"fmt"
"github.com/shirou/gopsutil/mem"
) func main() {
v, _ := mem.VirtualMemory()
fmt.Println(v)
}

  

total // 内存大小
available // 闲置可用内存
used // 已使用内存
usedPercent // 已使用百分比

  

获取cpu方面的信息

package main

import (
"fmt"
"github.com/shirou/gopsutil/cpu"
) func main() { res, err := cpu.Times(false) // false是展示全部总和 true是分布展示
if err != nil {
fmt.Println(err)
}
fmt.Println(res)
}
cpu // 具体cpu名称
user // 用户已使用cpu数值
system // 系统已使用cpu数值
idle // 闲置的cpu数值
.Total // 获取总cpu数值

  

CPU

采集CPU相关信息。

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负载信息:

import "github.com/shirou/gopsutil/load"

func getCpuLoad() {
info, _ := load.Avg()
fmt.Printf("%v\n", info)
}

  

Host

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)
}

  

Disk

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)
}
}

  

net IO

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)
}
}

  

net

获取本机IP的两种方式

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()
}