Golang初学:获取主机的磁盘空间信息,gopsutil

go version go1.22.1 windows/amd64

Windows 11 + amd64

x86_64 x86_64 GNU/Linux

---

 

序章

怎么获取磁盘空间信息呢?总量、剩余等。包括,Windows、Linux主机等。

使用标准库(os、fs、syscall 等)可以吗?可以,网上可以找到 获取 Linux 系统的相关信息,不过,要获取 Windows 的就比较麻烦了。

咨询了 通义千问,可以使用 github.com/shirou/gopsutil/disk 来获取相关信息。

 

获取磁盘空间剩余信息,对于需要使用 磁盘存储文件是有用的。

不过,一般磁盘空间会有专门的工具监控的。

--

另外还想获取 主机总内存信息,真难!通过标准库获取没成功。一般来说,golang 程序是运行在 容器中,容器启动时就已经限制了内存了,是否获取主机内存,获取用处也不大。

 

使用 第三方模块 获取磁盘信息

go get

进入项目目录,获取:ben发布于博客园

> go get -u github.com/shirou/gopsutil/disk
go: downloading github.com/shirou/gopsutil v2.21.11+incompatible
go: downloading github.com/yusufpapurcu/wmi v1.2.4
go: downloading github.com/go-ole/go-ole v1.2.6
go: downloading github.com/go-ole/go-ole v1.3.0
go: added github.com/go-ole/go-ole v1.3.0
go: added github.com/shirou/gopsutil v2.21.11+incompatible
go: added github.com/yusufpapurcu/wmi v1.2.4

得到了 github.com/shirou/gopsutil v2.21.11+incompatible // indirect 及其依赖包。

 

使用:Windows、Linux

上代码:

// Disk info
func GetDiskInfo() {
	// github.com/shirou/gopsutil/disk
	fmt.Println("using github.com/shirou/gopsutil/disk")
    // #1 获取分区
	parts, err := disk.Partitions(true)
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println(parts)
	fmt.Println("type=", reflect.TypeOf(parts), "size=", len(parts))

	for _, part := range parts {
        // #2 Linux 特别处理
		// don't use Yoda conditions (ST1017)
		if runtime.GOOS == "linux" && part.Mountpoint != "/" {
			// Ignoring
			continue
		}

        // #3 获取挂载点的使用信息
		usage, err := disk.Usage((part.Mountpoint))
		if err != nil {
			fmt.Println(err)
			continue
		}

        // #4 打印某挂载点的磁盘使用
		fmt.Printf("Part: %s\n", part.Device)
		fmt.Printf("Total: %d bytes\n", usage.Total)
		fmt.Printf("Free: %d bytes\n", usage.Free)
		fmt.Printf("Usedd: %d bytes\n", usage.Used)
		fmt.Println()
	}

}

 

测试结果

Windows:

using github.com/shirou/gopsutil/disk
[{"device":"C:","mountpoint":"C:","fstype":"NTFS","opts":"rw.compress"} {"device":"D:","mountpoint":"D:","fstype":"NTFS","opts":"rw.compress"}]
type= []disk.PartitionStat size= 2
Part: C:
Total: 127986036736 bytes
Free: 62972157952 bytes
Usedd: 65013878784 bytes

Part: D:
Total: 126805340160 bytes
Free: 61864873984 bytes
Usedd: 64940466176 bytes

只有 2个 挂载点,输出正确。ben发布于博客园

 

Linux(ECS):

没有代码中的 #2 时,打印了 36 条信息,其中包括不少 cgroup的,但空间为 0。

经过特别处理——只输出 挂载点(/)的,如下:

type= []disk.PartitionStat size= 36
Part: /dev/vda1
Total: 42090295296 bytes
Free: 30521069568 bytes
Usedd: 9619828736 bytes

注,上面的 /dev/vda1 挂在到了 /。可以使用 df -h 查看更多挂载点信息,不过,df 命令查询到的 不包括 一些 cgroup 的挂载点。

 

可能的其它方式

既然 df -h 可以获取 Linux 磁盘信息,是否可以通过 执行命令来获取呢?

cmd := exec.Command("df -h")

TODO

 

END.

ben发布于博客园

本文链接:

https://www.cnblogs.com/luo630/p/18208289

ben发布于博客园

参考资料

1、通义千问

https://tongyi.aliyun.com/qianwen/

2、

 

ben发布于博客园

ben发布于博客园

 

posted @ 2024-05-23 14:14  快乐的二当家815  阅读(166)  评论(0编辑  收藏  举报