2015-11-03 17 views
2

我正在使用Python和pexpect爲網絡設備自動執行CLI界面。 問題是我無法使用pexpect發送需要「是」/「否」確認的命令。 我認爲這是因爲pexpect不符合問題。如何使用pexpect在CLI上響應命令問題?

child = pexpect.spawn ('ssh -p <port> [email protected]') 
child.expect ("password: ") 
child.sendline ('userPass') 
child.expect ('> ') 
child.sendline('show') 
child.expect('> ') 
logging.info(child.before) 

# works fine untill now - it connects to the box and prints the show output 

child.sendline ('reset') 

logging.info(child.before) 
# this command prints the same thing as previous child.before 

logging.info('This line gets printed.') 

child.expect ("<additional text> Are You sure? [no,yes] ") 

logging.info('This line does not get printed.') 

child.sendline ('yes') 

回答

0

轉義期望文本後,「是」仍未被接受/發送至設備。 我通過發送和「是」後附加線(「」)解決了該問題:

child.sendline ('yes') 
child.sendline('') 
+0

在你的代碼中存在幾個問題。您應該嘗試將問題限制爲每個問題的一個問題(即,首先嚐試本地化您的問題)。否則,*每個*答案應該解決所有問題(這不是傳統的論壇)。我懷疑你的代碼需要'child.expect(pexpect.EOF); child.close()'在最後。 – jfs

2

試試這個:

import re 

child.expect(re.escape("<additional text> Are You sure? [no,yes] ")) 

我認爲,(但現在不檢查文檔)是Pexpect的處理文本的正則表達式。這對匹配不一定是常數的東西很有用。然而,這意味着當你想匹配在正則表達式語法中有意義的字符時(例如'?','['和']'),那麼你需要相應地轉義它們。

+0

是的,添加添加逃生導致文本的成功匹配。謝謝! – dan

0

[]?是正則表達式元字符(他們有特殊的意義,而不是逐字匹配)。爲避免將模式解釋爲正則表達式,請改爲使用child.expect_exact(your_pattern)