Login Automatically With SSH Keys

2 minute read

With SSH you can securely login to any Linux server and execute commands remotely. You can even use SSH to transfer and synchronize files from one server to another. Automating these tasks can make your life easier, but normally SSH prevents that because it requires you to login every time. Well, not anymore, in this article I will show you how to connect to SSH without a password.

About SSH Keys

SSH keys allow machines to identify each other without you having to type the password every time. First we need to generate a key (it's nothing more than a randomly generated sequence of bytes, see it as a fingerprint) on the machine you're going to make the connection from. And then you install that unique key on the machine that needs to accept the connection.

Little Helper Script

Installing keys takes quite a couple of commands, not very easy to remember either. And if you have multiple servers, you might even want to automate the process of installing keys. No worries, I did this for you. So just download the helper script and install it. Open a terminal, and type:

$ su -  # If you're going to use the keys to automate tasks, become root first
$ mkdir -p ~/bin
$ curl https://raw.github.com/kvz/deprecated/kvzlib/bash/programs/instkey.sh -ko ~/bin/instkey.bash \
 && chmod u+x $_

Running the Script: Installing Keys

Now with the script in place, installing SSH keys is easy. To allow easy access to server.example.com just open a terminal and type:

$ ~/bin/instkey.bash server.example.com

The first time you run the script, it will create the necessary keys, when it asks for a pass phrase, just hit enter. Then it logs in at server.example.com (now you need to enter the server's password for the last time ; ), and it saves the key.

Installing ssh Keys Under a Different User

Make sure you are logged in as the user you want to have passwordless ssh access. Let's say this user is called: kevin.

Goto the place you downloaded the instkey.sh script to, and type:

$ ./instkey.bash server.example.com kevin

Notice the second argument? This will make sure keys from kevin aren't remotely installed to root, but to kevin as well. Easy right?

Congratulations! You can now type

$ ssh server.example.com

And you'll be logged in right away! Another great idea is to use this technology to automatically synchronize files with rsync.

Pitfalls

  • Of course you should really be carefull where and when to install ssh keys, because if one machine is compromised, it's very easy for a cracker to hop to the next system without logging in. So choose wisely when to use this technology.
  • Keys are user specific. So if you're going to run programs as root that need to automatically login to systems, you must also install the key as root.

Categories: ,

Updated:

Leave a Comment Right Here