在CRON作业中执行时,在Shell脚本中抑制FTP的输出



我每天晚上都在运行一个备份shell脚本,在那里我tail一些数据,然后通过sftp将其发送到其他服务器。由于这是非常重要的数据,因此,如果出现问题,我想通过电子邮件注意。这就是为什么我选择是否在cron作业(托管服务器)中发生错误的原因。

这就是SFTP连接的样子:

sftp -i ~/.ssh/id_rsa server.com <<EOF
put $file
rm $file_old
EOF

不幸的是,现在每次脚本运行时,我都会收到一封邮件,例如:

Connected to server.com.
% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                               Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0

脚本工作,文件已转移。因此,是否有一种方法可以隐藏SFTP连接的输出,但仍显示脚本的错误。任何帮助都非常感谢!

抑制这些进度条的样本方法是执行命令如下:

sftp -q -i ~/.ssh/id_rsa server.com <<EOF
put $file
rm $file_old
EOF

此命令将在STDERR

上显示错误

您可以重定向SFTP的输出:

sftp -i ~/.ssh/id_rsa server.com > /dev/null 2>&1 <<EOF

这样,您将看不到输出。

然后,如果您想查看可能的错误,则可以使用:

sftp -i ~/.ssh/id_rsa server.com > /dev/null 2>&1 <<EOF
put $file
rm $file_old
EOF
sftp_status=$?
case $sftp_status in
    0) sftp_error="";;
    1) sftp_error="Error 1: Generic error - Undetermined error in file copy";;
    2) sftp_error="Error 2: Remote host connection failure";;
    3) sftp_error="Error 3: Destination is not directory, but it should be";;
    4) sftp_error="Error 4: Connecting to host failed";;
    5) sftp_error="Error 5: Connection lost for some reason";;
    6) sftp_error="Error 6: File does not exist";;
    7) sftp_error="Error 7: No permission to access file";;
    8) sftp_error="Error 8: Undetermined error from sshfilexfer";;
    9) sftp_error="Error 9: File transfer protocol mismatch";;
    65) sftp_error="Error 65: Host not allowed to connect";;
    66) sftp_error="Error 66: Protocol error";;
    67) sftp_error="Error 67: Key exchange failed";;
    68) sftp_error="Error 68: Host authentication failed";;
    69) sftp_error="Error 69: MAC error";;
    70) sftp_error="Error 70: Compression error (not used in SSH2)";;
    71) sftp_error="Error 71: Service not available";;
    72) sftp_error="Error 72: Protocol version not supported";;
    73) sftp_error="Error 73: Host key not verifiable";;
    74) sftp_error="Error 74: Connection lost";;
    75) sftp_error="Error 75: Disconnected by application";;
    76) sftp_error="Error 76: Too many connections";;
    77) sftp_error="Error 77: Cancelled by user";;
    78) sftp_error="Error 78: No more auth methods available";;
    79) sftp_error="Error 79: Illegal user name";;
    255) sftp_error="Error 255: Error occurred in SSH";;
    *) sftp_error="Unknown sftp Error";;
esac
echo $sftp_error

状态代码基于此列表:https://support2.microfofocus.com/techdocs/2487.html

最新更新