linuxshellcronscpsshpass

Problem in using scp with sshpass in Linux Shell


When I type the following command in Putty connected to Server A. My file is copied from Server A to Server B.

sshpass -p 'myPass' scp userB@serverB_ip:/file.txt /home/XXXXXX.txt

However, it does not work when I write it in .sh file and executed by a crontab job. My Shell file copyfilefromB.sh is as below:

#!/bin/sh
echo "start"
sshpass -p 'myPass' scp userB@serverB_ip:/file.txt /home/XXXXXX.txt
echo "end"

(I also tired the following, but also not work)

/usr/bin/sshpass -p 'myPass' scp userB@serverB_ip:/file.txt /home/XXXXXX.txt
/usr/bin/sshpass -p 'myPass' /usr/bin/scp userB@serverB_ip:/file.txt /home/XXXXXX.txt

My crontab file is as below:

0 1 * * * /usr/bin/sh /home/copyfilefromB.sh >> copyfilefromB.log

In the log file, I can only read the word "start" and "end", no error is printed, but the copy process is failed.

May I seek help from you guys? Anyone can help? Thank you for your answering.


Solution

  • when you first time run ssh or scp on giving host they check ssh public key fingerprints and ask would you like to accept and store them to ~/.ssh/known_hosts. cron runs his tasks as root user, so perhapse there are not stored fingerprints at /root/.ssh/known_hosts, but it could not ask because does not have a terminal

    add option -oStrictHostKeyChecking=accept-new:

    #!/bin/sh
    echo "start"
    sshpass -p 'myPass' scp -oStrictHostKeyChecking=accept-new userB@serverB_ip:/file.txt /home/XXXXXX.txt
    echo "end"