1

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.

Martin Prikryl
  • 167,268
  • 50
  • 405
  • 846
blueDroid
  • 231
  • 1
  • 3
  • 10
  • if you put `sql_query.script > result.txt` in a cronjob on that remote machine, does it work as expected? – Daniel F May 28 '19 at 20:42
  • It runs fine as well as if I paste it on the terminal. The problem is when using paramiko. It creates the file before the sql completes. – blueDroid May 28 '19 at 20:45
  • if you put `/bin/bash -c 'sql_query.script > result.txt 2>&1'` in the script above? That would ensure that you have a bash shell and would pipe everything into `result.txt` including the error messages, in case `sql_query.script` fails with errors. – Daniel F May 28 '19 at 20:46
  • Was it of any use? – Daniel F May 28 '19 at 21:29
  • Where/how do you get "Error 108"? – Martin Prikryl May 29 '19 at 06:38

1 Answers1

0

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:

Martin Prikryl
  • 167,268
  • 50
  • 405
  • 846