In writing shell scripts sometimes you want to be able to execute several SSH or SCP commands in a row. Unless you have set up authorised keys on the server, each one of the commands executed in the script will require that the user enter their password for the connection to be established. Or you can use a nice feature of SSH whereby you open a “master connection”. The master connection passes your user’s credentials to the server and then allows several “slave connections” to perform operations through itself without the need for reauthenticating.
Open the master connection
Create and use the slave connections
Close the master connection
Creating a master connection means establishing a connection to the SSH server which does not interact with the user (-N switch), stays in the background after authentication (-f switch), accepts to let slave connections use the communication channel it establishes (-M switch), and that we can store some sort of pointer to (the so-called ControlPath via the -o switch). Here’s how you can do this
ssh -M -f -N -o ControlPath=$SSHSOCKET username@servername
By using the master connection in subsequent ssh or scp commands, you will not be asked to specify username and password again. In order to do this, just use the -o option with ControlPath, but this time without the -M switch.
ssh -o ControlPath=$SSHSOCKET username@servername
scp -o ControlPath=$SSHSOCKET username@servername:remotefile ./
At the end of it all, you must remember to close the master connection. You invoke the ssh command, specify the path of your control socket file (-S switch), then send a control command to it (-O switch) to tell it to exit and close all communication channels.
ssh -S $SSHSOCKET -O exit username@servername
To conclude, it’s worth noting that you can also use this procedure in an interactive context, for example by opening one SSH connection in one terminal as the master (just omit the -N and -f switches) and the open slave connections in other terminals.
Other than this approach, another very common way of establishing SSH connections without the need to worry about entering passwords is that of generating a public/private key combination for yourself, then saving the private key in your local .ssh folder and the public one in .ssh/authorized_keys on the server.