Python script does not recognize Mysql query

Viewed 96

I am trying to receive the results of a query by using sshpass, an example below:

sshpass -p password ssh user@ip "mysql -u user -pdbpassword -h ip -P port database -e \"SELECT * FROM database.ViewName;\""

When I launch that command from my local machine, it works.

But when I do on my Python script, it doesnt:

import subprocess
import sys
from subprocess import check_output


command = 'sshpass -p password ssh user@ip "mysql -u user -pdbpassword -h ip -P port database -e \"SELECT * FROM database.ViewName;\""'
output = check_output(command, shell=True)

And it returns this error:

bash: -c: línea 0: EOF inesperado mientras se buscaba un `"' coincidente
bash: -c: línea 1: error sintáctico: no se esperaba el final del fichero
/bin/sh: 1: : Permission denied
Traceback (most recent call last):
  File "ipcompare.py", line 8, in <module>
    output2 = check_output(command2, shell=True)
  File "/usr/lib/python2.7/subprocess.py", line 223, in check_output
    raise CalledProcessError(retcode, cmd, output=output)
subprocess.CalledProcessError: Command 'sshpass -p password ssh user@ip "mysql -u user -pdbpassword -h ip -P port database -e \"SELECT * FROM database.ViewName;\""' returned non-zero exit status 127

I have tried:

  • chmod 777 to my script, the error is still the same.
  • Changing doble quotes for single quotes.
  • Escaping all special characters.
2 Answers

Basing on this line:

/bin/sh: 1: : Permission denied

It appears that you don't have privileges to execute that shell command. You sure that when running it locally, you are not having some elevated privileges (run some command with 'sudo' previously etc.)?

It'd isolate it a bit on your place, eg. start with something simple:

command = 'sshpass -p password ssh user@ip "pwd"'

If it works, you could further try to delegate mysql query.

Also, you are running the command and script on same machine? Sometimes databases have limited set of IP addresses which can access it. Check if that's not the case for your db.

I did this to solve the problem:

import subprocess
import sys
from subprocess import check_output


command = 'sshpass -p password ssh user@ip "mysql -u user -pdbpassword -h ip -P port database -e \\\"SELECT * FROM database.ViewName;\\\""'
output = check_output(command, shell=True)

Escaping the escape character was the answer for this issue.

Related