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
  • 2
  • 9

1 Answers1

0

I know this is an old post, but leaving this here in case someone has the same problem. You can use an echo that will run in case your command executes successfully, for example if you are doing an scp ... && echo 'transfer complete', then you can catch this output with a loop

        while True:
            s = chan.recv(4096)
            s = s.decode()
            if 'transfer done' in s:
               break
            time.sleep(1)
SmokeS
  • 1
  • 1