使用os.forkpty()创建伪终端以ssh到远程服务器并与之通信 [英] Using os.forkpty() to create a pseudo-terminal to ssh to a remote server and communicate with it

查看:181
本文介绍了使用os.forkpty()创建伪终端以ssh到远程服务器并与之通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个python脚本,该脚本可以ssh到远程服务器,并可以从python客户端执行简单的命令,例如ls,cd.但是,在成功地切入服务器后,我无法从伪终端读取输出.任何人都可以在这里帮助我,以便我可以在服务器上执行一些命令.

I'm trying to write a python script that can ssh into remote server and can execute simple commands like ls,cd from the python client. However, I'm not able to read the output from the pseudo-terminal after successfully ssh'ing into the server. Could anyone please help me here so that I could execute some commands on the server.

这是示例代码:

#!/usr/bin/python2.6
import os,sys,time,thread
pid,fd = os.forkpty()
if pid == 0:
    os.execv('/usr/bin/ssh',['/usr/bin/ssh','user@host',])
    sys.exit(0)
else:
    output = os.read(fd,1024)
    print output
    data = output
    os.write(fd,'password\n')
    time.sleep(1)
    output = os.read(fd,1024)
    print output
    os.write(fd,'ls\n')
    output = os.read(fd,1024)
    print output

示例输出:

user@host's password: 

Last login: Wed Aug 24 03:16:57 2011 from 1x.x.x.xxxx

-bash: ulimit: open files: cannot modify limit: Operation not permitted
host: /home/user>ls

推荐答案

我建议尝试模块pexpect,它是专门为此类事物(通过伪TTY与其他应用程序接口)或Fabric而构建的是为这种事情构建的,更抽象(使用SSH在远程服务器上自动执行系统管理任务).

I'd suggest trying the module pexpect, which is built exactly for this sort of thing (interfacing with other applications via pseudo-TTYs), or Fabric, which is built for this sort of thing more abstractly (automating system administration tasks on remote servers using SSH).

pexpect: http://pypi.python.org/pypi/pexpect/

面料: http://docs.fabfile.org/zh/1.11/

这篇关于使用os.forkpty()创建伪终端以ssh到远程服务器并与之通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆