SSH and SCP with keys instead of passwords

I’m writing about this bit of useful shell scripting, mostly so I know where to find it when I might need it again.

I needed to set up automatic backups using a shell script in Mac OS X, to copy (scp) tarballs from a mounted network drive on my Mac to a remote Linux environment. The only problem was the ssh authentication — the remote Linux server seemed to want a password every time. I remembered a friend of mine had done this a while back, and I started digging around. Here’s the summary of how you can set up your machine to be recognized by the remote machine,

1. On my Mac (Leopard), using the Terminal App, I ran,

ssh-keygen -t rsa

This outputs the following,

Generating public/private rsa key pair.
Enter file in which to save the key
(/Users/[username]/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):

I left that blank,

Enter same passphrase again:

Left that blank too,

Your identification has been saved in
/Users/[username]/.ssh/id_rsa.
Your public key has been saved in
/Users/[username]/.ssh/id_rsa.pub.
The key fingerprint is:
... finger print string here ...
[username]@[machine].local

Basically, this created two files in my user folder’s .ssh/ folder,

.ssh/id_rsa

(This is the private key — guard it well)

.ssh/id_rsa.pub

(This is the public key — pass it along)
2. I SSHed into the remote server to make sure my user account’s folder over there contained a .ssh/ folder. It didn’t, so I created one,

SSHed into remote server:

ssh user@remote

I was prompted for my password,

user@remote's password:

Once I was in, I created the .ssh/ folder,

mkdir .ssh

Then I exited the remote server.

3. Then I had to transfer my public key over to the remote server. I ran the following from my home folder,

ssh user@remote "cat >> .ssh/authorized_keys" < .ssh/id_rsa.pub

Again, I was prompted for my password,

user@remote's password:

When it was done adding my public key, it logged me out.

Now when I run,

ssh user@remote

I no longer get prompted for a password, I just go right in. This means my backup script, using scp, can run as a cron job.

This entry was posted in Bash/Shell Scripts, Tech. Bookmark the permalink.

Comments are closed.