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)

 

posted @ 2015-11-11 14:31  Believer007  阅读(981)  评论(0编辑  收藏  举报