此问题在此处已有答案:
Execute multiple dependent commands individually with Paramiko and find out when each command finishes(1个答案)
Executing command using "su -l" in SSH using Python(1个答案)
14小时前关门了。
我想等待给定的命令在远程计算机上执行完成。在这种情况下,它只是执行并返回,而不是等待它完成。
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)
根据我的研究,它不会返回任何状态代码,是否有任何逻辑来获得返回代码并等待直到过程完成?
1条答案
按热度按时间u2nhd7ah1#
我知道这是一个老帖子,但是把它留在这里以防有人遇到同样的问题。你可以使用一个echo,它将在你的命令成功执行的情况下运行,例如,如果你正在执行scp ... && echo 'transfer complete',那么你可以用一个循环捕获这个输出