Pexpect简单的测试——一个 expect的python实现

来源:互联网 发布:淘宝知识产权如何申请 编辑:程序博客网 时间:2024/05/19 08:44


 

Pexpect简单的测试——一个 expect的python实现

 

@for & ever 2010-07-03

 

Pexpect 是一个自动控制的 Python 模块,可以用来ssh、ftp、passwd、telnet 等命令行进行自动交互。
官方网站是 http://www.noah.org/
通过它,可以实现类似 expect 的操作。
例如我们可以用它来写python脚本,实现批量对一系列(大量的、配置相同的)的linux服务器进行操作。

 

一、安装方式
以root用户依次执行如下命令:
 wget http://pexpect.sourceforge.net/pexpect-2.3.tar.gz
 tar xzf pexpect-2.3.tar.gz
 cd pexpect-2.3
 sudo python ./setup.py install


二、简单测试

编写一个简单的脚本pexpect_test.py测试一下

#!/usr/bin/env python# -*- coding: utf-8 -*-# filename: pexpect_test.py'''Created on 2010-7-2@author: forever'''import pexpectif __name__ == '__main__':    user = 'forever'    ip = '192.168.0.200'    mypassword = 'forever'        print user    child = pexpect.spawn('ssh %s@%s' % (user,ip))    child.expect ('password:')    child.sendline (mypassword)        child.expect('$')    child.sendline('sudo -s')    child.expect (':')    child.sendline (mypassword)    child.expect('#')    child.sendline('ls -la')    child.expect('#')    print child.before   # Print the result of the ls command.    child.sendline("echo '112' >> /home/forever/1.txt ")    child.interact()     # Give control of the child to the user.    pass

0 0