嗨,我是 python 的新手。
我现在正在使用 popen() 方法开发分离 ssh shell。
"Start a shell process for running commands"
if self.shell:
error( "%s: shell is already running" )
return
cmd = [ './sshconn.py' ]
self.shell = Popen( cmd, stdin=PIPE, stdout=PIPE, stderr=STDOUT,
close_fds=True )
self.stdin = self.shell.stdin
self.stdout = self.shell.stdout
self.pid = self.shell.pid
self.pollOut = select.poll()
self.pollOut.register( self.stdout )
并且这个方法使用 paramiko 的 demo 中的 interactive.py 代码作为命令。
#!/usr/bin/python
import sys
import paramiko
import select
import termios
import tty
def main():
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('host', username='user', password='secret')
tran = ssh.get_transport()
chan = tran.open_session()
chan.get_pty()
chan.invoke_shell()
oldtty = termios.tcgetattr(sys.stdin)
try:
while True:
r, w, e = select.select([chan, sys.stdin], [], [])
if chan in r:
try:
x = chan.recv(1024)
if len(x) == 0:
print '\r\n*** EOF\r\n',
break
sys.stdout.write(x)
sys.stdout.flush()
except socket.timeout:
pass
if sys.stdin in r:
x = sys.stdin.read(1)
if len(x) == 0:
break
chan.send(x)
finally:
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
if __name__ == '__main__':
main()
问题是当 popen() 被执行时,它返回 Traceback (最近一次调用最后一次):
File "./sshconn.py", line 43, in <module>
main()
File "./sshconn.py", line 20, in main
oldtty = termios.tcgetattr(sys.stdin)
termios.error: (22, 'Invalid argument')
我该如何解决这个问题?