April 2, 2014

Configure Ubuntu Server to ssh with key and no password

Earlier I was configuring a machine with Ubuntu Server to be used as our build/process server. In the last months I was doing everything in Vagrant or AWS, but this one is a physical machine, and I have to do everything from scratch.

Being used to Python Fabric now, I wanted a way to run my scripts remotely. First I needed to enable SSH in the new server and to deploy keys to authenticate when ssh to it. OpenSSH went in as part of the deployment of Ubuntu, so that was easy.

Making the keys was clear enough with the instructions. As a reminder for me (I will probably need to do it again), I will recap the steps here:

  • In my own laptop, I run: mkdir -p ~/.ssh chmod 700 ~/.ssh ssh-keygen -t rsa
  • The last command fire a command line dialog asking for the file name to use for the keys (I used ngramaticbuild), and a passphrase. I left the passphrase empty, to not be asked for it. The end result are  two files, one public (extension .pub) and one private key. The private key stays in my laptop, the public file goes to the new server.
  • Then I ssh to the new server, logged in using username and password, and created a directory: /etc/ssh/ngramatic chmod 755 /etc/ssh/ngramatic chown ngramatic:ngramatic /etc/ssh/ngramatic

where ngramatic is the account I created in the server earlier.

  • I opened another terminal in my laptop and copied the public key to the new server scp ngramaticbuild.pub ngramatic@

where is the address of the new server.

  • Having the files in place, I did an: cd /etc/ssh/ngramatic cat ngramaticbuild.pub >> authorized_keys
  • And then configured ssh to read the keys when required: sudo nano /etc/ssh/sshd_config

and in the editor I put the line

PasswordAuthentication no ... AuthorizedKeysFile /etc/ssh/%u/authorized_keys

and saved.

  • A restart of OpenSSH closes the activity to authenticate with a key file: sudo service ssh restart
  • I closed my ssh session, opened it again from the directory where i have my private key and I wasn’t asked for a password to login, which is good: ssh -i ngramaticbuild ngramatic@
  • But if I did a sudo command, I was asked again for the password. Given I run scripts from Fabric, firing dialogs is not an option. The solution was simple, but took me some time to find it. The fix is to change the sudoers configuration: sudo visudo

and add at the bottom of the file:


After that my Fabric scripts are running happy, and I should be able to treat a physical server the same as the ones provided by AWS or Vagrant.