All articles

Password SSH from a script, without sshpass or expect

2 min readNotes

nitrateX Building with agents

Some servers accept only a password, and some machines don't let you install anything. OpenSSH has its own way out: it can ask a helper program for the password instead of the keyboard.

The situation

I needed an agent to run commands on a shared host that accepts password logins only. The usual tools were missing: no sshpass, no expect, no pip to install pexpect, and no sudo to add any of them.

What OpenSSH already offers

SSH_ASKPASS points to a program that prints the password to standard output. OpenSSH used to call it only when there was no terminal and a graphical display was set. Since OpenSSH 8.4, SSH_ASKPASS_REQUIRE=force tells it to use the helper every time.

cat > ~/askpass.sh <<'END'
#!/bin/sh
echo 'your-password'
END
chmod 700 ~/askpass.sh

export SSH_ASKPASS=~/askpass.sh
export SSH_ASKPASS_REQUIRE=force
setsid -w ssh -o StrictHostKeyChecking=accept-new user@host 'echo OK; hostname' < /dev/null

If OK and the host name come back, the helper did its job.

Why setsid -w

In my environment the two variables alone were not enough: ssh still found the terminal and waited for typing. setsid starts the command in a new session with no controlling terminal, so the helper is the only way left to get the password.

The -w matters. Without it, setsid can return right away while ssh keeps running in the background, so you lose both the output and the exit code. With -w it waits and passes the exit code back.

Details that save time

  • < /dev/null keeps ssh from waiting on standard input.
  • On a first connection, -o StrictHostKeyChecking=accept-new accepts the host key without a prompt. It still refuses a key that changed later.
  • scp works the same way: setsid -w scp file user@host:dir/ < /dev/null.
  • SSH_ASKPASS should be an absolute path. Unquoted ~ is expanded by the shell above, so it works.

When to use it

It suits short, supervised jobs: checking a few files, uploading one build, reading a log. For anything that runs on its own every day, set up a key.

Share on X

nitrateX Building with agents

Get new articles by email

Only when a new article is out. No ads. Details →