0

Having a list from a MySQL query, from my remote machine using a python script, I would like to put the results of the query into a txt file.

I am trying with this:

import subprocess
import sys
from subprocess import check_output
command = 'sshpass -p pass ssh user@ipaddress "echo \'' + str(list) + '\' > file.txt; ls"'
output = check_output(command, shell=True)
print (output)

But it returns an error.

Is there an easier way to do that?

The error:

  File "ipcompare.py", line 53, in <module>
    output3 = check_output(command, shell=True)
  File "/usr/lib/python2.7/subprocess.py", line 223, in check_output
    raise CalledProcessError(retcode, cmd, output=output)

An example of the list:

'['11.111.1.111/29-Name=0', '12.122.2.222/29-Name=0']
aldegalan
  • 480
  • 2
  • 12
  • What is the error? Can you share with us the list? And How is that related to `bash`? – vmemmap Aug 17 '20 at 12:16
  • @r0ei the error is: File "ipcompare.py", line 53, in output3 = check_output(command, shell=True) File "/usr/lib/python2.7/subprocess.py", line 223, in check_output raise CalledProcessError(retcode, cmd, output=output) – aldegalan Aug 17 '20 at 12:18
  • @jmgalan : CalledProcessError means that the remote program terminated with a non-zero exit code. Are you sure that `str(list)` does not contain any character which might upset the shell? The whole approach to this problem looks odd to me. Why can't you use `scp` or `rsync` if you can use `ssh`? – user1934428 Aug 17 '20 at 13:48
  • @jmgalan : Maybe it makes sense to do [eveything in Python](https://stackoverflow.com/questions/250283/how-to-scp-in-python), and refrain from using bash for this task. – user1934428 Aug 17 '20 at 13:50
  • @r0ei : I think it is related to bash, because the OP dynamically generates shell code, which is buggy and leads to an error. Actually, from the code posted, we can not even say for sure whether it is really bash which is actually used as a shell. – user1934428 Aug 17 '20 at 13:57

1 Answers1

0

Done with this:

import subprocess
from subprocess import check_output
command = 'mysql -u ' + args.user + ' -p' + args.pwd + ' -h ' + args.ipdb + ' -P 8036 myDTS -e "select example from example2;" 2>/dev/null'
output2 = check_output(command, shell=True)

This could be done from a remote machine, just by using sshpass command

aldegalan
  • 480
  • 2
  • 12