Safely remembering ssh credentials in bash script

2019-02-21 08:24发布

This question already has an answer here:

Imagine I have a bash script that executes commands on a remote machine via ssh:

# Do something here
ssh otheruser@host command1
# Do something else
ssh otheruser@host command2
# Do most local tasks

This script prompts me to enter credentials for otheruser@host multiple times. Is there a safe, easy, and accepted way to cache these credentials for the lifetime of the script but guarantee that they are lost after the script ends (either normally or when an error occurs)? Maybe a solution will use ssh-agent?

I am looking for something like this:

special_credential_saving_command_here # This will prompt for credentials
ssh otheruser@host command1 # This will not prompt now
ssh otheruser@host command2 # This will not prompt either

My motivation here is to avoid entering the credentials multiple times in the same script while not running the risk of those credentials persisting after the script has terminated. Not only is entering the credentials cumbersome, it also requires I wait around for the script to finish so that I can enter the credentials rather than leave it to run on its own (it's a long running script).

标签: linux bash ssh
1条回答
ら.Afraid
2楼-- · 2019-02-21 09:04

Use a control socket to share an authenticated connection among multiple processes:

ssh -fNM -S ~/.ssh/sock otheruser@host  # Will prompt for password, then exit
...
ssh -S ~/.ssh/sock otheruser@host command1
ssh -S ~/.ssh/sock otheruser@host command2
...
ssh -S ~/.ssh/sock -O exit otheruser@host  # Close the master connection

See man ssh_config, under the ControlPath option, for information on how to create a unique path for the control socket.

查看更多
登录 后发表回答