0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ギガ数えてみた

Last updated at Posted at 2025-10-04

最近の若者言葉で通信量のことをギガというらしいです。

インターネット側のifのinとoutをsnmpで拾ってsqlite3に入れます。

#!/bin/sh

LASTFILE="/tmp/intif.last"

# arge1 mib
IN=`bsnmpwalk -o quiet -s 10.0.1.1 1.3.6.1.2.1.2.2.1.10.6`
OUT=`bsnmpwalk -o quiet -s 10.0.1.1 1.3.6.1.2.1.2.2.1.16.6`

if [ -e  ${LASTFILE} ]; then

set `cat ${LASTFILE}`

shift 0
LAST=$1
if [ ${IN} -lt ${LAST} ]; then
INB=$((4294967295 - ${LAST} + 1 + ${IN}))
else
INB=$((${IN} - ${LAST}))
fi

shift 1
LAST=$1
if [ ${OUT} -lt ${LAST} ]; then
OUTB=$((4294967295 - ${LAST} + 1 + ${OUT}))
else
OUTB=$((${OUT} - ${LAST}))
fi

/usr/local/bin/sqlite3 /tmp/net.db "insert into intif(inb, outb) values("${INB},${OUTB}")"
fi

echo "${IN} ${OUT}" > ${LASTFILE}

カウンターは32Bitなので0 -> 4294967295 -> 0 -> 4294967295を繰り返します。

これをcronで5分おきに実行します。

テーブルは以下のように作ります。

  db.execute_batch("create table intif(date default CURRENT_DATE, time default CURRENT_TIME, inb INTEGER, outb INTEGER)")

当日分のギガを集計してjsonを作ります。

#!/usr/local/bin/mruby

db = SQLite3::Database.new("/tmp/net.db")

val = Array.new

# get last recode by JST
sel = "select sum(inb)/(1024*1024),sum(outb)/(1024*1024) from intif where date(datetime(date,time,'localtime'))='" + Time.now.to_s[0,10] + "'"

db.execute(sel) do |row, fields|
val[0] = row[0]
val[1] = row[1]
val[2] = val[0] + val[1]
end
if val.length == 0 then
val[0] = ""
val[1] = ""
val[2] = ""
end

print "{ \"a\": "
print "\"Total: " + val[2].to_s + "M\", "
print "\"b\": { \"c\": \"In: " + val[0].to_s + "M<br>Out: " + val[1].to_s
print "M\"} }"

これをMagic-Gridで表示します。

image.png

chart.jsでも書いてみました。

jsonを作るcgiは以下のようにしました。

#!/usr/local/bin/mruby

db = SQLite3::Database.new('/tmp/net.db')

val = Array.new

t = "intif"

i = 0
sel = "select date(datetime(date,time,'localtime')),sum(inb)/(1024*1024),sum(outb)/(1024*1024) from " + t + " group by date(datetime(date, time, 'localtime'))"
db.execute(sel) do |row, fields|
  val[i] = row
  i = i + 1
end

print "Content-type: text/html\n\n"

if i > 10
j = i - 10
else
j = 0
end
first = 1
print "["
while j < i - 1 do
  if first == 1
    first = 0
  else
    print ","
  end
  print "{"
  print "\"date\":\"" + val[j][0][5, 5]
  print "\",\"inb\":" + val[j][1].round(2).to_s
  print ",\"outb\":" + val[j][2].round(2).to_s
  print "}"
  j = j + 1
end
print "]"

いつものようにchart.js v2で書いてみます。

filename (1).png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?