Shell – How to type in password for multiple windows

gnome-terminalgnome3shell-scriptsshvagrant

I have a script that starts my vagrant machine, opens up multiple terminals and connects to the vagrant machine via ssh in every newly opened terminal. My problem is that I need about five terminals, and I don't want to type in the password for each terminal manually. Is there a way to get prompted for the password only once in the main terminal, and use the same password for the ssh command?

#!/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! ~~~"

Best Answer

In general (ignoring vagrant or other system-specific details) your best bet is to set up authentication with SSH keys, and run ssh-agent. Then open the ssh sessions with something like:

# 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

Or, if you can't use keys, you could rig something up with sshpass.

read -p "Enter password: " -s SSHPASS ; echo
for x in 1 2 3 ; do 
    sshpass -e ssh ...
done
unset SSHPASS

Though with the terminal in the middle, this would leave the password set in the terminal's environment. To work around that, you could save the password temporarily in a file:

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"

This still isn't optimal since there's a chance the password hits the disk, so keys would be better.

Related Question