欢迎光临
我们一直在努力

go语言学习例子No.23–获取系统信息

其实有包可以实现 https://github.com/shirou/gopsutil

下面是获取硬盘信息

知识点:

格式化打印小数点

awk处理并打印最后一行

strings.Fields分割空白字符并保存被切片

package main

import (
	"fmt"
	"os/exec"
	"strconv"
	"strings"
)

func main() {
	total, used := get_hhd()
	fmt.Printf("total: %.2fG\nused: %.2fG\n", float64(total)/1024, float64(used)/1024)
}

func get_hhd() (int, int) {
	cmd := exec.Command("bash", "-c", "df -Tlm --total -t ext4 -t ext3 -t ext2 -t reiserfs -t jfs -t ntfs -t fat32 -t btrfs -t fuseblk -t zfs -t simfs -t xfs | awk 'END {print $3,$4}'")
	out, _ := cmd.Output()
	r := strings.Fields(string(out))
	total, _ := strconv.Atoi(r[0])
	used, _ := strconv.Atoi(r[1])

	return total, used

}
cat /proc/meminfo | sed -n '1p;3p;15p;16p'
输出内存信息
package main

import (
	"fmt"
	"os/exec"
	"strconv"
	"strings"
)

func main() {

	MemTotal, MemAvailable, SwapTotal, SwapFree := get_mem()
	fmt.Printf("MemTotal: %.1fG\nMemAvailable: %.1fG\nSwapTotal: %.1fG\nSwapFree: %.1fG\n", float64(MemTotal)/1024/1024, float64(MemAvailable)/1024/1024, float64(SwapTotal)/1024/1024, float64(SwapFree)/1024/1024)
}

func get_mem() (int, int, int, int) {
	cmd := exec.Command("bash", "-c", "cat /proc/meminfo | sed -n '1p;3p;15p;16p'")
	out, _ := cmd.Output()
	r := strings.Fields(string(out))
	MemTotal, _ := strconv.Atoi(r[1])
	MemAvailable, _ := strconv.Atoi(r[4])
	SwapTotal, _ := strconv.Atoi(r[7])
	SwapFree, _ := strconv.Atoi(r[10])

	return MemTotal, MemAvailable, SwapTotal, SwapFree

}
cat <(grep 'cpu ' /proc/stat) <(sleep 1 && grep 'cpu ' /proc/stat) | awk -v RS="" '{printf "%d\n", ($13-$2+$15-$4)*100/($13-$2+$15-$4+$16-$5)}'
cpu使用率
package main

import (
	"fmt"
	"os/exec"
)

func main() {
	fmt.Println("cpu: " + get_cpu() + "% used.")
}

func get_cpu() string {
	cmd := exec.Command("bash", "-c", `cat <(grep 'cpu ' /proc/stat) <(sleep 1 && grep 'cpu ' /proc/stat) | awk -v RS="" '{printf "%d", ($13-$2+$15-$4)*100/($13-$2+$15-$4+$16-$5)}'`)
	out, _ := cmd.Output()

	return string(out)

}

用上面的包来实现就简单了

package main

import (
	"fmt"
	"github.com/shirou/gopsutil/cpu"
	"github.com/shirou/gopsutil/disk"
	"github.com/shirou/gopsutil/mem"
	"github.com/shirou/gopsutil/net"
	"time"
)


func main() {
	m, _ := mem.VirtualMemory()
	c,_:=cpu.Percent(time.Second,false)
	d,_:=disk.Usage("/")
	n, _ := net.IOCounters(true)

	fmt.Printf("%v: Totalsend:%.2f Totalrecv:%.2f\n", n[1].Name, toG(n[1].BytesSent), toG(n[1].BytesRecv))


	// almost every return value is a struct
	fmt.Printf("memory: %.2f%% used %.2fG/%.2fG\n", m.UsedPercent,toG(m.Available), toG(m.Total))

	// convert to JSON. String() is also implemented
	fmt.Printf("cpu: %.2f%% used\n",c[0])
	fmt.Printf("disk: %.2f%% used %.2fG/%.2fG\n",d.UsedPercent,toG(d.Free),toG(d.Total))
}

func toG(i uint64) float64{
	return float64(i)/1024/1024/1024
}

下次用ajax每秒刷新一下显示在网页上

已经有人写好了我们可以参考下研究下 https://github.com/ylqjgm/ServerStatus

package main

import (
	"fmt"
	"time"

	"github.com/shirou/gopsutil/cpu"
	"github.com/shirou/gopsutil/disk"
	"github.com/shirou/gopsutil/mem"
	"github.com/shirou/gopsutil/net"
)

func main() {
	getstatus()
	for {
		time.Sleep(time.Second)
		getNetSpeed()
	}

}

func toG(i uint64) float64 {
	return float64(i) / 1024 / 1024 / 1024
}
func toKB(i uint64) float64 {
	return float64(i) / 1024
}
func toMB(i uint64) float64 {
	return float64(i) / 1024 / 1024
}
func getNetSpeed() {
	// 读取所有网卡网速
	Net, _ := net.IOCounters(true)
	// 定义网速保存变量
	var rx, tx uint64
	// 循环网络信息
	for _, nv := range Net {
		// 去除多余信息
		if "eth0" == nv.Name {
			// 加上网速信息
			rx += nv.BytesRecv
			tx += nv.BytesSent
		}
	}
	// 暂停一秒
	time.Sleep(time.Second)
	// 重新读取网络信息
	Net, _ = net.IOCounters(true)
	// 网络信息保存变量
	var rx2, tx2 uint64
	// 循环网络信息
	for _, nv := range Net {
		// 去除多余信息
		if "eth0" == nv.Name {
			// 加上网速信息
			rx2 += nv.BytesRecv
			tx2 += nv.BytesSent
		}
	}
	// 两次相见
	if toKB(rx2-rx) > 1024 || toKB(tx2-tx) > 1024 {
		fmt.Printf("\r下载:%.2f MB/s 上传: %.2f MB/s", toMB(rx2-rx), toMB(tx2-tx))
	} else {
		fmt.Printf("\r下载:%.2f KB/s 上传: %.2f KB/s", toKB(rx2-rx), toKB(tx2-tx))
	}

}
func getstatus() {
	m, _ := mem.VirtualMemory()
	c, _ := cpu.Percent(time.Second, false)
	d, _ := disk.Usage("/")
	n, _ := net.IOCounters(true)

	fmt.Printf("%v: Totalsend:%.2fG Totalrecv:%.2fG\n", n[1].Name, toG(n[1].BytesSent), toG(n[1].BytesRecv))

	// almost every return value is a struct
	fmt.Printf("memory: %.2f%% used %.2fG/%.2fG\n", m.UsedPercent, toG(m.Available), toG(m.Total))

	// convert to JSON. String() is also implemented
	fmt.Printf("cpu: %.2f%% used\n", c[0])
	fmt.Printf("disk: %.2f%% used %.2fG/%.2fG\n", d.UsedPercent, toG(d.Free), toG(d.Total))
}

上面加了个网速实时刷新

 收藏 (0) 打赏

您可以选择一种方式赞助本站

支付宝扫一扫赞助

微信钱包扫描赞助

未经允许不得转载:家里蹲的狐狸 » go语言学习例子No.23–获取系统信息

分享到: 生成海报
avatar

热门文章

  • 评论 抢沙发

    • QQ号
    • 昵称 (必填)
    • 邮箱 (必填)
    • 网址

    登录

    忘记密码 ?

    切换登录

    注册

    我们将发送一封验证邮件至你的邮箱, 请正确填写以完成账号注册和激活