使用Crontab+SCP从远程服务器拉取文件遇脚本错误求助
解决Bash脚本拉取远程文件的问题
问题描述
尝试通过Cron任务将远程服务器文件拉取到本地,要求脚本持续检查直至文件可用后下载。编写的脚本运行时出现以下错误:
/usr/bin/ssh-copy-id: ERROR: ssh: Could not resolve hostname xxxxxxxxxx: Name or service not known ./cplocalfromRemote2.sh: line 14: goto: command not found host's password:
原脚本代码:
#!/bin/bash year=$(date +%Y) month=$(date +%m) day=$(date +%d) hour="00" ssh-keygen # I suspect this line and the one below should be done once and not in the script. ssh-copy-id _lms_2023 cd ${HOME}/ModelOutput_LMS/WRF_OUTPUT/tmp cd ${HOME}/ModelOutput_LMS/WRF_OUTPUT/tmp goto GOTO_1 if ssh lmshpc@41.203.191.69 "test -e /${HOME}/DA/OUTPUT/"$year$month$day$hour"/noda/graphics/*.png"; then scp lmshpc@41.203.191.69:${HOME}/DA/OUTPUT/"$year$month$day$hour"/noda/graphics/*.png . if [ $? -eq 0 ]; then exit fi else sleep 30 GOTO_1 fi
错误修复与脚本优化
1. 移除脚本内的ssh-keygen和ssh-copy-id命令
ssh-keygen会在每次运行脚本时生成新密钥对,完全没必要;ssh-copy-id仅需手动执行一次,用于配置免密登录,步骤如下:# 手动执行一次即可,无需放入脚本 ssh-keygen -t rsa ssh-copy-id lmshpc@41.203.191.69- 原脚本中
ssh-copy-id _lms_2023的主机名错误,导致"无法解析主机名"的报错,需替换为正确的远程主机标识lmshpc@41.203.191.69。
2. 替换goto命令(Bash不支持该语法)
Bash没有goto功能,改用while true循环实现持续检查逻辑,直到文件下载成功才退出循环。
3. 修正路径与文件检查逻辑
- 移除重复的
cd命令,确保仅进入一次本地目标目录。 - 远程路径中的
${HOME}是本地环境变量,应使用远程用户的HOME路径(可省略,远程命令默认从用户HOME目录启动),或直接写绝对路径避免歧义。 test -e *.png无法正确检测是否存在匹配的PNG文件,改用ls结合grep的方式判断:ssh lmshpc@41.203.191.69 "ls /DA/OUTPUT/${year}${month}${day}${hour}/noda/graphics/*.png 2>/dev/null | grep -q ."
修正后的完整脚本
#!/bin/bash year=$(date +%Y) month=$(date +%m) day=$(date +%d) hour="00" # 切换到本地目标目录,切换失败则直接退出 cd "${HOME}/ModelOutput_LMS/WRF_OUTPUT/tmp" || exit 1 # 持续检查远程文件,直到下载成功 while true; do # 检查远程是否存在目标PNG文件 if ssh lmshpc@41.203.191.69 "ls /DA/OUTPUT/${year}${month}${day}${hour}/noda/graphics/*.png 2>/dev/null | grep -q ."; then # 执行文件下载 scp lmshpc@41.203.191.69:/DA/OUTPUT/${year}${month}${day}${hour}/noda/graphics/*.png . # 验证下载是否成功 if [ $? -eq 0 ]; then echo "文件下载成功" exit 0 fi fi # 间隔30秒后再次检查 sleep 30 done
额外说明
- 确保已完成免密登录配置,避免Cron任务运行时需要手动输入密码。
- 如果远程路径中的
/DA/OUTPUT/并非绝对路径,需根据远程用户的实际HOME目录调整,例如改为~/DA/OUTPUT/。
内容的提问来源于stack exchange,提问作者Zilore Mumba
相关产品推荐
相关产品推荐

