7

Not sure if the question I'm asking is correct but basically I wanted to automate this process

  scp ~/.ssh/id_rsa.pub username@example.com:~/
  ssh username@example.com
  mkdir .ssh
  cat id_rsa.pub >> .ssh/authorized_keys
  rm id_rsa.pub
  chmod go-w ~
  chmod 700 ~/.ssh
  chmod 600 ~/.ssh/authorized_keys

So I thought I could create a shell script and put it in my .bash_profile like this:function

setup_ssh () {
  scp ~/.ssh/id_rsa.pub $1:~/
  ssh $1
  #the following is happens when connected to the server using ssh
  mkdir .ssh
  cat id_rsa.pub >> .ssh/authorized_keys
  rm id_rsa.pub
  chmod go-w ~
  chmod 700 ~/.ssh
  chmod 600 ~/.ssh/authorized_keys
}

But of course this doesn't work because it doesn't continue the commands once connected to the server. Is there any way to continue the commands once it's connected to the server via ssh?

Marc
  • 213

2 Answers2

8

Here's a slightly different way that works:

setup_ssh() {
  cat ~/.ssh/id_rsa.pub | ssh $1 '
    mkdir .ssh;
    cat >> .ssh/authorized_keys;
    chmod go-w .;
    chmod 700 .ssh;
    chmod 600 .ssh/authorized_keys
  '
}

You could also get rid of the cat and have the shell pipe in your id_rsa.pub file, but I think this is enough to get you going.

Edit:
The way it works
You're basically starting a new shell on the remote host to execute the commands you passed to ssh (in the quotes). When it gets to the cat >> .ssh/authorized_keys part, nothing has read from the STDIN yet, so the data from the cat ~/.ssh/id_rsa.pub is still sitting there. cat reads data from STDIN and then we redirect that to the new authorized_keys file. Then we execute the remaining commands.

phemmer
  • 71,831
  • The key is that all the commands to be run on the remote machine are the parameters to ssh (using the single quotes). – Aaron D. Marasco Jan 22 '12 at 01:02
  • Thanks so much this worked great. For some reason it would stick at cat >> .ssh/authorized_keys, so I just set it to the lines that I had and it worked great. Thanks so much! – Marc Jan 23 '12 at 10:00
  • Actually I'm going to have to go with the answer below. didn't know this was already implemented. – Marc Jan 23 '12 at 10:06
  • @Marc its bad etiquette to radically change someones answer like that. The solution I proposed removed the need for typing the password multiple times, removed the need for having a temporary file, and removed superfluous commands. – phemmer Feb 25 '12 at 22:37
  • 1
    Sorry Patrick. I really should have appended it to the end of the post. I completely understand though. – Marc Feb 28 '12 at 01:10
5

Adds your identity to the remote server, also creates ~/.ssh tree with appropriate permissions if needed.

ssh-copy-id -i ~/.ssh/id_rsa.pub user@server
forcefsck
  • 7,964