开发者

Cron fails to run bash script

I have bash script

#!/bin/sh

DTFILE=/etc/daytime.addr
DTPORT=13
DAYTIME_ERROR=/tmp/dtm.err

function daytime_error(){
    if [[ -z $1 ]]
    then 
    exit 1
    fi
    if [[ -e $DAYTIME_ERROR ]]
    then
    echo "Error already reported"
    else
    logger "$1"
    touch $DAYTIME_ERROR
    fi
    exit 1
}

if [[ -s $DTFILE ]]
then
    ADDR=$(head -n1 $DTFILE)
    DAYTIME=$(telnet $ADDR $DTPORT | time_conv.awk)
    if [[ -z $DAYTIME ]]
    then
    daytime_error "Daytime client: no connection to $ADDR"
    else
    date -s "$DAYTIME"
    hwclock -w
    rm $DAYTIME_ERROR
    fi

else
    daytime_error "Daytime client: no daytime server address in file $DTFILE"
fi

and it works when called from command line, but fails when cron calls it. Specifically the line with telnet command gives zero bytes of output. Telnet has 755 mask, so every user should be able to use it. Any ideas ?

Update, contents of time_conv.awk:

#! /usr/bin/awk -f

/[0-9]+:[0-9]+:[0-9]+/ {
    if ($2~/Jan/) $2=1;
    else if ($2~/Feb/) $2=2;
    else if ($2~/Mar/) $2=3;
    else if ($2~/Apr/) $2=4;
    else if ($2~/May/) $2=5;
    else if ($2~/Jun/) $2=6;
    else if ($2~/Jul/) $2=7;
    else开发者_StackOverflow社区 if ($2~/Aug/) $2=8;
    else if ($2~/Sep/) $2=9;
    else if ($2~/Oct/) $2=10;
    else if ($2~/Nov/) $2=11;
    else if ($2~/Dec/) $2=12;
    print $5 "-" $2 "-" $3 " " $4
}


I'm guessing that some paths are missing... Did you try to use /usr/bin/telnet instead of telnet?

To find the path of telnet you can use which telnet.


Okay. Wild guess time...

Are you using a .rhosts file? That way, when you telnet, you don't have to enter a password. You can't do that in a crontab script.

If that's the cause, three things you have to do:

  • Find out what user that crontab is running under.
  • For that user, run the ssh-keygen program, and generate a public and private key. Do the same for the remote machine. Now, create an authorized_hosts file on the remote machine and add in your public key.
  • Once this is done, switch from telnet to ssh. SSH is more secure anyway.


You should mention the specific error messages you get. Anyway, since you say that the telnet line causes an error I assume the following common pitfall:

  • Your script requires the Bash shell to run properly.
  • The default shell of your system is not /bin/bash. Look at what /bin/sh is pointing at, e.g. with ls -l /bin/sh
  • Your account, though, is set to have /bin/bash as default shell (probably this is set for your account in /etc/passwd or by means of the variable $SHELL.

Solutions:

  • Change the default shell of your system (depends on your system, not what I recommend).
  • Make your cronjobs use Bash as default: Set SHELL=/bin/bash in the crontab.
  • Change the 1st line of your script to mention Bash explicitly: #!/bin/bash (my recommendation)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜