2017-05-06 189 views
0

我使用paramiko建立ssh會話併發送命令到服務器。Python ssh paramiko檢測失敗的命令

很少的命令沒有成功執行。我如何檢測那些命令無法執行並終止python代碼。 下面是我想做的代碼:

remote_conn_pre = paramiko.SSHClient() 
remote_conn_pre.set_missing_host_key_policy(
    paramiko.AutoAddPolicy()) 
remote_conn_pre.connect(host, username=username, password=password, look_for_keys=False, allow_agent=False) 
print "SSH connection established to %s" % host 
# Use invoke_shell to establish an 'interactive session' 
remote_conn = remote_conn_pre.invoke_shell() 
remote_conn.send("\n") 
remote_conn.send("scope org engg\n") 
remote_conn.send("\n") 
remote_conn.send("show service-profile") 
if remote_conn.recv_ready(): 
    details = remote_conn.recv(5000) 
remote_conn.close() 

詳細輸出:

servera# scope org engg 
    Error: Managed object does not exist # org engg is not exist that the reason we are getting this error 
    servera# 
    servera# show service-profile 

    % Incomplete Command at '^' marker # since the above command is failed but paramiko does not able to identify it is moving to second command execution . There is no org engg so that the reason i am getting incomplete command warning. 

注:這是不是一個殼,所以我必須使用shell調用這裏。

請幫助如何檢測不成功的ran命令並終止python程序。要做到這一點

+0

的paramiko不能告訴你,如果命令失敗與否。你必須自己解析輸出。 – pynexj

+0

謝謝我會做同樣的方式 – asteroid4u

回答

-1

一種方法是:

  • 本地可以處理錯誤創建一個小的bash腳本,
  • 複製腳本中使用scp遠程服務器,
  • 運行腳本,並抓住它的輸出,
  • 解析輸出以查看是否發生錯誤。

這裏是bash腳本的例子:

#!/bin/bash 

function error() { 
    local parent_line_no="$1" 
    local message="$2" 
    local code="${3:-1}" 
    if [[ -n "$message" ]] ; then 
     echo "Error on or near line ${parent_line_no}: ${message}; exiting with status ${code}" 
    else 
     echo "Error on or near line ${parent_line_no}; exiting with status ${code}" 
    fi 
    exit "${code}" 
} 
trap 'error ${LINENO}' ERR 

# your commands here... 
+0

遠程服務器是不是基於Unix/Linux的服務器,這將工作? – asteroid4u

+0

@ asteroid4u:是的,這是一個** bash **腳本。 –

+0

OP的遠程登錄shell看起來不像bash。 – pynexj