【问题标题】:Python ssh paramiko to detect failed commandPython ssh paramiko 检测失败的命令
【发布时间】:2017-10-04 15:54:50
【问题描述】:

我正在使用 paramiko 建立 ssh 会话并向服务器发送命令。

很少有命令没有成功执行。我如何检测这些命令无法执行并终止 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,所以我必须在这里使用 shell 调用。

请帮助如何检测不成功的运行命令并终止python程序。

【问题讨论】:

  • paramiko 无法告诉您命令是否失败。你必须自己解析输出。
  • 谢谢我会这样做

标签: python linux shell ssh paramiko


【解决方案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...

【讨论】:

  • 远程服务器不是基于 unix/linux 的服务器,这样可以吗?
  • @asteroid4u:是的,这是一个 bash 脚本。
  • OP 的远程登录 shell 看起来不像 bash。
  • 是的,远程服务器不 bash shell 它的那种开关