Examples
banshee/examples-collection/examples/mechanics/
lists
Example: arrays and the list tools, count, has, get, add; the TCP ports a Linux listens on.
by banshee1 installation1 version
Published on October 27, 2026. First version in this collection.
// Lists: build one, write under a key, add at the end, test and read a key that may be missing, count.
// The collector checks that the TCP ports expected on a Linux are listening.
need('protocol:ssh');
$expected = variable('example:ports:expected', 'multiline', array(
'label' => 'Expected ports',
'help' => 'One port per line, for example 22.',
));
output('listening', 'number', array('label' => 'Ports listening'));
output('closed', 'text', array('label' => 'Expected ports closed'));
watch.expect('port-closed', 'Expected port closed', 'closed', array('critical' => array('none')));
// One line per listening socket, "LISTEN 0 128 0.0.0.0:22 0.0.0.0:*": the fourth word is address:port.
$read = ssh.run('ss -H -l -t -n');
// array(): an empty list. Writing under a key that is missing creates it, and what is missing above it:
// $ports['22']['0.0.0.0'] creates $ports['22'] too.
$ports = array();
foreach (text.lines($read['output']) as $line) {
$words = text.words($line);
$m = text.match($words[3], '^(.*):([0-9]+)$');
$ports[$m[2]][$m[1]] = true;
}
// list.count: the number of elements, here the number of ports.
value('listening', list.count($ports));
// list.has: is there an element under this key? list.add: the list with one more element at its end.
$closed = array();
foreach (text.lines($expected) as $port) {
if (!list.has($ports, $port)) {
$closed = list.add($closed, $port);
}
}
// list.get: the element under a key, or the default given when the key is missing; here, the
// first port closed, '' when there is none.
if (list.get($closed, 0, '') == '') {
value('closed', 'none');
} else {
value('closed', text.join($closed, ', '));
}