0

I have a remote server and a local server. I am trying to automatically transfer a nightly backup on the remote server to my local one. SSH keys are setup, so no password is required.

Using the following command, it works manually:

scp -r -P {REMOTEPORT} user@serveripaddress:/home/remoteuser/directory /home/localuser/directory

I would like to set a cronjob so the previous action runs, but I am new to writing actual scripts. Is there a simple script that would make this happen?

Eric
  • 37
  • 2
  • 5
  • you probably just need to prepend scp with '/usr/bin/' for this to work as a script. Although I recommend rdist as the best tool for doing this. – user16081-JoeT Jan 29 '14 at 00:08
  • You got a nice round answer below, but I recommend the simplest approach: just run that same line (albeit with a full pathname to the scp command) from cron, and you will be ok. – James Jan 29 '14 at 02:25

1 Answers1

3

You could write a simple script, let's say backup.sh :

#!/bin/bash
/usr/bin/scp -r -P {REMOTEPORT} user@serveripaddress:/home/remoteuser/directory /home/localuser/directory

Make it executable with chmod +x backup.sh

Then, edit crontab (crontab -e) and set it up :

0 0 * * * /path/to/backup.sh > /var/log/backup.log 2>&1

Also, you could run it directly from cron (crontab -e) :

0 0 * * * /usr/bin/scp -r -P {REMOTEPORT} user@serveripaddress:/home/remoteuser/directory /home/localuser/directory > /var/log/backup.log 2>&1

ps : if you run into troubles, for sure we can help, but i strongly recommend reading this for debugging : Why is my crontab not working, and how can I troubleshoot it?

krisFR
  • 12,830
  • 3
  • 31
  • 40
  • OK, so I can run simple command line actions directly in crontab. What is the last part you added to the original command: `> /var/log/backup.log 2>&1` – Eric Jan 29 '14 at 18:02
  • @Eric It redirects ok messages (if any) and error messages (if any) in a log file. Also you can use `>> /var/log/backup.log 2>&1` to append messages to the log file and not overwrite it each time. It could be a good idea to log command execution to check if everything went right ! – krisFR Jan 29 '14 at 19:46