Cron – redirecting output from telnet / nc to file in script fails when cron’d

cronnetcatscriptingtelnet

So, I have device on my network which sits there listening on a port for a connection, and when a connection is made it dumps ascii data out. I need to capture that data to a file. I wrote a dead simple shell script that does this:

#!/bin/bash

#Config Variables. Age is in Days.
DATA_ROOT=/root/data
FILENAME=data_`date +%F`.dat
HOST=device
COMPRESS_AGE=3

#Sanity Checks
if [ ! -e $DATA_ROOT ]
then
        echo "The directory $DATA_ROOT seems to not exist. Please create it."
        exit 1
fi

if [ -e $DATA_ROOT/$FILENAME ]
then
        echo "You seem to have extracted data already today. Aborting"
        exit 1
fi


#Get Data
nc $HOST 2202 > $DATA_ROOT/$FILENAME
#Compress old Data
find $DATA_ROOT -type f -mtime +$COMPRESS_AGE -exec gzip {} \;

exit 0

It works great when I run it by hand, but when I run it from cron, it doesn't capture any of the output. If I replace nc with telnet I see the initial telnet headers about escape sequences and whatnot, but not the data.

Ideas? I've tried forcing bash to act like an interactive shell with -i. I've tried redirecting both stderr and stdout. I know it's got to be some silly simple thing, but I'm utterly failing. This is driving me nuts…

EDIT I also just noticed that the nc processes from all my previous attempts at this have been siting sleeping, and when I killed them, cron sent me a bunch of non-sensical error messages. At least now I have something to dig into!

Best Answer

It's possible that your script is working, and it's just the output that's getting lost. You could try capturing the nc output into a variable of it's own, and then echoing that variable out to

#Get Data
ncoutput=$( /path/to/nc $HOST 2202 2>&1 )
printf "%s\n" "$ncoutput" > $DATA_ROOT/$FILENAME
#Compress old Data
find $DATA_ROOT -type f -mtime +$COMPRESS_AGE -exec gzip {} \;

exit 0

printf preserves the formating of the output, whereas echo doesn't.