123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- package util
- import (
- "github.com/shirou/gopsutil/cpu"
- "github.com/shirou/gopsutil/disk"
- "github.com/shirou/gopsutil/mem"
- "os/exec"
- "strconv"
- "strings"
- "time"
- )
- // GetCpuPercent cpu总占用率
- func GetCpuPercent() float64 {
- percent, _ := cpu.Percent(time.Second, false)
- return percent[0]
- }
- // GetMemoryPercent 内存总占用率
- func GetMemoryPercent() float64 {
- memory, _ := mem.SwapMemory()
- return memory.UsedPercent
- }
- // GetDiskPercent 磁盘总占用率
- func GetDiskPercent() float64 {
- parts, _ := disk.Partitions(true)
- diskInfo, _ := disk.Usage(parts[0].Mountpoint)
- return diskInfo.UsedPercent
- }
- // GetDiskUsed 解析 df 命令的输出
- // df -B1 /dev/vdb
- // Filesystem 1B-blocks Used Available Use% Mounted on
- // /dev/vdb 527371075584 16390344704 484120408064 4% /mnt/disk001
- func GetDiskUsed(filesystem string) (uint64, error) {
- cmd := exec.Command("df", "-B1", filesystem)
- output, err := cmd.CombinedOutput()
- if err != nil {
- return 0, err
- }
- lines := strings.Split(string(output), "\n")
- fields := strings.Fields(lines[1])
- parseUint, err := strconv.ParseUint(fields[2], 10, 64)
- if err != nil {
- return 0, err
- }
- return parseUint, nil
- }
- // GetDiskUsagePercent 获取磁盘使用率
- func GetDiskUsagePercent() (float64, error) {
- // 执行 df 命令获取磁盘使用情况
- cmd := exec.Command("df", "--total")
- output, err := cmd.Output()
- if err != nil {
- return 0.0, err
- }
- // 解析 df 命令输出,计算磁盘占比
- lines := strings.Split(string(output), "\n")
- for _, line := range lines[1:] {
- fields := strings.Fields(line)
- if len(fields) >= 6 && fields[0] == "total" {
- //filesystem := fields[0]
- total, _ := strconv.ParseFloat(strings.TrimSuffix(fields[1], "G"), 64)
- used, _ := strconv.ParseFloat(strings.TrimSuffix(fields[2], "G"), 64)
- usedPercent := (used / total) * 100
- //fmt.Printf("文件系统 %s 已使用 %.2f%%\n", filesystem, usedPercent)
- return usedPercent, err
- }
- }
- return 0.0, nil
- }
|