The output file is created before the database results are available.
Passing a simple os command works fine:
# command = "whoami > result.txt"
works fine. I would get my user name when I open the result.txt file. The problem is waiting for the database to return the result. It comes out empty even though there is data returned from the actual query
import paramiko
def get_report(command):
# reference: https://stackoverflow.com/questions/5193886/python-paramiko-issue-while-closing-the-connection.
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('server123', username='username', password='password')
stdin, stdout, stderr = client.exec_command(command)
exit_status = stdout.channel.recv_exit_status()
if exit_status == 0:
print("File processed")
else:
print("Error", exit_status)
client.close()
command = "sql_query.script > result.txt"
get_report(command=command)
I expect to received a data set of first_name, last_name, and location but instead I get Error 108.
If a command does not work, when executed using Paramiko, debug it by reading its error output.
Use stderr.readlines()
for that.
If the same command works in regular shell, but not in Paramiko, the problem is usually related to a different environment used by the SSH "exec" channel, which is used by SSHClient.exec_command
. See: