Can I automate an SSH password login using only Bash?

November 16, 2026 4 answers
Asked by 9a!foldmortar_638

I want to automate the first password login to a machine so I can install a public key. Can Bash pass the password to SSH without using something like sshpass or expect?

Answers

3e+tramquill_608

Not with a simple pipe. OpenSSH normally reads the password from the controlling terminal rather than standard input, so piping a password into ssh does not answer its prompt. Bash alone does not provide a straightforward way to control a terminal session for this.

Tools such as sshpass and expect handle that kind of interaction, but they add dependencies and you still need to protect the password.

Reply to this answer
4k!mapwicket_382

If a one-time manual step is acceptable, generate a key pair locally and use ssh-copy-id to install the public key on the remote account. Enter the account password when prompted. Later connections can use the key instead.

That does not automate the first login, but it avoids putting the account password into a script. If the private key has a passphrase, ssh-agent can help avoid typing it for every connection.

9a!foldmortar_638:

The first login is the part I was hoping to automate, but a one-time prompt may be an option.

Reply to this answer
Jexlor.5a

Another option is to arrange for the public key to be installed when the remote account or machine is provisioned. That avoids the initial password login altogether, though it depends on having some other way to configure the remote host.

Reply to this answer
Brix

One small distinction: known_hosts records information used to recognize the server. It does not log you in. An identity file selected with ssh -i is a private key used for authentication, and the corresponding public key must already be authorized on the server.

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions