2013-09-30 51 views
1

我有一個Python例程,它調用某種CLI(例如telnet),然後執行其中的命令。問題是CLI有時會拒絕連接,並且在主機shell中執行命令導致各種錯誤。我的想法是在調用CLI後檢查shell提示是否改變。如何在Python中獲取實際的shell提示字符串?

問題是:如何在Python中獲取shell提示字符串?

呼應PS1是不是一個解決方案,因爲一些的CLI無法運行它,它返回一個符號般的字符串,而不是實際的提示:

SC-2-1:~ # echo $PS1 
\[\]\h:\w # \[\] 

編輯

我的例行:

def run_cli_command(self, ssh, cli, commands, timeout = 10): 
    ''' Sends one or more commands to some cli and returns answer. ''' 
    try: 
     channel = ssh.invoke_shell() 
     channel.settimeout(timeout) 
     channel.send('%s\n' % (cli)) 
     if 'telnet' in cli: 
      time.sleep(1) 
     time.sleep(1) 
     # I need to check the prompt here 
     w = 0 
     while (channel.recv_ready() == False) and (w < timeout): 
      w += 1 
      time.sleep(1) 
     channel.recv(9999) 
     if type(commands) is not list: 
      commands = [commands] 
     ret = '' 
     for command in commands: 
      channel.send("%s\r\n" % (command)) 
      w = 0 
      while (channel.recv_ready() == False) and (w < timeout): 
       w += 1 
       time.sleep(1) 
      ret += channel.recv(9999) ### The size of read buffer can be a bottleneck... 
    except Exception, e: 
     #print str(e) ### for debugging 
     return None 
    channel.close() 
    return ret 

一些解釋需要在這裏:ssh參數是一個paramiko.SSHClient()實例。我使用此代碼登錄到服務器,然後從那裏調用另一個CLI,可以是SSH,telnet等。

回答

1

我建議發送將PS1更改爲已知字符串的命令。當我使用Korn Shell腳本中的Oracle sqlplus作爲協處理時,我已經這麼做了,知道何時結束從我發佈的最後一條語句讀取數據/輸出。所以基本上,你會送:

PS1='end1>'; command1 

然後,你看行,直到看到「END1>」(額外容易,在PS1的末尾添加一個新行)。

相關問題