0

I am using paramiko to establish ssh session and send commands to the server.

Few of the commands are not successfully executed. How do i detect those commands are failed to execute and terminate python code. Below is the code what I am trying :

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()

Details output:

  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. 

Note: This is not a shell so I have to use shell invoke here.

Please help how to detect not successful ran command and terminate the python program.

2
  • paramiko cannot tell you if the command failed or not. you have to parse the output all by yourself. Commented May 6, 2017 at 12:23
  • Thanks i will do same way Commented May 7, 2017 at 3:07

1 Answer 1

-1

One way to do that is:

  • create a small bash script locally which can handle errors,
  • copy the script in the remote server using scp,
  • run the script and catch it's output,
  • parse the output to see if an error occurs.

Here is an example of bash script:

#!/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...
Sign up to request clarification or add additional context in comments.

4 Comments

remote server is not unix/linux based server this will work?
@asteroid4u: Yes, this is a bash script.
the OP's remote login shell does not look like bash.
yes remote server does not bash shell its kind of of switch

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.