Thursday, March 31, 2011

Authorized_keys and SCP

I have SSH access to a machine, and I want to add my public key to the `authorized_keys` file so I don't have to type a password to log in. A friend taught me a neat command for doing this:

% cat ~/.ssh/id_rsa.pub | ssh user@server "cat >> .ssh/authorized_keys"

Meaning:

  • Output the contents of my public key
  • Send that as standard input to this ssh command
  • The ssh command runs `cat` on the server
  • Since `cat` on the server is called without arguments, it uses standard input - in this case, the contents of my public key file
  • My public key gets added to `authorized_keys`

Added my key to `authorized_keys` has another benefit, besides not having to type the password when I SSH in: since I'm automatically recognized as a user, I can use tab completion for scp commmands. (Note: I'm using the zsh shell; remote tab-completion doesn't work for me in bash.)

In other words, if there's a file called "foo.txt" in my home directory on that server, and I want to copy it to my local machine, I can start type this:

% scp user@server:fo

... and hit tab, and it will auto-complete "foo.txt". That makes using scp a lot less tedious.