Pexpect学习:
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学习:的更多相关文章
- python pexpect 学习与探索
pexpect是python交互模块,有两种使用方法,一种是函数:run另外一种是spawn类 1.pexpect module 安装 pexpect属于第三方的,所以需要安装, 目前的版本是 3. ...
- pexpect库学习之包装类详解
在pexpect库中,包装类的构造参数使用的命令或者要包装命令的提示符,还可以通过这个包装类来修改命令的提示符,那么所谓的包装类实际就是用于给用户交互相应的子命令,它的实例方法主要是“run_comm ...
- 雨痕 的《Python学习笔记》--附脑图(转)
原文:http://www.pythoner.com/148.html 近日,在某微博上看到有人推荐了 雨痕 的<Python学习笔记>,从github上下载下来看了下,确实很不错. 注意 ...
- 学习Python要知道哪些重要的库和工具
本文转自:https://github.com/jobbole/awesome-python-cn 环境管理 管理 Python 版本和环境的工具 p:非常简单的交互式 python 版本管理工具. ...
- Python学习笔记—自动化部署【新手必学】
前言本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理.作者:唯恋殊雨 目录 pexpect fabric pexpect P ...
- Python 应用领域及学习重点
笔者认为不管学习什么编程语言,首先要知道:学完之后在未来能做些什么? 本文将浅谈 Python 的应用领域及其在对应领域的学习重点.也仅是介绍了 Python 应用领域的"冰山一角" ...
- 从直播编程到直播教育:LiveEdu.tv开启多元化的在线学习直播时代
2015年9月,一个叫Livecoding.tv的网站在互联网上引起了编程界的注意.缘于Pingwest品玩的一位编辑在上网时无意中发现了这个网站,并写了一篇文章<一个比直播睡觉更奇怪的网站:直 ...
- Angular2学习笔记(1)
Angular2学习笔记(1) 1. 写在前面 之前基于Electron写过一个Markdown编辑器.就其功能而言,主要功能已经实现,一些小的不影响使用的功能由于时间关系还没有完成:但就代码而言,之 ...
- ABP入门系列(1)——学习Abp框架之实操演练
作为.Net工地搬砖长工一名,一直致力于挖坑(Bug)填坑(Debug),但技术却不见长进.也曾热情于新技术的学习,憧憬过成为技术大拿.从前端到后端,从bootstrap到javascript,从py ...
随机推荐
- SharePoint PowerShell使用Backup-SPSite指令来备份网站集
备份网站集: Backup-SPSite -Identity http://win2012sp2013:1000/ -Path "C:\KenmuTemp\Test File\Temp\si ...
- c++浅拷贝和深拷贝---14
原创博文,转载请标明出处--周学伟http://www.cnblogs.com/zxouxuewei/ 1.什么是拷贝构造函数: 拷贝构造函数,又称复制构造函数,是一种特殊的构造函数,它由编译器调用来 ...
- 5 -- Hibernate的基本用法 --1 4 Hibernate概述
Hibernate 不仅仅管理Java类到数据库的映射(包括Java数据类型到SQL数据类型的映射),还提供数据查询和获取数据的方法,可以大幅度减少开发时人工使用SQL和JDBC处理数据的时间.
- maven打包 jar
最后更新时间: 2014年11月23日 1. maven-shade-plugin 2. maven-assembly-plugin 3. maven-onejar-plugin maven-shad ...
- Netty权威指南之AIO编程
由JDK1.7提供的NIO2.0新增了异步的套接字通道,它是真正的异步I/O,在异步I/O操作的时候可以传递信号变量,当操作完成后会回调相关的方法,异步I/o也被称为AIO,对应于UNIX网络编程中的 ...
- Ansible Playbook 使用循环语句
如下,with_items 是循环的对象,with_items 是 python list 数据结构,task 会循环读取 list 里面的值,key 的名称是 item [root@localhos ...
- [PyCharm] 设置自动启动时自动打开项目
设置启动PyCharm时自动打开(或不打开)上次进行的项目: 选择 “Settings - General - Reopen last project on startup”,勾选该选项则启动时自动打 ...
- 嵌入式之UBOOT
嵌入式Linux系统的结构分为四个区,如图所示: 1.Bootloader区存放的是Bootloader,Coidre972开发板上使用的uboot,它负责嵌入式系统最初的硬件初始化.驱动和内核加载. ...
- js 中的break continue return
break:跳出整个循环 1.当i=6时,就跳出了整个循环,此for循环就不继续了: continue:跳出当前循环,继续下一次循环: return :指定函数返回值 1.在js当中,常使用retur ...
- Swift - static和class的使用
Swift中表示 “类型范围作用域” 这一概念有两个不同的关键字,它们分别是static和class.这两个关键字确实都表达了这个意思,但是在其他一些语言,包括Objective-C中,我们并不会特别 ...