繁体   English   中英

带有paramiko Interactive.py的Python popen()

[英]Python popen() with paramiko interactive.py

嗨,我是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的演示中的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(最近一次调用为last):

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')

我该如何解决?

我认为,一个可能的解释是, sys.stdin未连接到一个TTY(这是一个PIPE在你Popen )。

如果需要交互式外壳,则应与其交互。 如果要使用非交互式外壳,理想的解决方案是调用一个远程程序,然后等待它返回成功或失败的错误代码。 尝试使用paramiko只是exec_command() ,这要简单得多。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM