Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am writing a bash script that should start a serf agent( on a remote machine via ssh. I have set up rsa keys using...

ssh-key-gen -t rsa -b 4096
ssh-copy-id -i ~/.ssh/ <remote-host>

And I can ssh into the remote machine without a password from the terminal. This is the call I'm making in the script

ssh <user>@<hostname> "serf agent -node database -event-handler user:database_install=~/"

But when the script is executing, I have to use this command in order to run it without password prompt...

ssh -i ~/.ssh/ <remote-host> <command>

Why do I have to do this in the script when I don't need to do it in the terminal?

share|improve this question
shouldn't '' be the PUBLIC key ? the -i flag is supposed to be used to provide the PRIVATE key to ssh. – mveroone Mar 21 '14 at 8:47
possible duplicate of Log in using SSH without password – Cees Timmerman Aug 28 '15 at 12:11

ssh -i selects a file from which the identity (private key) or public key authentication is read.

You could configure ssh to use it in your config for this host so you do not have to specify it.

Add to ~/.ssh/config (replace with hostname or IP of your server):

    User username
    PreferredAuthentications publickey,password
    IdentityFile ~/.ssh/

This config will make your connection to always try to use key and then fallback to password if key would not be available for some reason.

So now you should be able to use ssh <user>@<host> <command> with it automatically using your private key for authentication.

share|improve this answer
Okay. So even though I used...ssh-copy-id -i ~/.ssh/ <remote-host> the ssh call in the bash script is not using the key? – restin84 Mar 21 '14 at 15:51
Nowhere in my answer did I tell you to use ssh-copy-id, so please reread my answer. – phoops Mar 21 '14 at 16:21
I understand that you did not mention ssh-copy-id but you did not say NOT to use it. However I did what you said. I've called the host database. In the terminal the call to ssh is successful (no password/passphrase). If I do the same command in the bash script I get this error: ssh: Could not resolve hostname database: Name or service not known – restin84 Mar 21 '14 at 16:39

Have you tried ssh-add on the system start?

ssh-add — adds private key identities to the authentication agent

you can use this command and by default on connection ssh will try to use your private keys and only after that - password.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.