用pexpect做交互式的程序

来源:互联网 发布:网络管理小结 编辑:程序博客网 时间:2024/06/01 10:14

http://www.ibm.com/developerworks/cn/linux/l-cn-pexpect1/


其中一个ftp的例子是

import os
import sys

(command_output, exitstatus)  = pexpect.run('ls -la', withexitstatus=1)
#print "%s, %d" %(command_output, exitstatus)

child = pexpect.spawn('ftp ftp.openbsd.org')
child.logfile = sys.stdout
child.expect('Name .*: ')
child.sendline('anonymous')
child.expect('Password:')
child.sendline('ex@example.com')
child.expect('ftp> ')
child.sendline('cd pub/OpenBSD')
child.expect('ftp> ')
child.sendline('get README')
child.expect('ftp> ')
child.sendline('bye')

1。 需要注意的是中间这个 child.logfile = sys.stdout 用来表明在标准输出中显示log。

如果不加这个,那么交互的输出将不会在stdout中显示。


2。 还有就是用pexpect.run()执行一个命令的输出在 返回值中,晕阿,开始我还一直以为会直接在stdout中显示的。。。


下面是个telnet的例子,本来想加密的,后来发现不好做。 先留着吧。

#!/usr/bin/python
import os
import sys
import pexpect
import base64


def main():
    
    host_name = raw_input("Enter the host name: ")
    
    if host_name == "haven":
        host_name = "haven.au.ibm.com"
    elif host_name == "ford11":
        host_name = "ford11.ltc.austin.ibm.com"
    elif host_name == "zhangli":
        host_name = "9.3.190.254"
    else:
        print "Unknown host name"
        exit()
    
    telnet_cmd = "telnet %s" %(host_name)
    
    try:
        child = pexpect.spawn(telnet_cmd)
        child.logfile = sys.stdout
        i = child.expect(['Username: ', 'Unable to connect to remote host'], 30)
        if i == 0:
            child.sendline('ywywyang@cn.ibm.com')
            child.expect('Password:')
            child.sendline('144025_shyw_')
            i == child.expect(['BSO Authentication Successful', 'BSO Authentication Error'])
            if i == 0:
                print "Passed"
            else:
                print "Try Again"
        else:
            print "You passed the BSO already"
            child.close()
    except pexpect.EOF:
        child.close()
    except pexpect.TIMEOUT:
        print "Connection timeout"
        clile.close()
    else:
        child.close()

if __name__ == "__main__":
    main()