2015-07-10 187 views
0

我有我手動執行類似下面運行交互的shell腳本在python

首先,它打印一些消息,然後在最後一個shell腳本詢問用戶名:

>/x/y/somescript "a b c" 

Please enter the credentials of the XXX administrator account to use... 
NOTE: The account provided below must hold the XXXXX role. 

Username: 

然後我進入後用戶名並按ENTER鍵,它要求輸入密碼

Password: 

輸入密碼並按下ENTER鍵後不久,它就會顯示一些所需的輸出,如下所示。

Following is the list of algorithm(s) available in the system 
| Algorithm Name |  Algorithm Type  | Key Size | Status | 
| SHA512withRSA | SIGNATURE_ALGORITHM | -  | enabled | 
| SHA1withDSA | SIGNATURE_ALGORITHM | -  | disabled | 
| SHA256withDSA | SIGNATURE_ALGORITHM | -  | disabled | 
| SHA512withDSA | SIGNATURE_ALGORITHM | -  | disabled | 
| SHA256withECDSA | SIGNATURE_ALGORITHM | -  | enabled | 

現在我想在oo中自動執行此操作。我認爲,對於同樣的問題,觀察者會是一個很好的工具。我寫了一個小腳本。

#!/usr/bin/env python 
import pexpect 

localcmd='/x/y/some_script "a b c"' 

def localOutput(command): 
     child = pexpect.spawn (command) 
     child.expect ('Username: ') 
     child.sendline ('administrator') 
     child.expect ('Password: ') 
     child.sendline ('Testpassw0rd') 
     return child.before # Print the result of the ls command. 

localout=localOutput(localcmd) 

print "output from local query: \n "+localout # print out the result 

但是,當我執行腳本它總是說:

# python final.py 
output from local query: 
administrator 

可有人告訴我,我錯了什麼呢?

+0

在'return child.before'之前插入'child.expect(pexpect.EOF)' – jfs

+0

添加語句後不工作,但現在有不同的輸出。說無效的用戶。但是手動執行時,它的用戶名和密碼就可以工作。但不是在python腳本中。 – user1939168

+0

創建一個虛擬'child.py'腳本來模擬'somescript'的輸出,使用'pexpect'運行它並檢查用戶名,密碼。 – jfs

回答

0

您的函數可能會在pexpect已讀取子進程的所有輸出之前提前返回。您需要添加child.expect(pexpect.EOF),以便讀取所有輸出(也許直到某個緩衝區已滿)。

一個更簡單的選擇是使用pexpect.run() function

output, status = pexpect.runu(command, withexitstatus=1, 
           events={'Username:': 'administrator\n', 
             'Password:': 'Testpassw0rd\n'}) 

如果該命令會產生大量輸出或時間過長(timeout參數)可能有問題。