Add fault tolerance to cron noise

Not all cron jobs are created equal, and some of them can afford to fail sporadically before we need to worry about them. Maybe they rely on a third party server, and we don’t want the occasional fail to pollute our inbox.

Here is a little cron job wrapper I created that will suppress stderr but keeps track of the job’s returned exit codes. Above a certain threshold of consecutive abnormal exits it doesn’t suppress stderr anymore.


# if the counter file doesn't already exist we create/initialize it
if [ ! -f /tmp/counter_ri7g3 ] ;
then
    echo 0 > /tmp/counter_ri7g3 ;
fi ;

# we pull the current counter
counter=`cat /tmp/counter_ri7g3` ;

# if the counter is still small, we send stderr to /dev/null
if [ $counter -lt 5 ] ;
then
    $1 > /dev/null 2>&1 ;
# otherwise stderr will follow its normal path and find its way to email
else
    $1 > /dev/null ;
fi ;

# lastly if running the $1 resulted in an abnormal exit, the counter is incremented
if [ ! $? = 0 ] ;
then
    counter=`cat /tmp/counter_ri7g3` ;
    echo "$counter+1" | bc > /tmp/counter_ri7g3 ;
# and if $1 exited normally, we reset the counter
else
    echo 0 > /tmp/counter_ri7g3 ;
fi ;

a cron entry calling it looks as such:


30 * * * *      root      /usr/local/bin/cron_wrapper "/path/to/script arg_1 arg_2"

Poor man’s 2FA: a simpler 2-factor authentication mechanism for SSH

The problem with PAM based 2FA:
  • PAM does not get called when the SSH daemon does key based authentication. So your 2FA there only works with password authentication. This might be something you want but maybe not.
  • A PAM module based solution to 2FA is harder to implement
The solution: Poor man’s 2FA!

It is possible to add the ForceCommand directive to your sshd_config. Like the name suggests it simply runs a command after authentication and before the shell is spawned. This is a good spot to add an extra check, say another factor for authentication.

The code:
#!/bin/bash
trap "echo "I'm sorry Dave. I'm afraid I can't do that."; sleep 1 ; kill -9 $PPID ; exit 1" 2 20
code=`od -a -A n /dev/urandom | head -2 | tr -d ' ' | tr -d 'n' | sed 's/[^a-zA-Z0-9]//g' | awk '{print substr($0,1,5)}'`
echo -e "Subject:$code\nFrom:root@server <root@server.com>\n2FA code in subject" | sendmail phone_number@carrier.com
read input
if [ $code = $input ];
then
    `awk -F: '($1 == $LOGNAME) { print $7 }' /etc/passwd`
else
kill -9 $PPID
fi

That’s it really, save this to an executable file, replace the obvious variables and ForceCommand its ass.

Python SNMP simple example to get 1 OID

Because it took me forever to piece this simple code together

import netsnmp
session = netsnmp.Session( DestHost='your.host.com', Version=2, Community='public' )
vars = netsnmp.VarList( netsnmp.Varbind('.1.3.6.1.4.1.2021.8.1.101.1') )
print( session.get(vars) )