带有paramiko interactive.py的Python popen()
嗨,我是python的新手 我现在正在使用popen()方法开发分离ssh shell 该方法使用paramiko演示中的interactive.py代码作为命令带有paramiko interactive.py的Python popen(),python,Python,嗨,我是python的新手 我现在正在使用popen()方法开发分离ssh shell 该方法使用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(pa
#!/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()时,它返回
回溯(最近一次呼叫最后一次):
文件“/sshconn.py”,第43行,在
main()
文件“/sshconn.py”,第20行,主
oldtty=termios.tcgetattr(sys.stdin)
termios.error:(22,“无效参数”)
如何解决这个问题?我认为一个可能的解释是
sys.stdin
没有连接到TTY(它是管道,就像您的Popen
)
如果您想要一个交互式shell,那么应该与之交互。如果需要非交互式shell,理想的解决方案是调用远程程序并等待它返回成功或失败的错误代码。试着用paramiko
来代替,它简单得多。很少有好的理由从Python脚本运行Python文件<代码>导入该文件,并在自己的脚本中使用其类和方法。
#!/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()
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')