1.下载 安装
wget https://pypi.python.org/packages/source/p/pexpect/pexpect-2.4.tar.gz#md5=fe82d69be19ec96d3a6650af947d5665
tar zxvf pexpect-2.4.tar.gz
cd pexpect-2.4/
python setup.py install
示例
child = pexpect.spawn ('/usr/bin/ftp') #执行ftp客户端命令
child = pexpect.spawn ('/usr/bin/ssh [email protected]') #使用ssh登录目标机器
child = pexpect.spawn ('ls -latr /tmp') #显示 /tmp目录内容
expect() 定义
expect(self, pattern, timeout=-1, searchwindowsize=None)
expect() 在执行中可能会抛出两种类型的异常分别是 EOF and TIMEOUF,其中 EOF 通常代表子程序的退出, TIMEOUT 代表在等待目标正则表达式中出现了超时。
实例
child.expect(["suc","fail",pexpect.TIMEOUT,pexpect.EOF])
如果查找suc成功返回0 如果超时返回2 如果子程序推出返回3
send 系列函数
send(self, s)
sendline(self, s='')
sendcontrol(self, char)
close
如果程序运行中间出现了错误,如用户名密码错误,超时或者 EOF,远程 server 连接不上,都会使用 c hild.close(force=True) 关掉 ftp 子程序。调用 close 可以用来关闭与子程序的 connection 连接,如果你不仅想关闭与子程序的连接,还想确保子程序是真的被 terminate 终止了,设置参数 force=True,其最终会调用 c hild.kill(signal.SIGKILL) 来杀掉子程序。
附录
scp命令使用脚本
# -*- coding: utf-8 -*-
import sys
from optparse import OptionParser
import traceback
import pexpect
import datetime
def scp_from(user,host,route_from,route_to,password):
cmd = "scp -r %s@%s:%s %s"%(user,host,route_from,route_to)
print cmd
scp = pexpect.spawn(cmd)
try:
i = scp.expect(['password:',pexpect.EOF],timeout=60)
if i == 0:
scp.sendline(password)
j = scp.expect(['password:',pexpect.EOF],timeout=60)
if j == 0:
print "password wrong for %s"%host
except:
traceback.print_exc()
scp.close()
def scp_to(route_from,user,host,route_to,password):
cmd = "scp -r %s %s@%s:%s"%(route_from,user,host,route_to)
print cmd
scp = pexpect.spawn(cmd)
try:
i = scp.expect(['password:',pexpect.EOF],timeout=60)
if i == 0:
scp.sendline(password)
j = scp.expect(['password:',pexpect.EOF],timeout=60)
if j == 0:
print "password wrong for %s"%host
except:
traceback.print_exc()
scp.close()
def main():
usage1 = "python scp.py from user host route_from route_to passwprd"
usage2 = "=(scp -r user@host:/route_from route_to)"
usage3 = "python scp.py to route_from user host route_ro passwprd"
usage4 = "=(scp -r route_from user@host:/route_ro)"
parser = OptionParser(usage=usage1+usage2+usage3+usage4)
(options,args) = parser.parse_args()
if len(args) < 6 or len(args) > 6 or (args[0] != 'from' and args[0] != 'to'):
print usage1
print usage2
print usage3
print usage4
return
print options
print args
if args[0] == 'from':
user = args[1]
host = args[2]
route_from = args[3]
route_to = args[4]
password = args[5]
else:
user = args[2]
host = args[3]
route_from = args[1]
route_to = args[4]
password = args[5]
if 'from' in args:
scp_from(user,host,route_from,route_to,password)
elif 'to' in args:
scp_to(route_from,user,host,route_to,password)
now = datetime.datetime.now()
now_time = datetime.datetime.strftime(now,'%Y年%m月%d日 %H:%M:%S ')
print now_time
if __name__ == "__main__":
main()