1

I wanted to wait the given command execution has been completed on remote machines. this case it just executed and return and not waiting till its completed.

import paramiko
import re
import time


def scp_switch(host, username, PasswdValue):
    ssh = paramiko.SSHClient()

    try:
        # Logging into remote host as my credentials 
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(host, username=username, password=PasswdValue ,timeout=30)

        try:
            # switcing to powerbroker/root mode 
            command = "pbrun xyz -u root\n"

            channel = ssh.invoke_shell()
            channel.send(command)
            time.sleep(3)


            while not re.search('Password',str(channel.recv(9999), 'utf-8')):
                time.sleep(1)
                print('Waiting...')

            channel.send("%s\n" % PasswdValue)
            time.sleep(3)

            #Executing the command on remote host with root (post logged as root)
            # I dont have any specific keyword to search in given output hence I am not using while loop here.

            cmd = "/tmp/slp.sh cool >/tmp/slp_log.txt \n"
            print('Executing %s' %cmd)
            channel.send(cmd) # its not waiting here till the process completed,
            time.sleep(3)
            res = str(channel.recv(1024), 'utf-8')
            print(res)

            print('process completed')
        except Exception as e:
            print('Error while switching:', str(e))

    except Exception as e:
        print('Error while SSH : %s' % (str(e)))

    ssh.close()

""" Provide the host and credentials here  """
HOST = 'abcd.us.domain.com'
username = 'heyboy'
password = 'passcode'

scp_switch(HOST, username, password)

As per my research, it will not return any status code, is there any logic to get the return code and wait till the process completed?

Srinivas Gadi
  • 117
  • 1
  • 8
  • Unless you have a very good reason to use `invoke_shell`, use `exec_command` instead, and your life will be way more easier. – Martin Prikryl May 21 '20 at 11:00
  • Here is my requirement **1)** I need to loginto remote host with my credentials --> used paramiko **2)** I need to switch root/power broker and execute the commands --> this is the reason I had to use `invoke_shell`, if I use `exec_command` it will execute the commands with my `ID` rather `root`. – Srinivas Gadi May 21 '20 at 15:00
  • It's possible that you have used `exec_command` incorrectly. See [Executing command using “su -l” in SSH using Python](https://stackoverflow.com/q/51493317/850848) – Martin Prikryl May 21 '20 at 16:37
  • Does this answer your question? [Execute multiple dependent commands individually with Paramiko and find out when each command finishes](https://stackoverflow.com/questions/50962485/execute-multiple-dependent-commands-individually-with-paramiko-and-find-out-when) – Martin Prikryl May 26 '20 at 06:45

0 Answers0