python pexpect 模块
Pexpect 模塊
兩個主要接口
pexpect.run('ls -la')
?
child = pexpect.spawn('scp foo myname@host.example.com:.')
? ? ? ? child.expect ('Password:')
? ? ? ? ##在這個地方會阻塞,直到出現(xiàn)password或者超時推出
? ? ? ? child.sendline (mypassword)
管道符的特殊處理
?
shell_cmd = 'ls -l | grep LOG > log_list.txt'
? ? ? ? ? ? ? ?child = pexpect.spawn('/bin/bash', ['-c', shell_cmd])
? ? ? ? ? ? ? ?child.expect(pexpect.EOF) #等待斷開
將log日志重定向到某個文件或者標(biāo)準(zhǔn)輸出
fout = open('filename','w+')
child.logfile = fout
child.logfile = sys.stdout
fout.close()
如果是僅僅看child返回的信息,而不看你寫給child的信息,那么
child.logfile_read = sys.stdout
寫給child的信息則是
child.logfile_send = sys.stdout
?
? ? try:
? ? ? ? child.sendline('ls -l')
? ? ? ? child.expect(pexpect.EOF)
? ? ? ? #child.prompt()
? ? ? ? print child.before
? ? except:
expect不斷的讀入緩沖區(qū)內(nèi)容等待匹配結(jié)束,before代表匹配前的內(nèi)容,即ls的執(zhí)行結(jié)果,after代表匹配之后的內(nèi)容
child.before child.buffer? ? ? ? ? ? ? ? ? ?
?
另外在pexpect中,有一個很好用的接口,就是sendcontrol(),比如說sendcontrol('c'),向目標(biāo)機器發(fā)送一個中斷符號,主要用在前面的命令執(zhí)行時間過長,退出當(dāng)前命令,并使當(dāng)前命令對后續(xù)命令沒有影響,比如說expect('~#', 3),此時發(fā)生了超時,后續(xù)再發(fā)送命令,可能那個超時的命令的結(jié)果還將輸出,就會對當(dāng)前的結(jié)果有影響,發(fā)送sendcontrol('c'),則好的多,再expect()一下就ok啦
sendeof(),只能用在開頭處,另外對于某些平臺是發(fā)送ctrl+d命令,所以還是不是很好用
參考文獻(xiàn): http://www.ibm.com/developerworks/cn/linux/l-cn-pexpect1/ http://www.ibm.com/developerworks/cn/linux/l-cn-pexpect2/?
?
?
?
?
轉(zhuǎn)載于:https://blog.51cto.com/3502990/653254
總結(jié)
以上是生活随笔為你收集整理的python pexpect 模块的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 回调函数的含义
- 下一篇: python 钩子函数的使用