我有一个脚本,写在bash中,从cron运行。 它所做的第一件事情之一是SSH到远程主机,并检索目录中的文件列表。 从命令行运行时一切正常,但不是从cron运行。
脚本部分最初看起来像这样:
FILES=$($SSH_BINARY -i $SSH_KEY $SSH_USER@$REMOTE_HOST "ls $REMOTE_DIRECTORY") echo "Got files = $FILES"
我在该行上面添加了一个echo语句(如下所示)来certificate它不是path或variables问题:
echo "$SSH_BINARY -i $SSH_KEY $SSH_USER@$REMOTE_HOST \"ls $REMOTE_DIRECTORY\""
如果我把结果输出行并作为相同的用户cron将(根)运行,它没有问题。
认为它可能与分配给variables有关,我修改了FILES =行来读取(因此,把输出直接放到我的last_run_output文件中):
$SSH_BINARY -vv -i $SSH_KEY $SSH_USER@$REMOTE_HOST "ls $REMOTE_DIRECTORY"
cron条目如下所示:
34 * * * * /root/path/to/my/script/get_logs.sh > /root/path/to/last_run_output 2>&1
所以,除了PATH,variables赋值和权限问题之外,我开始在ssh中使用debugging标志。 我从命令行运行一次,然后从cron运行,并比较输出。 以下是差异中的一些亮点:
侧面是不成功的尝试,+侧面是成功的尝试,在cron之外运行。
@@ -87,9 +77,7 @@ debug1: Remote: X11 forwarding disabled. debug1: Remote: Forced command: /home/sshacs/acssshsink netstorageuser debug1: Authentication succeeded (publickey). -debug2: fd 4 setting O_NONBLOCK debug2: fd 5 setting O_NONBLOCK -debug2: fd 6 setting O_NONBLOCK debug1: channel 0: new [client-session] debug2: channel 0: send open debug1: Entering interactive session.
我无法解释为什么这些额外的文件描述符在debugging2中提到从cron运行时,但它似乎是相关的(注意阅读<= 0 rfd 4 len 0行下面):
@@ -100,20 +88,672 @@ debug2: callback done debug2: channel 0: open confirm rwindow 0 rmax 32768 debug2: channel 0: rcvd adjust 131072 -debug2: channel 0: read<=0 rfd 4 len 0 -debug2: channel 0: read failed -debug2: channel 0: close_read -debug2: channel 0: input open -> drain -debug2: channel 0: ibuf empty -debug2: channel 0: send eof -debug2: channel 0: input drain -> closed + [[ Very large output of the ls command ]] +debug1: client_input_channel_req: channel 0 rtype exit-status reply 0 debug2: channel 0: rcvd eof debug2: channel 0: output open -> drain debug2: channel 0: obuf empty debug2: channel 0: close_write debug2: channel 0: output drain -> closed -debug1: client_input_channel_req: channel 0 rtype exit-status reply 0 debug2: channel 0: rcvd close +debug2: channel 0: close_read +debug2: channel 0: input open -> closed debug2: channel 0: almost dead debug2: channel 0: gc: notify user debug2: channel 0: gc: user detached
任何想法,不胜感激。
尝试添加-t -t到您的SSH连接选项。 这会; 强制一个伪terminal被分配。
多选项强制tty分配,即使
ssh没有本地tty。
你应该进一步debugging你的脚本。 两件事情要尝试:
Rwrite它直接做文件输出,而不是通过输出redirect。 也就是说,在脚本中这样做:
$SSH_BINARY -i $SSH_KEY $SSH_USER@$REMOTE_HOST "ls $REMOTE_DIRECTORY" > savefile
在cron中用bash -x运行脚本并保存结果。 将脚本的第一行更改为#!/bin/bash -x并尝试类似的操作
34 * * * * /root/path/to/my/script/get_logs.sh > script_debug 2>&1
这应该会帮助你精确地缩小你的脚本在做什么。 我怀疑cron的输出redirect在这种情况下无法正常工作。
另外,愚蠢的问题:你有没有证实根可以写入/root/path/to/last_run_output ? 当脚本运行在cron中时,你是否证实你没有设置noclobber ?
编辑:基于来自OP的意见进一步排除故障的想法。
所以没有任何上述的想法似乎工作。 那么把这个守场者放到远程机器上的文件里,然后把它放回去呢? 这将消除任何奇怪的引用或inputredirect问题。