Linux – ssh without password from a bash script


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?

Best Answer

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.

Related Question