"Store" a remote SSH session?

You can use a ControlMaster and ControlPersist to allow a connection to persist after the command has terminated:

When used in conjunction with ControlMaster, specifies that the master connection should remain open in the background (waiting for future client connections) after the initial client connection has been closed. If set to no, then the master connection will not be placed into the background, and will close as soon as the initial client connection is closed. If set to yes or 0, then the master connection will remain in the background indefinitely (until killed or closed via a mechanism such as the “ssh -O exit”). If set to a time in seconds, or a time in any of the formats documented in sshd_config(5), then the backgrounded master connection will automatically terminate after it has remained idle (with no client connections) for the specified time.

So, the first SSH command will setup a control file for the connection, and the other two will reuse that connection via that control file. Your ~/.ssh/config should have something like:

Host host
    User root
    ControlMaster auto
    ControlPath /tmp/ssh-control-%C
    ControlPersist 30   # or some safe timeout

And your script won't need any other changes.


You could take a hint from a similar question on StackOverflow and use a bash Here document:

ssh root@host 'bash -s' << EOF
  command1
  command2
  command3
EOF

You can use expect script. It can automate ssh connection and run commands on the remote machine. This code should shed some light on automating the ssh connection.

you are looking for something like this. store the following code in a file foo.expect

#login to the remote machine
spawn ssh username@hostname
expect "?assword" { send "yourpassword\r"}

#execute the required commands; following demonstration uses echo command
expect "$ " {send "echo The falcon has landed\r"}
expect "$ " {send "echo The falcons have landed\r"}
expect "$ " {send "echo Will the BFR? land? \r"}

#exit from the remote machine
expect "$ " {send "exit\r"}

run it as expect foo.expect

You need expect application to run this script. It can be installed with the command apt-get install expect

This book will help you explore expect script. Happy scripting!