首页 > 解决方案 > 等到命令在 paramiko invoke_shell() 中完成

问题描述

我想等待给定的命令执行已在远程机器上完成。这种情况下它只是执行并返回,而不是等到它完成。

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)

根据我的研究,它不会返回任何状态码,是否有任何逻辑来获取返回码并等待进程完成?

标签: python-3.xparamiko

解决方案


推荐阅读