Below is the code I used, I want to use pexpect to get the entire output of a commmand running in a ssh section:
I have tried many ways to get the output of the command, but it always return the string before the marker, i can't get the string after the marker, I need to get the entire output of the command. please help me with above function run_command_and_return_status_and_output
import pexpect
import sys
def ssh_login(ssh_host, ssh_username, ssh_password, timeout=10):
ssh_command = f"ssh {ssh_username}@{ssh_host}"
child = pexpect.spawn(ssh_command, timeout=timeout)
try:
# Expect the SSH password prompt
index = child.expect([pexpect.TIMEOUT, 'password:', pexpect.EOF], timeout=timeout)
if index == 0:
raise Exception("SSH connection timeout")
if index == 1:
# Send the SSH password
child.sendline(ssh_password)
# Expect the shell prompt after successful login
index = child.expect(['7503', pexpect.EOF], timeout=timeout)
if index == 0:
return child # Successfully logged in
raise Exception("Authentication failed")
except Exception as e:
child.close()
raise e
def run_command_and_return_status_and_output(child, command, success_marker, failure_marker, timeout=10):
status = "Pass" # Initialize status as Pass, assuming the command will pass
output = ""
try:
# Send the command
child.sendline(command)
# Expect the output
index = child.expect([success_marker, failure_marker, pexpect.EOF, pexpect.TIMEOUT], timeout=timeout)
if index == 0:
status = "Pass"
if index == 1:
status = "Fail"
if index not in [0, 1]:
status = "Exception"
output = child.before.decode('utf-8')+child.after.decode('utf-8')
if output:
# Remove the command from the output
output = output.replace(command, "")
except Exception as e:
status = "Exception"
output = str(e)
finally:
return status, output
def run_command_and_return_status_and_output(child, command, success_marker, failure_marker, timeout=10):
status = "Pass" # Initialize status as Pass, assuming the command will pass
output = ""
try:
# Send the command
child.sendline(command)
# Expect the output
index = child.expect([success_marker, failure_marker, pexpect.EOF, pexpect.TIMEOUT], timeout=timeout)
if index == 0:
status = "Pass"
elif index == 1:
status = "Fail"
# Get the entire output, including before and after
output = child.before.decode('utf-8') + child.after.decode('utf-8')
except Exception as e:
status = "Exception"
output = str(e)
finally:
return status, output
# Example usage
ssh_host = "your host"
ssh_username = "your username"
ssh_password = "your password"
child = ssh_login(ssh_host, ssh_username, ssh_password)
command = "ifconfig -a"
success_marker = "lo"
failure_marker = "xxx"
timeout = 10
status, output = run_command_and_return_status_and_output(child, command, success_marker, failure_marker, timeout)
print("Status:", status)
print("Output:", output)
# Close the SSH connection
child.close()