Pexpect 是一个用来启动子程序并对其进行自动控制的 Python 模块,它可以用来和像 ssh、ftp、passwd、telnet 等命令行程序进行自动交互。

shell 命令expect使用    http://blog.51cto.com/superleedo/1931418

安装pexpect

打开 https://pypi.org/project/pexpect/#files

下载 wget https://files.pythonhosted.org/packages/09/0e/75f0c093654988b8f17416afb80f7621bcf7d36bbd6afb4f823acdb4bcdc/pexpect-4.5.0.tar.gz

tar zxf pexpect-4.5.0.tar.gz

cd pexpect-4.5.0/

python setup.py install


ssh远程登录,登录成功后执行命令‘ls -lh’示例

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pexpect
import sys
#通过spawn类启动和控制子应用程序
child = pexpect.spawn('ssh root@192.168.1.124')
#将pexpect的输入输出信息写到mylog.txt文件中
fout = file('mylog.txt','w')
child.logfile = fout
#将pexpect的输入输出信息输出到标准输出
#child.logfile = sys.stdout
#expect方法用来判断子程序产生的输出,判断是否匹配相应字符串
child.expect('password:')
#字符串匹配则使用sendline进行回应-----send:发送命令,不回车、sendline:发送命令,回车、sendcontrol:发送控制符,如:sendctrol('c')等价于‘ctrl+c'、sendeof:发送eof
child.sendline('123456')
child.expect('#')
child.sendline('ls -lh')
child.expect('#')

ssh登录还可以使用pexpect的run函数实现

pexpect.run('ssh root@192.168.1.124',events={'password:','123456'})



针对ssh远程登录,pexpect又派生出了pxssh类,在ssh会话操作上再做一层封装

from pexpect import pxssh
import getpass

try:
    s = pxssh.pxssh()   #创建pxssh对象

    hostname = raw_input('hostname:')
    username = raw_input('username:')
    password = getpass.getpass('password:')   #接收密码输入

    s.login(server=hostname,username=username,password=password)  #建立ssh连接

    s.sendline('uptime')  #运行uptime命令
    s.prompt()   #匹配系统提示符
    print s.before  #打印出现系统提示符前的命令输出

    s.sendline('ls -lh')  #运行命令
    s.prompt()   #匹配系统提示符
    print s.before  #打印出现系统提示符前的命令输出

    s.sendline('df -h')  #运行命令
    s.prompt()   #匹配系统提示符
    print s.before  #打印出现系统提示符前的命令输出

    s.logout()  #断开ssh连接

except pxssh.ExceptionPxssh as e:
    print 'pxssh failed on login'
    print str(e)



自动化FTP示例

#!/usr/bin/env python
# -*- coding: utf-8 -*-

form __future__ import unicode_literals	#使用unicode编码
import pexpect
import sys

child=pexpect.spawnu('ftp ftp.openbsd.org')
child.expect('(?i)name .*: ')	#(?i)忽略大小写
child.sendline('anonymous')
child.expect('(?i)password')
child.sendline('mima123456')
child.expect('ftp> ')
child.sendline('bin')	#开启二进制传输
child.expect('ftp> ')
child.sendline('get test.txt')
child.expect('ftp> ')
sys.stdout.write(child.before)
print("Escape character is '^]'.\n")
sys.stdout.write(child.after)
sys.stdout.flush()
child.interact()
child.sendline('bye')
child.close()


远程文件打包并下载示例

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import pexpect
import sys

ip="192.168.1.124"
user="root"
passwd="kkl123456"
target_file="/data/logs/nginx.log"

child=pexpect.spawn('/usr/bin/ssh', [user+'@'+ip])
fout=file('mylog.txt','w')
child.logfile=fout

try:
	child.expect('(?i)password')
	child.sendline(passwd)
	child.expect('#')
	child.sendline('tar -zcf /data/logs/nginx.tar.gz ' +target_file)
	child.expect('#')
	print child.before
	child.sendline('exit')
	fout.close()
except EOF:
	print "expect EOF"
except TIMEOUT:
	print "expect TIMEOUT"

child=pexpect.spawn('/usr/bin/scp', [user+'@'+ip+':/data/logs/nginx.tar.gz','/home'])
fout=file('mylog.txt','a')
child.logfile=fout

try:
	child.expect('(?i)password')
	child.sendline(passwd)
	child.expect(pexpect.EOF)
except EOF:
	print "expect EOF"
except TIMEOUT:
	print "expect TIMEOUT"