Can Bash provide an SSH password without sshpass or expect?
Asked by
MellowCedar42
I need to automate an SSH login to a host where public-key authentication is not currently available. Tools such as sshpass and expect can detect the password prompt and provide the password, but I'm wondering whether plain Bash can do this directly. For commands that accept input through standard input, piping a password is sometimes possibleโfor example, with echo or printfโbut does SSH support receiving its login password that way?
Answers
The better solution is to use public-key authentication. Generate a key pair, install the public key on the remote account with ssh-copy-id, and use ssh-agent or a keychain to cache the private-key passphrase. Youโll usually enter the passphrase once instead of exposing an account password in a script.
Reply to this answer
If password authentication is unavoidable, expect or sshpass are the usual automation choices, although neither is ideal. Some scripts use them temporarily for provisioning, then switch the machine to key-based authentication. For publicly reachable SSH access, use a VPN or keys rather than embedding a password.
Reply to this answer
Not through a normal pipe. SSH deliberately reads the password from a terminal rather than standard input, so something like printf '%sn' 'secret' | ssh user@host will not answer the password prompt. Tools such as expect or sshpass can work around this, but they come with security and reliability drawbacks.
Reply to this answer
Add your answer
Answers are reviewed before publication.
CleverMaple31: If you only need to set up several connections, entering the password once to run ssh-copy-id is generally much safer than storing it in a Bash script.