OPTION 1: You can reuse the ssh process by redirecting input using PIPE.
Here is an example:
[(Z) </tmp> ]% touch input_file [(Z) </tmp> ]% tailf input_file | ssh <remote_host>
Now try to write something to a file
[(Z) </tmp> ]% echo "date" >> /tmp/input_file
Here is a way to use this in Python using the subprocess module.
import subprocess SSH_CMD = "cat -| /usr/bin/ssh -o PasswordAuthentication=no -T -x %s " HOSTNAME = "127.0.0.1" s = subprocess.Popen(SSH_CMD%HOSTNAME , shell=True, close_fds=True, stdin=subprocess.PIPE, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
This starts a subprocess that can be reused. Note that close_fds=True is required due to a known bug ( http://bugs.python.org/issue2320 ).
>>> REMOTE_CMD = "date" >>> s.stdin.write( REMOTE_CMD + ... "\necho 'remote command completed with exit code = '$?\n") >>> s.stdout.readline() 'Thu Feb 16 20:01:36 PST 2012\n' >>> s.stdout.readline() 'remote command completed with exit code = 0\n'
Line
echo 'remote command completed with exit code = '$?\n used to know that the remote command has completed and is being written to s.stdout. It is also useful to know the exit code of the remote command.
To use the same subprocess to execute another remote command:
>>> REMOTE_CMD = "uptime" >>> s.stdin.write( REMOTE_CMD + ... "\necho 'remote command completed with exit code = '$?\n") >>> s.stdout.readline() ' 20:02:17 up 28 days, 9:15, 48 users, load average: 0.01, 0.02, 0.05\n' >>> s.stdout.readline() 'remote command completed with exit code = 0\n'
Returning to your question, once you create the ssh subprocess, you can continue to send remote commands. Once the user completes, you can kill the subprocess.
>>> s.kill()
OPTION 2: I never used this, but ssh has the ControlMaster option to reuse ssh. Check the man page for ssh_config (5)