SSH ask password once, reuse password until timeout finishes
(Reposting my comment as an answer per request from klor).
It's not what you want to hear, but this is what key-based authentication is for. So long as you put a passphrase on your private key, it's no less secure than password authentication.
You can use ssh-agent
to avoid needing to enter the passphrase every time, and the -t
option to ssh-agent
will give you the timeout behavior you're after.
# start a shell under ssh-agent with a 5-minute timeout for keys loaded with ssh-add
ssh-agent -t 300 /bin/bash
# add your key(s) to the agent; ssh-add will prompt for passphrase, if one is set
ssh-add
# do some stuff
ssh remote.server cat /some/file
rsync file1 file2 [email protected]:/some/directory
# after 300 seconds, timeout reached, run ssh-add again to re-add your keys
ssh-add
Your script will need some logic to determine when the timeout occurs. One way would be to run ssh
and rsync
with -o BatchMode=yes
, which will prevent interactive authentication methods, so if the key is no longer usable, ssh
will exit instead of prompting for a password. You can use the exit code to determine if you need to run ssh-add
again; $?
should be set to 255
in this case.
You'll still need to work out how to feed the passphrase to ssh-add
, because it doesn't provide a way to accept it programmatically. Unless your script will prompt you to enter it by hand, you'll probably need to use expect
for that part, and that will mean hard-coding the passphrase somewhere.