Non interactive SSH and OTP
2026-11-18
The question of feeding password and OTP while establishing a SSH has been poping so often in my circles, and almost all the time it points to this particular stackoverflow question.
That accpeted answer is in a way great, shove all the things
in a script and be a victim of ps -ef oopsie.
I wrote one another answer to compete for the worst security practice, following is a mirror of the same for future reference.
This is an answer based on Youjun Hu's but uses a password manager (GPG based) and otp extension for that.
Disclaimer: It's only a bit better than above in terms of privacy standpoint!
For pass(1) to store and encrypt password, you need a gpg private/public key on your system. Following can be used to create one,
$ gpg --full-generate-key
$ gpg --list-keys # make sure 'ultimate is present'
pub ed25519 2026-10-03 [SC]
8713A6BF0B3ED23BE6B5F3200F64BC438BB3C02C
uid [ultimate] hisacro_stackoverflow <hisacro_stack@overflow>
sub cv25519 2026-10-03 [E]
For using the pass, from man 1 pass,
$ pass init hisacro_stackoverflow
$ pass insert hpc/pwd # type in your password, it will be encrypted with your gpg keys
pass(1) needs pass-otp extension for
managing TOTP. Once pass-otp has been setup one can use the provided otpauth://totp/user%his..erflow%saf..?secret=something1345&issuer=me
$ echo "otpauth://..." | pass otp insert hpc/otp
Now both password and otp are stored with gpg encryption on ~/.password-store (default location), this can be checked with
$ pass hpc/pwd
$ pass otp hpc/otp
Just for the first time, you might be asked for GPG password and it will persist later (if necessary timeout behavior can be configured with pass).
Integration with expect(1), adopted Youjun Hu's script,
#!/usr/bin/expect -f
set pwd [exec pass hpc/pwd]
set otp [exec pass otp hpc/otp]
set gate_prompt "*?:~> "
# spawn scp some_file username@gate:~/
# spawn ssh gate
expect "*?assword:"
send -- "${pwd}\r"
expect "*?OTP:"
send -- "${otp}\r"
# for interactive session uncomment below
# interact
expect "*?:~> "
send "touch news \r"
expect "*?:~> "
send -- "exit \r"
expect eof
Save the above file and make it executable, now it can be used as
$ ./expect_script