Set up public key authentication with SSH

1. Generate a keypair using the ssh-keygen

$ ssh-keygen -t rsa

You will be prompted to supply a filename for saving the keypair. Press enter to accept the default filename.
Then enter passphrase twice.
The keypair files below are generated in ~/.ssh.

  • id_rsa

2. Add public key to the remote SSH server

Copy the public key file generated in step 1 to the user's home directory of remote server using scp or ftp.

$ scp ~/.ssh/ user@host:

On remote server register the public key to ~/.ssh/authorized_keys using cat command and redirection.

$ cat >> ~/.ssh/authorized_keys

Modify the permissions of ~/.ssh directory and ~/.ssh/authorized_keys to allow only owner of them to read or write.

$ chmod 700 ~/.ssh
$ chmod 600 ~/.ssh/authorized_keys
  • Pay attention to the permission of the user's home directory of client side.
    In case that write permission for other than owner is set, it's bad.
    For example, when file mode of /home/hoge is 777 and you attempt to connect with SSH, you will have an error below.

    Permission denied (publickey,gssapi-with-mic).

    In this case the log file of server side (/var/log/secure) says

    Authentication refused: bad ownership or modes for directory /home/hoge

    You should set home directory's permissions to 700, 711, or 755.

3. Attempt to log in with public key authentication

$ ssh -l user host

You will be prompted to enter passphrase then enter the passphrase which you specified in executing ssh-keygen command.
Notice the passphrase is NOT a password of the user

4. Client side

Copy private key file (id_rsa) to the client side ~/.ssh

  • Pay attention to the permission of the private key file.
    Below is an error on Mac OS X.

    Permissions 0640 for '/Users/xxx/.ssh/id_rsa' are too open.
    It is recommended that your private key files are NOT accessible by others.
    This private key will be ignored.
    bad permissions: ignore key: /Users/xxx/.ssh/id_rsa
    Permission denied (publickey,gssapi-with-mic).

    Set the permissions of id_rsa to 600 and it will be OK.

  • If you use cwRsync, copy private key file (id_rsa) in .ssh directory under the HOME environment variable. (Same as directory in which known_hosts is created)

    For example:

    If HOME is /home/pistolfly and cygwin directory is C:\cygwin, use C:\cygwin\home\.ssh.
    (You can also specify path to private key file with -i option in rsync -e or --rsh options)

5. Disable password authentication

Edit /etc/ssh/sshd_config (server side)


PasswordAuthentication yes


PasswordAuthentication no

Disable root login.

PermitRootLogin no

Reload sshd as a root. Don't logout as root yet.

$ /etc/init.d/sshd reload

Leave a Reply

Your email address will not be published. Required fields are marked *

5 + one =

This site uses Akismet to reduce spam. Learn how your comment data is processed.