选项 1:
您可以通过使用 PIPE 重定向输入来重新使用 ssh 进程。
这是一个基本的例子:
[(Z) </tmp> ]% touch input_file
[(Z) </tmp> ]% tailf input_file | ssh <remote_host>
现在尝试在文件中写入一些内容
[(Z) </tmp> ]% echo "date" >> /tmp/input_file
这是一种在 Python 中使用 subprocess 模块来使用它的方法。
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)
这会启动一个可以重复使用的子进程。请注意,close_fds=True 是必需的,因为存在已知错误 (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'
echo 'remote command completed with exit code = '$?\n 行用于知道远程命令已完成并且已完成写入 s.stdout。这对于了解远程命令的退出代码也很有用。
使用相同的子进程执行另一个远程命令:
>>> 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'
回到你的问题,一旦你创建了一个 ssh 子进程,你就可以继续发送远程命令。用户退出后,您可以终止子进程。
>>> s.kill()
选项 2:我从来没有使用过这个,但是 ssh 有一个 ControlMaster 选项可以重新使用 ssh。检查 ssh_config(5) 的手册页