SCP not working in crontab but works on commandline

13,682

Solution 1

I have tried virtually every answer found related to the problem. The answer just came accidentally.

I typed username instead of root and it worked. I don't know how but it worked. Hope this will help people like me.

2 10 * * * root /usr/bin/scp -i /home/username/.ssh/id_rsa -r /var/www/abc abc@ip:/home/abc

2 10 * * * username /usr/bin/scp -i /home/username/.ssh/id_rsa -r /var/www/abc abc@ip:/home/abc

Solution 2

Why don't you try putting the the scp command in a bash script and put the bash script in the cron , also remember to put the shebang in your sh script as follows : #! /bin/bash (generally the path , confirm this by typing which bash in your shell). Also chmod a+x your sh script to make it executable and try the sh script from bash as ./script.sh and then put it in the crontab.

Why did the scp command not work in crontab? The following post does a good job explaining the different kinds of problems one faces with cron jobs - https://askubuntu.com/questions/23009/reasons-why-crontab-does-not-work

In your case it's an environment problem. Crontab's environment is different from that of bash's. Hope this helps.

Solution 3

This is my solution. Made in Raspberry with Jessie OS.

Fix connection with the server with public key with no passphrase. You can find tutorials everywhere. The thing is do it as the same user that shall create the crontab. In my case I made the keys as PI (user on my Raspberry). Make sure you can login without password on your server.

Then I created my script that uploads all txt-files in a directory to the server every 5th minute. ex:

"#!/bin/bash scp /mnt/www/hus/*.txt [email protected]:/www/images/hustemp"

Save it as xxxxxxx.sh in your home dir and make it executable (chmod +x xxxxxxx.sh).

Then itś time to create the cronjob. I think you have to be in your home dir.Just run crontab -e (no sudo in front)and edit to what you want. In my case: */5 * * * * /home/pi/upload.sh

It works perfect!

Good Luck Anders

Share:
13,682
tapaljor
Author by

tapaljor

Updated on June 09, 2022

Comments

  • tapaljor
    tapaljor almost 2 years

    After much research, I couldn't find a solution but post this question.

    I have a computer A and B both Ubuntu desktop. I want to copy file from A to B. Steps I followed.

    1. ssh-keygen in computer A
    2. Left password blank
    3. Copied id_rsa.pub to computer B ~/.ssh/ from computer A
    4. Renamed id_rsa.pub to authorized_keys in computer B
    5. In computer A I did scp -i ~/.ssh/id_rsa -r /var/www/abc abc@ip:/home/abc/
    

    If I do step 4 in commandline its working fine. But when I did same in crontab

    22 10 * * * root scp -i ~/.ssh/id_rsa -r /var/www/abc abc@ip:/home/abc
    

    Its doing nothing.