To capture the output of a SSH command execution session in a txt file I did this:
sys.stdout = open('Output_Log.txt','w')
Now, once the SSH session is closed, I want to stop writing to the file and let the other print statements come to the console.
But that is not happening. The subsequent prints are overwriting my above log file and I am loosing my SSH command execution data.
Here is the complete code:
session.exec_command('cd /project/neptune/neptune_psv/fw; ./Do_Regr.sh -i Testlist_Regression.in -m 135.24.237.198 -g')
stdout_data = []
stderr_data = []
sys.stdout = open('Output_Log.txt','w')
sys.stderr = open('Error_Log.txt','w')
while True:
try:
if session.recv_ready():
stdout_data.append(session.recv(16384))
if session.recv_stderr_ready():
stderr_data.append(session.recv_stderr(16384))
if session.exit_status_ready():
break
except socket.timeout:
print("SSH channel timeout exceeded.")
break
except Exception:
traceback.print_exc()
break
print 'exit status: ', session.recv_exit_status()
print ''.join(stdout_data)
print ''.join(stderr_data)
session.close()
trans.close()
print "############Regression Complete############"
When I open Output_Log.txt I only find the last print. Whereas, if I comment the last print statement (Regression Complete) then the Output_Log nicely captures the stdout_data of the session.