使用github.com/shirou/gopsutil
库来获取机器信息,您可以按照以下步骤进行:
1、安装相关库
go get github.com/shirou/gopsutilgo get github.com/yusufpapurcu/wmigo get github.com/shirou/gopsutil/v3/disk
2、代码实现
package mainimport ("fmt""github.com/shirou/gopsutil/cpu""github.com/shirou/gopsutil/host""github.com/shirou/gopsutil/mem""github.com/shirou/gopsutil/v3/disk")func main() {// 获取主机信息hostInfo, err := host.Info()if err != nil {fmt.Printf("Failed to get host info: %v", err)return}fmt.Printf("Host info: %+v\n", hostInfo)// 获取CPU信息cpuInfo, err := cpu.Info()if err != nil {fmt.Printf("Failed to get CPU info: %v", err)return}fmt.Printf("CPU info: %+v\n", cpuInfo)// 获取内存信息memInfo, err := mem.VirtualMemory()if err != nil {fmt.Printf("Failed to get memory info: %v", err)return}fmt.Printf("Memory info: %+v\n", memInfo)// 获取磁盘分区信息diskPartitions, err := disk.Partitions(true)if err != nil {fmt.Printf("Failed to get disk partitions: %v", err)return}fmt.Printf("Disk partitions: %+v\n", diskPartitions)for _, partition := range diskPartitions {// 获取每个磁盘分区的使用情况usage, err := disk.Usage(partition.Mountpoint)if err != nil {fmt.Printf("Failed to get disk usage for %s: %v", partition.Mountpoint, err)continue}fmt.Printf("%s usage: %+v\n", partition.Mountpoint, usage)}}
来源地址:https://blog.csdn.net/qq_21275565/article/details/131297086