Automatically "enter password" for OpenSSH

Reason
I just want to copy the SSH Key to the new mechine
- Add new machines from time to time
- Configration the SSH Key not yet
- I don’t want to input the password by manual every time
In theory, one ssh-copy-id can solve the problem, but the reality is: ssh just doesn’t let you pipe your password in.
echo password | ssh user@host
This is not valid or don’t work.
This is not a bug, it is a design choice of OpenSSH.
Why is OpenSSH so “stubborn”?
OpenSSH is very conservative about passwords:
- Do not read password from STDIN
- Scripted password authentication is discouraged
- Forces you to either use TTY or key
It makes perfect sense from a security perspective, but it does feel a little uncomfortable during the initialization phase.
After looking through the documentation and source code, I found that
OpenSSH actually has a “backdoor”, but it never recommends you use it:
SSH_ASKPASS
What is the SSH_ASKPASS
Simply put:
- ssh without TTY
- If SSH_ASKPASS is detected
- will execute it
- Read password back from STDOUT
This is not a hack, this is an official mechanism.
It’s just that the usage conditions are very harsh.
The core point: you must “have no terminal”
This is the deepest hole I have stepped into.
As long as ssh thinks it’s still connected to the TTY:
- AskPass is never called
- It will just wait for you to enter it manually
There is only one solution: setsid
My implementation
What I ended up using was a very primitive, yet completely controllable method.
Generate a temporary AskPass program
ssh_helper() {
ASKPASS="$(mktemp)"
cat >"$ASKPASS" <<'EOF'
#!/bin/sh
echo "$PASS"
EOF
chmod 700 "$ASKPASS"
}
It does nothing but echo the password.
execute
PASS="$PASSWORD" \
SSH_ASKPASS="$ASKPASS" \
DISPLAY=dummy \
setsid -w ssh-copy-id \
-i ~/.ssh/id_rsa.pub \
-p port \
user@host
- SSH_ASKPASS: tells ssh where to go to ask for the password
- DISPLAY=dummy: Even if it is fake, it must be there
- setsid: This is the soul
If any one is missing in the list, you will fail.
Is this thing safe?
Let’s be honest: not safe. At least not “elegant”.
- Password is clear text
- in environment variables
- Visible to the same user process
So I only use it when I need to batch initialize it in a shell script. After success, I immediately switch to key login.
Be sure to delete it after use
This cannot be omitted:
rm -f "$ASKPASS"
Temporary files are a time bomb if left alone.
my conclusion
SSH_ASKPASS is like the narrow path OpenSSH leaves for advanced users:
- Not written in the novice tutorial
- You are not encouraged to use
- But after you really understand the ssh behavior model, it is reasonable and self-consistent
I wouldn’t use it as a regular solution, but it has saved me a lot of time as long as I know what I’m doing.
If you’ve read this far, you probably need it.