[关闭]
@orangleliu 2016-09-23T02:59:57.000000Z 字数 1600 阅读 1643

OpenResty 查询Linux主机流量

nginx


事情是这样的,我买了vps,每个月流量不是很多,我就想看看用了多少流量。但是我又不想去主机的后台查,我还不想用那些监控软件,优点小题大做了,于是我就想弄个脚本,然后openresty读出来,我没事看眼。

获取流量数据

vps的操作系统是Centos6,用shell命令或者是读取某个文件获取

可以读下面两个文件,venet0是网卡名

  1. [root@CT1391 ~]# cat /sys/class/net/venet0/statistics/rx_bytes
  2. 2300558468
  3. [root@CT1391 ~]# cat /sys/class/net/venet0/statistics/tx_bytes
  4. 2111210364

lua脚本

lua读取网卡数据并显示,还需要一个每月清零的动作(一般都是重启网卡,没有找到其他法子,麻烦点就是每个月初记录下来,自己计算当月)。

nginx配置部分

  1. server {
  2. listen 80;
  3. server_name localhost;
  4. lua_code_cache off;
  5. location /status {
  6. default_type text/html;
  7. charset utf-8;
  8. content_by_lua_file /etc/nginx/lua/tstatus.lua;
  9. }
  10. }

tstatus.lua

  1. local io = require "io"
  2. local math = require "math"
  3. -- 改成自己的网卡和总量
  4. local fname = "eth2"
  5. local month_flow = "250G"
  6. local function get_value(v)
  7. local file = io.open("/sys/class/net/"..fname.."/statistics/"..v.."_bytes")
  8. local value = file:read()
  9. file:close()
  10. return value
  11. end
  12. local function round(num, dip)
  13. return tonumber(string.format("%."..(dip or 0).."f", num))
  14. end
  15. local function flow_format(v)
  16. local v = tonumber(v)
  17. if v < 1024 then
  18. return v.."byte"
  19. elseif v < 1024*1024 then
  20. return round(v/1024.0, 2).."Kb"
  21. elseif v < 1024*1024*1024 then
  22. return round(v/1024.0/1024.0, 2).."M"
  23. elseif v < 1024*1024*1024*1024 then
  24. return round(v/1024.0/1024.0/1024.0, 2).."G"
  25. end
  26. end
  27. local rx = get_value("rx")
  28. local tx = get_value("tx")
  29. local total = rx + tx
  30. ngx.say("您本月可用的总流量是"..month_flow.."<br>")
  31. ngx.say("RX:"..rx.." -> "..flow_format(rx).."<br>")
  32. ngx.say("TX:"..tx.." -> "..flow_format(tx).."<br>")
  33. ngx.say("Total:"..total.." -> "..flow_format(total))
  34. ngx.exit(200)

测试

  1. [root@orangleliu lzz]# curl http://192.168.59.104/status
  2. 您本月可用的总流量是250G<br>
  3. RX:3412800496 -> 3.18G<br>
  4. TX:61802720 -> 58.94M<br>
  5. Total:3474603216 -> 3.24G

先这么着,下个月1号先把累计的流量记录下来,弄个持久化和计算当月的流程吧。。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注