
Q: I need to copy a file, or set of files, from one machine to a remote machine on a given schedule via SSH. How can I accomplish this?
A: This is a pretty common need and pretty handy when you need to copy files over a machine where the backup software is running. The process of configuring is pretty easy and just involves a few steps needed to automate the login between the two machines. So let’s see what we need to do, for the post I will use a simple copy script but you can easily adopt this to anything needed.
If you never did this generate the public/private key pair that will be used to authenticate between the machines, it’s needless to say that you should export and protect the private key, with the following command :
ssh-keygen -t rsa
You will be asked for a key pass phrase, leave this empty just, again, be sure to protect the private key. Now copy the public key to the remote machine with the following command :
scp ~/.ssh/id_rsa.pub remote_host:/some_dir
Now we need to import the public key to the list of authorized hosts on the “remote” machine so just login to the machine via SSH and issue the following command :
cat ~/id_rsa.pub >> ~/.ssh/authorized_keys
This will import the public key to the list of authorized keys (machines) into the authorized list of machines/users who can login without a password, to test this you can issue the following command :
ssh REMOTE_USERNAME@remote_host
You should get immediately the shell prompt without being asked for a password, if you are prompted for a password double check the steps as something went wrong
No back to the original problem, how do I automate the copy of a file/directory via SCP and cron? Simply open up your crontab file and put your script with the desired schedule something like :
scp -r /PATH_TO_FILES/* REMOTE_USER@remote_host:BACKUPS/
There you go, the machine will automatically execute the script at the desired schedule copying your files from machine to machine without asking any password or any manual interaction.
There are, of course, more elegant or “sophisticated” ways of doing this (rsync, puppet, cfengine just to name a few) but for a simple requirement as the above this will work like a charm.
I hope you found the article useful, if so please take some time to retweet it or to leave a comment!
Cheers Lethe.
VN:F [1.9.20_1166]
Rating: 3.0/5 (2 votes cast)
Incoming search terms: