u_disk.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package util
  2. import (
  3. "os/exec"
  4. "strconv"
  5. "strings"
  6. )
  7. // GetDiskUsed 解析 df 命令的输出
  8. // df -B1 /dev/vdb
  9. // Filesystem 1B-blocks Used Available Use% Mounted on
  10. // /dev/vdb 527371075584 16390344704 484120408064 4% /mnt/disk001
  11. func GetDiskUsed(filesystem string) (uint64, error) {
  12. cmd := exec.Command("df", "-B1", filesystem)
  13. output, err := cmd.CombinedOutput()
  14. if err != nil {
  15. return 0, err
  16. }
  17. lines := strings.Split(string(output), "\n")
  18. fields := strings.Fields(lines[1])
  19. parseUint, err := strconv.ParseUint(fields[2], 10, 64)
  20. if err != nil {
  21. return 0, err
  22. }
  23. return parseUint, nil
  24. }
  25. // GetDiskUsagePercent 获取磁盘使用率
  26. func GetDiskUsagePercent() (float64, error) {
  27. // 执行 df 命令获取磁盘使用情况
  28. cmd := exec.Command("df", "--total")
  29. output, err := cmd.Output()
  30. if err != nil {
  31. return 0.0, err
  32. }
  33. // 解析 df 命令输出,计算磁盘占比
  34. lines := strings.Split(string(output), "\n")
  35. for _, line := range lines[1:] {
  36. fields := strings.Fields(line)
  37. if len(fields) >= 6 && fields[0] == "total" {
  38. //filesystem := fields[0]
  39. total, _ := strconv.ParseFloat(strings.TrimSuffix(fields[1], "G"), 64)
  40. used, _ := strconv.ParseFloat(strings.TrimSuffix(fields[2], "G"), 64)
  41. usedPercent := (used / total) * 100
  42. //fmt.Printf("文件系统 %s 已使用 %.2f%%\n", filesystem, usedPercent)
  43. return usedPercent, err
  44. }
  45. }
  46. return 0.0, nil
  47. }