需求是这样的,想远程执行这个命令,返回各个硬盘分区的剩余空间的大小,当然,剩余空间太小可能就要处理了。
01 | package main |
02 |
03 | import ( |
04 | "fmt" |
05 | "syscall" |
06 | // "strings" |
07 | gofstab "github.com/deniswernert/go-fstab" |
08 | ) |
09 |
10 | type DiskStatus struct { |
11 | All uint64 `json: "all" ` |
12 | Used uint64 `json: "used" ` |
13 | Free uint64 `json: "free" ` |
14 | } |
15 | const ( |
16 | B = 1 |
17 | KB = 1024 * B |
18 | MB = 1024 * KB |
19 | GB = 1024 * MB |
20 | ) |
21 | // disk usage of path/disk |
22 | func DiskUsage(path string) (disk DiskStatus) { |
23 | fs := syscall.Statfs_t{} |
24 | err := syscall.Statfs(path, &fs) |
25 | if err != nil { |
26 | return |
27 | } |
28 | disk.All = fs.Blocks * uint64(fs.Bsize) |
29 | disk.Free = fs.Bfree * uint64(fs.Bsize) |
30 | disk.Used = disk.All - disk.Free |
31 | return |
32 | } |
33 | func main(){ |
34 | mounts ,_ :=gofstab.ParseSystem() |
35 | |
36 | for _,val := range mounts{ |
37 | //fmt.Printf("%v\n",val.File) |
38 | if val.File == "swap" ||val.File == "/dev/shm" ||val.File == "/dev/pts" ||val.File == "/proc" ||val.File == "/sys" { |
39 | continue |
40 | } |
41 | disk := DiskUsage(val.File) |
42 | //fmt.Printf("All: %.2f GB\n", float64(disk.All)/float64(GB)) |
43 | //fmt.Printf("Used: %.2f GB\n", float64(disk.Used)/float64(GB)) |
44 | //fmt.Printf("Free: %.2f GB\n", float64(disk.Free)/float64(GB)) |
45 | diskall:=float64(disk.All)/float64(GB) |
46 | diskfree:= float64(disk.Free)/float64(GB) |
47 | |
48 | dfpercent:=float64(diskfree/diskall) |
49 | fmt.Printf( "%s %.2f%%\n" ,val.File, dfpercent*100) |
50 | } |
51 | } |