SSH/SCP Without Being Prompted for a Password

Technical

About two or three times a year I find myself in need of a background process that either needs to SSH or SCP into a remote machine . Since I do it so infrequently, I need to remind myself of the procedure each time so I've decided to lay it out here for anyone - but especially me - to reference.

This process will allow a user to access, via the SSH protocol, another server without being prompted for a password. This technique is tremendously useful if, for example, you want to run a cron job that creates a backup using rsync or one that simply needs to copy files from another server to be processed locally.

Terminology

Client
The machine that will be initiating the SSH or SCP connection.
Server
The remote machine that is accepting the connection.

Notes

  • My shell of preference is tcsh so the commands in these instructions work in that shell. I'm not aware of any differences for bash or other shells, but consider this your disclaimer.
  • I use an RSA key, but DSA keys may be used instead (perhaps others, but I can't speak to that).
  • These steps assume that the server is properly set up to allow SSH connections and that a ~/.ssh directory exists for the user on that server.

Steps

  1. Prepare the client environment by creating an SSH directory in your home directory if one does not already exist.
    $ mkdir -p ~/.ssh
    $ chmod 700 ~/.ssh
  2. Generate the public and private keys (id_rsa.pub and id_rsa, respectively).
    $ ssh-keygen -t rsa
    When prompted, press three times to accept the default file locations and an empty passphrase.
  3. Copy the public key to the server.
    $ scp id_rsa.pub user@server:~
  4. SSH to the server and append the content of the public key file to the authorized_keys file.
    $ ssh user@server
    $ cat id_rsa.pub >> .ssh/authorized_keys
  5. Ensure that the authorized_keys file permissions are properly limited.
    $ chmod 0600 .ssh/authorized_keys
  6. Disconnect from the server and, from the client, try to ssh to the server. You should be able to login successfully without being prompted for a password.

Troubleshooting

I've run into situations - mostly in LAN environments where DNS isn't complete or reliable - where my host isn't recognized by the server. If you're unable to login without a password, cat the authorized_keys file on the server.

This file will contain a lot of encrypted data, but at the end of the file you should recognize your username@host. Verify the host. If it looks right, then try changing it to username@clientip. If DNS is flaky or incomplete, specifying an IP address rather than the client name should take care of it. This has solved the problem for me on several occasions.


Search

Rob  Wilkerson