I use psql copy command to convert PostgreSQL result to CVS file on remote server. I use the below code in python. But it is creating an empty file in the directory.
secretData=json.loads(get_secret(row[31]))
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=secretData['linux-host'], username=secretData['linux-username'],
password=secretData['linux-password'], port=secretData['linux-port'])
channel = ssh.get_transport().open_session()
query = 'select * from ' + row[20] + ' where ' + row[25] + ' > ' + row[21] + ' and ' + row[25] + '<=' + str(maxID) + ''
SQL_for_file_output='export PGPASSWORD='+secretData['postgresPassword']+';psql -h "'+secretData['postgreshost']+'" -U "'+secretData['postgresUserName']+'" -c "\copy ('+query+' ) to STDOUT csv header" DB > '+row[17]+row[2]
channel.exec_command(SQL_for_file_output)
exit_code = channel.recv_exit_status()
if exit_code == 0:
print('File Moved Successfully')
else:
stdout = channel.makefile().read()
stderr = channel.makefile_stderr().read()
print(stdout)
print(stderr)
print("Error", exit_code)
channel.close()
ssh.close()
What am missing?
Can anyone please suggest me the solution?