You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写sshpass+scp的Bash脚本实现密码认证的Cron定时任务?

问题解决步骤

1. 消除终端运行时的here-document警告

你的脚本中多余了<<-EOF、quit和EOF这部分内容——scp是一次性文件传输命令,不需要通过交互输入quit来结束会话,这部分冗余代码导致了警告。修改后的基础脚本如下:

#!/bin/bash
sshpass -p 'password' scp /dir/sub/sub/sub/sub/file.csv username@ftps.server.com:/

2. 修复crontab定时执行失败的问题

crontab运行环境与终端不同,需要调整以下几点:

  • 使用命令绝对路径:crontab的默认PATH范围很窄,需指定sshpass和scp的绝对路径。可以通过which sshpass和which scp查看路径,示例修改:
    #!/bin/bash
    /usr/bin/sshpass -p 'password' /usr/bin/scp /dir/sub/sub/sub/sub/file.csv username@ftps.server.com:/
    
  • 禁用主机密钥检查:首次连接目标服务器时,ssh会要求确认主机指纹,crontab无交互环境会导致命令卡住。给scp添加ssh参数跳过检查:
    #!/bin/bash
    /usr/bin/sshpass -p 'password' /usr/bin/scp -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null /dir/sub/sub/sub/sub/file.csv username@ftps.server.com:/
    
  • 添加日志输出(调试用):在crontab条目中重定向日志,方便排查错误,比如设置每5分钟执行一次:
    */5 * * * * /path/to/your/transfer_script.sh >> /var/log/scp_transfer.log 2>&1
    
  • 优化密码安全性(可选):避免密码明文写在脚本里,将密码存入权限严格的文件(仅自己可读):
    # 创建密码文件并设置权限
    echo 'password' > ~/.sshpass
    chmod 600 ~/.sshpass
    
    脚本同步修改为:
    #!/bin/bash
    /usr/bin/sshpass -f ~/.sshpass /usr/bin/scp -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null /dir/sub/sub/sub/sub/file.csv username@ftps.server.com:/
    

内容的提问来源于stack exchange,提问作者jasonharvey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 16:10:01