go获取服务器信息(主机、CPU、内存、硬盘)
使用github.com/shirou/gopsutil库来获取机器信息,您可以按照以下步骤进行:
1、安装相关库
go get github.com/shirou/gopsutil
go get github.com/yusufpapurcu/wmi
go get github.com/shirou/gopsutil/v3/disk
2、代码实现
package main
import (
"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)
}
}