pexecpt run用法:
格式:
run(command,timeout=-1,withexitstatus=False,events=None,extra_args=None,logfile=None, cwd=None, env=None)
返回值:
(command_output, exitstatus) = run ('ls -l /bin', withexitstatus=1)

spawn用法:实现启动子程序,它有丰富的方法与子程序交互从而实现用户对子程序的控制。它主要使用 pty.fork() 生成子进程,并调用 exec() 系列函数执行 command 参数的内容
使用:
child = pexpect.spawn ('/usr/bin/ftp') #执行ftp客户端命令
child = pexpect.spawn ('/usr/bin/ssh user@example.com') #使用ssh登录目标机器
child = pexpect.spawn ('ls -latr /tmp') #显示 /tmp目录内容
需要参数时的用法:
child = pexpect.spawn ('/usr/bin/ftp', [])
child = pexpect.spawn ('/usr/bin/ssh', ['user@example.com'])
child = pexpect.spawn ('ls', ['-latr', '/tmp'])

日志记录:
child = pexpect.spawn('some_command')
fout = file('mylog.txt','w')
child.logfile = fout
child.expect(expect.EOF) ---表示匹配结束
标准输出:
child = pexpect.spawn('some_command')
child.logfile = sys.stdout
记录输出日志:
child = pexpect.spawn('some_command')
child.logfile_send = sys.stdout
写日志必须要有expect才能写入

expect用法:为了控制子程序,等待子程序产生特定输出,做出特定的响应,可以使用 expect 方法
expect(self, pattern, timeout=-1, searchwindowsize=None)
可以加pexpect.EOF , pexpect.TIMEOUT 来控制程序运行时间
如果难以估算程序运行的时间,可以使用循环使其多次等待直至等待运行结束:
while True:
index = child.expect(["suc","fail",pexpect.TIMEOUT])
if index == 0:
break
elif index == 1:
return False
elif index == 2:
pass
expect 不断从读入缓冲区中匹配目标正则表达式,当匹配结束时 pexpect 的 before 成员中保存了缓冲区中匹配成功处之前的内容, pexpect 的 after 成员保存的是缓冲区中与目标正则表达式相匹配的内容
实例:
>>>child = pexpect.spawn('/bin/ls /')
>>>child.expect ('media')
>>>print child.before
bin data etc lib lost+found misc net proc sbin srv tmp usr
boot dev home lib64
>>>print child.after
media

在使用 expect() 时,由于 Pexpect 是不断从缓冲区中匹配,如果想匹配行尾不能使用 “$” ,只能使用 “\r\n”代表一行的结束。 另外其只能得到最小匹配的结果,而不是进行贪婪匹配,例如 child.expect ('.+') 只能匹配到一个字符

send含数用法:
send(self, s)
sendline(self, s='') #会额外输入一个回车符
sendcontrol(self, char) #发送控制字符,例如发送ctrl+c child.sendcontrol('c')
((?i)name) 正则表达式忽略大小写

pexpect 不会解释 shell 的元字符,如重定向 redirect,管道 pipe,必须新开一个必须得重新启动一个新 shell
child = pexpect.spawn('/bin/bash -c "ls -l | grep LOG > log_list.txt"')

脚本实例:

#!/usr/bin/python
import pexpect
import os,sys
from optparse import OptionParser
import logging,multiprocessing #menue
usage='%prog [-h][-s Servers][-c CMDS][--version]' parser=OptionParser(usage=usage,version='HuZhiQiang 2.0_20150609')
parser.add_option('-s','--Server',dest='server',default='ip.txt',help='The Server Info')
parser.add_option('-c','--CMDS',dest='cmd',default='pwd',help='You wann to execute commands')
(options,args)=parser.parse_args()
print options.server,options.cmd logging.basicConfig(level=logging.DEBUG)
logger=logging.getLogger(__name__) handler=logging.FileHandler('hello.txt')
handler.setLevel(logging.INFO) formatter=logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler) #ssh functions
def connect(ip,username,password,port,prompt=']#'):
try:
ssh_newkey='Are you sure you want to continue connecting'
child=pexpect.spawn('ssh '+username + '@'+ip+' -p '+port,maxread=5000)
child.logfile=fout
i=child.expect([prompt,'assword:*',ssh_newkey,'refused',pexpect.TIMEOUT,'key.*? failed'])
#print i
#if not False:
# print child.before,child.after
if i==0:
pass
elif i==1:
child.send(password+'\r')
if i==2:
child.sendline('yes')
if i==4:
raise Exception('Error TIMEOUT!')
if i==3:
print 'Connect refused'
if i==5:
print child.before,child.after
os.remove(os.path.expanduser('~')+'/.ssh/known_hosts')
child.expect('#')
child.sendline(options.cmd)
child.expect(']#')
logging.INFO( 'The command %s result is:' % options.cmd)
logging.INFO( child.before)
except:
print 'Connect Error,Please check!'
#sys.exit() #check -s isn't exits
if os.path.exists(options.server):
filename=options.server
pass
else:
print 'Please check %s and ip.txt is exits' % options.server
exit(-1) #execute
fout=file('mylog.txt','w') for line in open(filename):
ip,user,passwd,port=line.strip().split()
print '*'*50
print 'The follow ip is %s:' % ip
p=multiprocessing.Pool(processes=4)
result=p.apply_async(connect,[ip,user,passwd,port])
print result.get()
#connect(ip,user,passwd,port)

Pexpect学习:的更多相关文章

  1. python pexpect 学习与探索

    pexpect是python交互模块,有两种使用方法,一种是函数:run另外一种是spawn类 1.pexpect  module 安装 pexpect属于第三方的,所以需要安装, 目前的版本是 3. ...

  2. pexpect库学习之包装类详解

    在pexpect库中,包装类的构造参数使用的命令或者要包装命令的提示符,还可以通过这个包装类来修改命令的提示符,那么所谓的包装类实际就是用于给用户交互相应的子命令,它的实例方法主要是“run_comm ...

  3. 雨痕 的《Python学习笔记》--附脑图(转)

    原文:http://www.pythoner.com/148.html 近日,在某微博上看到有人推荐了 雨痕 的<Python学习笔记>,从github上下载下来看了下,确实很不错. 注意 ...

  4. 学习Python要知道哪些重要的库和工具

    本文转自:https://github.com/jobbole/awesome-python-cn 环境管理 管理 Python 版本和环境的工具 p:非常简单的交互式 python 版本管理工具. ...

  5. Python学习笔记—自动化部署【新手必学】

      前言本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理.作者:唯恋殊雨   目录 pexpect fabric pexpect P ...

  6. Python 应用领域及学习重点

    笔者认为不管学习什么编程语言,首先要知道:学完之后在未来能做些什么? 本文将浅谈 Python 的应用领域及其在对应领域的学习重点.也仅是介绍了 Python 应用领域的"冰山一角" ...

  7. 从直播编程到直播教育:LiveEdu.tv开启多元化的在线学习直播时代

    2015年9月,一个叫Livecoding.tv的网站在互联网上引起了编程界的注意.缘于Pingwest品玩的一位编辑在上网时无意中发现了这个网站,并写了一篇文章<一个比直播睡觉更奇怪的网站:直 ...

  8. Angular2学习笔记(1)

    Angular2学习笔记(1) 1. 写在前面 之前基于Electron写过一个Markdown编辑器.就其功能而言,主要功能已经实现,一些小的不影响使用的功能由于时间关系还没有完成:但就代码而言,之 ...

  9. ABP入门系列(1)——学习Abp框架之实操演练

    作为.Net工地搬砖长工一名,一直致力于挖坑(Bug)填坑(Debug),但技术却不见长进.也曾热情于新技术的学习,憧憬过成为技术大拿.从前端到后端,从bootstrap到javascript,从py ...

随机推荐

  1. 安装yeoman报没有权限的错误

    新的ubuntu服务器, 不小心先装了npm, 再装的node, 再用meanjs装的yeoman(即不是自己npm install -g yo装的, 是用meanjs的stack一步到位的),而正常 ...

  2. Linux I/O优化 磁盘读写参数设置

    关于页面缓存的信息,可以用cat /proc/meminfo 看到.其中的Cached 指用于pagecache的内存大小(diskcache-SwapCache).随着写入缓存页,Dirty 的值会 ...

  3. VS2015常用快捷键

    1.回到上一个光标位置/前进到下一个光标位置  1)回到上一个光标位置:使用组合键“Ctrl + -”: 2)前进到下一个光标位置:“Ctrl + Shift + - ”. 2.复制/剪切/删除整行代 ...

  4. multiselect2side:jQuery多选列表框插件

    http://blog.csdn.net/rosanu_blog/article/details/8550723 http://www.bkjia.com/jQuery/449193.html < ...

  5. ajax+json+Struts2实现list传递(转载)

    一.首先需要下载JSON依赖的jar包.它主要是依赖如下: json-lib-2.2.2-jdk15 ezmorph-1.0.4       commons-logging-1.0.4       c ...

  6. SQLServer------备份与还原

    转载: http://www.cnblogs.com/zgqys1980/archive/2012/07/04/2576382.html

  7. 【代码审计】iZhanCMS_v2.1 前台IndexController.php页面存在SQL注入 漏洞分析

      0x00 环境准备 iZhanCMS官网:http://www.izhancms.com 网站源码版本:爱站CMS(zend6.0) V2.1 程序源码下载:http://www.izhancms ...

  8. Linux 集群架构

    集群介绍 Keepalived 配置高可用集群

  9. 系统头文件cmath,cstdlib报错

    >C:\Program Files (x86)\Microsoft Visual Studio\\Community\VC\Tools\MSVC\\include\cstdlib(): erro ...

  10. commons-beanutils的使用

    commons-beanutils是通过内省来完成的. 需要两个包: commons-beanutils-1.8.3.jar commons-logging-1.1.1.jar JavaBean类: ...