Scripting ntopng with Lua

Posted · Add Comment

The ntopng architecture is divided in three layers:

  • Ingress layer (flow or packet capture).
  • Monitoring engine: the ntopng core.
  • Lua scripting engine
  • Data export layer (via web, syslog or log files).

ntopng

Thanks to the scripting engine, ntopng is fully scriptable. This means that via Lua you can extract the monitoring information and report it into HTML pages or export it to third party applications. The ntopng Lua API is pretty simple it consists of two classes, ntop and interface. ntopng also comes with some example scripts that highlight the main API functionalities, although the best demo is perhaps the ntopng web interface. The embedded HTTP(S) web server is responsible for parsing GET/POST parameters (if any) and places them into the _GET global scripts variable so that they can be accessed from Lua. Scripts are also used in ntopng to execute periodic actions such as dumping throughput and top talkers to disk. ntopng is fully reentrant thus means that multiple scripts can be safely executed simultaneously.

An example of Lua scripting is the following.

--
-- (C) 2013 - ntop.org
--
dirs = ntop.getDirs()
package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path

require "lua_utils"

sendHTTPHeader('text/html')

interface.find(ifname)
ifstats = interface.getStats()

type = _GET["type"]

if((type == nil) or (type == "size")) then
what = ifstats["pktSizeDistribution"]
end

local pkt_distribution = {
['upTo64'] = '<= 64',
['upTo128'] = '64 <= 128',
['upTo256'] = '128 <= 256',
['upTo512'] = '256 <= 512',
['upTo1024'] = '512 <= 1024',
['upTo1518'] = '1024 <= 1518',
['upTo2500'] = '1518 <= 2500',
['upTo6500'] = '2500 <= 6500',
['upTo9000'] = '6500 <= 9000', ['above9000'] = '> 9000'
}

tot = 0
for key, value in pairs(what) do
tot = tot + value
end

threshold = (tot * 5) / 100

print "[\n"
num = 0
sum = 0
for key, value in pairs(what) do
if(value > threshold) then
if(num > 0) then
print ",\n"
end

print("\t { \"label\": \"" .. pkt_distribution[key] .."\", \"value\": ".. value .." }")
num = num + 1
sum = sum + value
end
end

if(sum < tot) then
print("\t, { \"label\": \"Other\", \"value\": ".. (tot-sum) .." }")
end

print "\n]"

In bold the API calls are highlighted. ntopng transparently handles the redirection of the output into web pages, and mix of HTML with Lua code similar to what happens with other scripting languages such as PHP. Developers familiar with web scripting languages should become familiar with ntopng pretty quickly and thus extend and customise it without much hassle.

Please make sure that you share your scripts with the ntopng community.