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 pexpect
- if __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
如果执行命令中有 (>, |, or *) 的操作, 需要用以下形式
shell_cmd = 'ls -l | grep LOG > log_list.txt'
child = pexpect.spawn('/bin/bash', ['-c', shell_cmd])
class spawn(object) def __init__(self, command, args=[], timeout=30, maxread=2000, searchwindowsize=None, logfile=None, cwd=None, env=None)
This is the constructor. The command parameter may be a string that includes a command and any arguments to the command. For example:
child = pexpect.spawn ('/usr/bin/ftp')
child = pexpect.spawn ('/usr/bin/ssh user@example.com')
child = pexpect.spawn ('ls -latr /tmp')
You may also construct it with a list of arguments like so:
child = pexpect.spawn ('/usr/bin/ftp', [])
child = pexpect.spawn ('/usr/bin/ssh', ['user@example.com'])
child = pexpect.spawn ('ls', ['-latr', '/tmp'])
After this the child application will be created and will be ready to talk to. For normal use, see expect() and send() and sendline().
Remember that Pexpect does NOT interpret shell meta characters such as redirect, pipe, or wild cards (>, |, or *). This is a common mistake. If you want to run a command and pipe it through another command then you must also start a shell. For example:
child = pexpect.spawn('/bin/bash -c "ls -l | grep LOG > log_list.txt"')
child.expect(pexpect.EOF)
The second form of spawn (where you pass a list of arguments) is useful in situations where you wish to spawn a command and pass it its own argument list. This can make syntax more clear. For example, the following is equivalent to the previous example:
shell_cmd = 'ls -l | grep LOG > log_list.txt'
child = pexpect.spawn('/bin/bash', ['-c', shell_cmd])
child.expect(pexpect.EOF)