Wednesday, November 13, 2013

How to use scp command without prompting for password

You may need to write a shell script in which you want to copy a file from one server to another. OfCouse you can easily achieve it with SCP command however when you automate the shell script using crontab it will get stuck because of password prompt. To avoid this you want SCP command to work without prompting for password.

Secure Copy (SCP) allows files to be copied to, from, or between different hosts

Let’s assume you want to copy a file from host server (HOST) to destination server (DEST).

1. On HOST server run below command

$ ssh-keygen -t rsa

First it will prompt for "Enter file in which to save the key" just keep it blank by pressing enter. Then it will prompt for passphrase, again keep it blank by pressing enter. It will generate a public key (id_rsa.pub) and a private key (id_rsa) in the folder <your_home_dir>/.ssh

Output -

$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/.ssh/id_rsa.
Your public key has been saved in /home/.ssh/id_rsa.pub.
The key fingerprint is:
1a:7b:3b:d7:5c:f0:6d:f1:01:75:0f:b1:71:6a:15:be user@HOST

2. Share the public key (id_rsa.pub) with DEST server

Copy the file id_rsa.pub from HOST to <your_home_dir>/.ssh folder of DEST. You can use scp or ftp anyway you are comfortable with.

3. Copy the contents of id_rsa.pub to <your_home_dir>/.ssh/authorized_keys2 in DEST server

Below command will append the content of id_rsa.pub to authorized_keys2. Note - you may even copy to authorized_keys whichever file exits on <your_home_dir>/.ssh in DEST server

$ cat id_rsa.pub >> authorized_keys2

Now if you use SCP command to transfer a file from HOST to DEST it won’t prompt for password. I hope it helped you.

No comments:

Post a Comment