====== python expect模块pexpect简单应用 ====== Pexpect 是一个自动控制的 Python 模块,可以用来ssh、ftp、passwd、telnet 等命令行进行自动交互。 官方网站是 http://www.noah.org/。通过它,可以实现类似 expect 的操作。 例如我们可以用它来写python脚本,实现批量对一系列(大量的、配置相同的)的linux服务器进行操作。 如果你对expect还不太了解,那么可以参考[[linux:expect]] ===== 一、pexpect 安装方式 ===== 以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 pexpect if __name__ == '__main__': user = 'http://www.pythonclub.org' 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