每秒计算一次网卡出口带宽,并保存到指定文件,用于其他程序,如:php、shell读取带宽
那么如果是shell ,为啥不写在shell里面呢?答案是可以的,只是场景不一样,这里用go实现读取一次,然后其他程序可以多任务执行,直接使用结果。
package main
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"os/exec"
"strings"
"time"
)
func main() {
for {
var stdOut, stdErr bytes.Buffer
cmd := exec.Command("sh", "-c","dstat -n 1 1 | awk 'END {print}' | awk '{print $2}'")
cmd.Stdout = &stdOut
cmd.Stderr = &stdErr
err := cmd.Run();
if err!=nil {
fmt.Println(cmd.Stderr,err.Error())
os.Exit(1)
}
fmt.Print(cmd.Stdout)
path := "/workspace/tmp/network-speed.data"
content := stdOut.String()
content = strings.Replace(content, "\n", "", -1)
if content=="0" {
time.Sleep(1*time.Second)
continue
}
if strings.Contains(content, "B") {
content = "1"
} else if strings.Contains(content, "k"){
content = "1"
} else if strings.Contains(content, "M"){
content = strings.Replace(content,"M","",-1)
}
err = ioutil.WriteFile(path, []byte(content), 0666)
if err != nil {
panic(err)
time.Sleep(1*time.Second)
}
}
}
网友评论