in ccmlib/remote.py [0:0]
def execute(self, command, is_displayed=True, profile=None):
"""
Execute a command on the remote server
:param command: Command to execute remotely
:param is_displayed: True if information should be display; false to return output
(default: true)
:param profile: Profile to source (unix like system only should set this)
(default: None)
:return: A tuple defining the execution of the command
* output - The output of the execution if the output was not displayed
* exit_status - The exit status of remotely executed script
"""
# Modify the command for remote execution
command = " ".join("'{0}'".format(argument) for argument in command)
# Execute the command and initialize for reading (close stdin/writes)
if not profile is None and not profile is "None":
command = "source " + profile + ";" + command
stdin, stdout, stderr = self.ssh.exec_command(command)
stdin.channel.shutdown_write()
stdin.close()
# Print or gather output as is occurs
output = None
if not is_displayed:
output = []
output.append(stdout.channel.recv(len(stdout.channel.in_buffer)).decode("utf-8"))
output.append(stderr.channel.recv(len(stderr.channel.in_buffer)).decode("utf-8"))
channel = stdout.channel
while not channel.closed or channel.recv_ready() or channel.recv_stderr_ready():
# Ensure the channel was not closed prematurely and all data has been ready
is_data_present = False
handles = select.select([channel], [], [])
for read in handles[0]:
# Read stdout and/or stderr if data is present
buffer = None
if read.recv_ready():
buffer = channel.recv(len(read.in_buffer)).decode("utf-8")
if is_displayed:
sys.stdout.write(buffer)
if read.recv_stderr_ready():
buffer = stderr.channel.recv_stderr(len(read.in_stderr_buffer)).decode("utf-8")
if is_displayed:
sys.stderr.write(buffer)
# Determine if the output should be updated and displayed
if buffer is not None:
is_data_present = True
if not is_displayed:
output.append(buffer)
# Ensure all the data has been read and exit loop if completed
if (not is_data_present and channel.exit_status_ready()
and not stderr.channel.recv_stderr_ready()
and not channel.recv_ready()):
# Stop reading and close the channel to stop processing
channel.shutdown_read()
channel.close()
break
# Close file handles for stdout and stderr
stdout.close()
stderr.close()
# Process the output (if available)
if output is not None:
output = "".join(output)
# Return the output from the executed command
return output, channel.recv_exit_status()