【发布时间】:2018-01-29 13:14:28
【问题描述】:
我使用 Python pexpect(和 winpexpect)通过 ssh 执行命令
if platform.system() == 'Windows':
pexpectmodname = "winpexpect"
from winpexpect import winspawn as spawn
else:
pexpectmodname = "pexpect"
from pexpect import spawn
pexpectmod = __import__(pexpectmodname)
...
# connect
shellCmd = "ssh %s %d -l %s %s" % (portParam, port, username, server.host)
self.spawn = spawn(shellCmd, timeout=self.timeout, env=os.environ, ignore_sighup=False)
...
# DO WORK WITH SSH
...
# close ssh connection #1 (send exit)
self.spawn.sendline('exit')
index = self.spawn.expect([pexpectmod.EOF, "(?i)there are stopped jobs"])
if index == 1:
self.spawn.sendline("exit")
self.spawn.expect([pexpect.EOF])
# close ssh connection #2 (check isalive, send exit and close)
if self.spawn.isalive():
self.spawn.sendline('exit')
self.spawn.close()
# close ssh connection #3 (send sigkill)
import signal
self.spawn.kill(signal.SIGKILL)
如何关闭 self.spawn 以确保 ssh 会话已关闭? Windows 和 UNIX 的跨平台方式是什么?
【问题讨论】:
标签: python ssh pexpect winpexpect