I want to have passwordless ssh to persist even after after I restart or logoff and then login. Somehow I have to run ssh-agent and use command ssh-add at login. In a tutorial I read that I should add the following lines to .bashrc:

Is there any way to do it in my script say like I use ssh-agent bashssh-add inside my script? This way it can add the keys and make the connection passwordless whenever I run the script.
–
Abhishek AnandMay 3 '11 at 6:35

4 Answers
4

You can use ssh-copy-id to copy your public key to the remote machine. If you didn't add a password when doing ssh-keygen, then it won't prompt for a password whenever you ssh into that remote machine.

This starts ssh-agent using the socket /tmp/user.agent and then runs ssh-add to load a private key into it. I then start ssh to server with a remote port forward. Attempt to connect to port 2222 on server will be forwarded back to the client and connect to port 22 on the client. -N says don't start a shell and -f says fork and run in background. I use this kind of command to make my desktop accessible from a server without opening up a port on my router. Later when you log in again, the agent will still be running. Just reset the agent socket with export SSH_AUTH_SOCK=/tmp/user.agent and you can run ssh again. ssh-add is only needed after ssh-agent is first started.

With Keychain you can do it as long as you use a key pair without password. It is a simple shell script wrapping ssh-agent, so there is no need to install any additional software.

It automatically detects if you have ssh-agents running and uses them. You can configure it to automatically load a set of keys and to forget them on certain occasions.

Is ideal to deal with cronjobs that require SSH access to a different machine. You only need to source the correct file in ~/.keychain file and it the cronjob will be able to use any key you have setup.

Note: This will work even if you logout but it won't if you restart the system or kill the agent. There is now way to keep a key open if the agent is dead unless you store the password in a file. Obviously this would defeat the whole purpose of password protected keys.