Kyl*_*ith 5 linux ssh bash shell-scripting
我有一个用 bash 编写的脚本,它从 cron 运行。它做的第一件事是通过 SSH 连接到远程主机并检索目录中的文件列表。从命令行运行时一切正常,但不是从 cron 运行。
脚本部分最初是这样的:
FILES=$($SSH_BINARY -i $SSH_KEY $SSH_USER@$REMOTE_HOST "ls $REMOTE_DIRECTORY")
echo "Got files = $FILES"
Run Code Online (Sandbox Code Playgroud)
我在该行上方添加了一个 echo 语句(如下所示)以证明它不是路径或变量问题:
echo "$SSH_BINARY -i $SSH_KEY $SSH_USER@$REMOTE_HOST \"ls $REMOTE_DIRECTORY\""
Run Code Online (Sandbox Code Playgroud)
如果我采用结果输出行并以相同的用户 cron 将(root)运行它,它就可以正常工作。
认为它可能与变量赋值有关,我修改了 FILES= 行以读取(因此,将输出直接放入我的 last_run_output 文件中):
$SSH_BINARY -vv -i $SSH_KEY $SSH_USER@$REMOTE_HOST "ls $REMOTE_DIRECTORY"
Run Code Online (Sandbox Code Playgroud)
cron 条目如下所示:
34 * * * * /root/path/to/my/script/get_logs.sh > /root/path/to/last_run_output 2>&1
Run Code Online (Sandbox Code Playgroud)
因此,撇开 PATH、变量分配和权限问题不谈,我开始在 ssh 中使用调试标志。我从命令行运行一次,然后从 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.
Run Code Online (Sandbox Code Playgroud)
我无法解释为什么从 cron 运行时在 debug2 中提到了这些额外的文件描述符,但它似乎是相关的(注意 read<=0 rfd 4 len 0 line 下面):
@@ -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
Run Code Online (Sandbox Code Playgroud)
任何想法都非常感谢。