sexta-feira, 5 de fevereiro de 2010

Reading stdin on scripts for handling SNMP traps

In a shell, sometimes data are read through standard input (i.e STDIN) rather than arguments, which are most commonly used. For that reading purpose there is an instruction named "read", whose syntax is exemplified below:

$ read var

$ echo "var: $var"
var: 123

Today I was wondering how could I retrieve all values passed to a given Shell script considering that one does not know how many items are available. There are a lot of script samples of reading regular files, line by line, using "while" loop along with "read" command. But what if one needs to read the standard input?

Fortunately, there is a special device on Linux called /dev/stdin, which promised to give the expected outcome. And here's a testing script based on that assertion:

while read s
echo "s = $s"
done < /dev/stdin

And it works perfectly! Well, but.. is there any real application for such trick?

Yes, indeed! My real motivation was to debug and understand why the integration between Net-SNMP (i.e. snmptrapd service) and ZABBIX was not working when SNMP traps were received by the server. Those traps were supposed to be forwarded by snmptrapd to a Shell script called, which invoked zabbix_sender along with the received arguments.

Thus, in order to fine-grained debbuging, I created another script, named with the contents below:


echo "Request received: $0"
echo "--------------------------------------------------"

while read param
echo -e "$param "
done < /dev/stdin

echo "--------------------------------------------------"

exit 0

On the configuration file snmptrapd.conf the following line was appended:

traphandle default /bin/bash /home/zabbix/

In order to send a simple SNMP trap the following command was issued:

$ snmptrap -v 1 -c public localhost . localhost 6 12345678 8 . s "2010-02-04 17:03:18,352,DEBUG,main,SimpleTest,This is a Debug Message"

So, here are the LOG results after receiving a SNMP trap by the server:

2010-02-05 11:48:32 localhost [] (via UDP: []:40338) TRAP, SNMP v1, community public
SNMPv2-SMI::enterprises.24.0 Enterprise Specific Trap (12345678) Uptime: 0:00:00.08
SNMPv2-SMI::enterprises. = STRING: "2010-02-04 17:03:18,352,DEBUG,main,SimpleTest,This is a Debug Message"
Request received: /home/zabbix/
UDP: []:40338
DISMAN-EVENT-MIB::sysUpTimeInstance 0:0:00:00.08
SNMPv2-MIB::snmpTrapOID.0 SNMPv2-SMI::enterprises.
SNMPv2-SMI::enterprises. "2010-02-04 17:03:18,352,DEBUG,main,SimpleTest,This is a Debug Message"
SNMP-COMMUNITY-MIB::snmpTrapCommunity.0 "public"
SNMPv2-MIB::snmpTrapEnterprise.0 SNMPv2-SMI::enterprises.24.0

That's it! I hope that tip is worthful for someone else. :)