Monday, January 9, 2012

How To scp, ssh and rsync without prompting for password

Lets say you want to copy between two hosts host_src and host_dest. host_src is the host where you would run the scp, ssh or rsyn command, irrespective of the direction of the file copy!
  1. On host_src, run this command as the user that runs scp/ssh/rsync
    $ ssh-keygen -t rsa

    Generating public/private rsa key pair.
    Enter file in which to save the key (/root/.ssh/id_rsa):
    Enter passphrase (empty for no passphrase):
    Enter same passphrase again:
    Your identification has been saved in /root/.ssh/id_rsa.
    Your public key has been saved in /root/.ssh/
    The key fingerprint is:
    82:c6:21:5b:9e:07:6e:6d:3b:66:47:eb:9e:ff:6a:bd root@localhost
    Chú ý:  Nếu không muốn hiện bản nhập key thì Enter passphrase bằng rỗng
    This will prompt for a passphrase. Just press the enter key. It'll then generate an identification (private key) and a public key. Do not ever share the private key with anyone! ssh-keygen shows where it saved the public key. This is by default ~/.ssh/
    Your public key has been saved in /.ssh/
  1. Transfer the file to host_dest by either ftp, scp, rsync or any other method.
  1. On host_dest, login as the remote user which you plan to use when you run scp, ssh or rsync on host_src.
  2. Copy the contents of to ~/.ssh/authorized_keys
    $ cat >> ~/.ssh/authorized_keys
    $ chmod 700 ~/.ssh/authorized_keys
    Cần copy nội dung ghi vào file ~/.ssh/authorized_keys
    Nếu có nhiều key thì copy vào bên dưới file  ~/.ssh/authorized_keys

    If this file does not exists, then the above command will create it. Make sure you remove permission for others to read this file. If its a public key, why prevent others from reading this file? Probably, the owner of the key has distributed it to a few trusted users and has not placed any additional security measures to check if its really a trusted user.

  1. Note that ssh by default does not allow root to log in. This has to be explicitly enabled on host_dest. This can be done by editing /etc/ssh/sshd_config and changing the option of PermitRootLogin from no to yes. Don't forget to restart sshd so that it reads the modified config file. Do this only if you want to use the root login.
Well, thats it. Now you can run scp, ssh and rsync on host_src connecting to host_dest and it won't prompt for the password. Note that this will still prompt for the password if you are running the commands on host_dest connecting to host_src. You can reverse the steps above (generate the public key on host_dest and copy it to host_src) and you have a two way setup ready!

No comments: