gpt4 book ai didi

Python ssh paramiko 检测失败的命令

转载 作者:太空宇宙 更新时间:2023-11-04 04:33:18 25 4
gpt4 key购买 nike

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

少数命令未成功执行。我如何检测这些命令未能执行并终止 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 程序。

最佳答案

一种方法是:

  • 在本地创建一个可以处理错误的小型 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...

关于Python ssh paramiko 检测失败的命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43817271/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com