如何为多个窗口输入密码?

Chr*_*ris 5 ssh shell-script gnome-terminal gnome3 vagrant

我有一个脚本可以启动我的流浪机器,打开多个终端并在每个新打开的终端中通过 ssh 连接到流浪机器。我的问题是我需要大约五个终端,我不想手动输入每个终端的密码。有没有办法在主终端中只提示输入一次密码,并为 ssh 命令使用相同的密码?

#!/bin/bash
cd /home/kkri/public_html/freitag/vagrant
vagrant up
for run in $(seq 1 $1)
 do
  gnome-terminal --window-with-profile=dark -e "ssh vagrant@localhost -p 2222" --$
 done
gnome-terminal --window-with-profile=git          
clear
echo "~~~ Have fun! ~~~"
Run Code Online (Sandbox Code Playgroud)

ilk*_*chu 9

通常(忽略 vagrant 或其他特定于系统的详细信息)您最好的选择是使用 SSH 密钥设置身份验证,然后运行ssh-agent. 然后使用以下内容打开 ssh 会话:

# load the key to the agent with a 10 s timeout
# this asks for the key passphrase
ssh-add -t10  ~/.ssh/id_rsa  
for x in 1 2 3 ; do 
    ssh .... 
done
Run Code Online (Sandbox Code Playgroud)

或者,如果您不能使用密钥,则可以使用sshpass.

read -p "Enter password: " -s SSHPASS ; echo
for x in 1 2 3 ; do 
    sshpass -e ssh ...
done
unset SSHPASS
Run Code Online (Sandbox Code Playgroud)

尽管终端位于中间,但这会将密码设置在终端环境中。要解决此问题,您可以将密码临时保存在文件中:

read -p "Enter password: " -s SSHPASS ; echo
PWFILE=~/.ssh/secret_password
cat <<< "$SSHPASS" > "$PWFILE"
unset SSHPASS
for x in 1 2 3 ; do 
    sshpass -f "$PWFILE" ssh ...
done
shred --remove "$PWFILE"
Run Code Online (Sandbox Code Playgroud)

这仍然不是最佳的,因为密码有可能命中磁盘,所以密钥会更好。