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.
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
I need to execute the following command from Python on Windows:
psql -h localhost -p 5432 -U postgres -f script.sql db_name
The above script works fine when ran from git bash / powershell. After entering the script in a terminal, I need to provide a password to confirm it (similar to when using sudo).
How can I do that? I keep finding solutions that I think are linux-based.
How do I do it on Windows? I have tried many variations of solutions involving subprocess, i.e:
import subprocess
p2 = subprocess.Popen(
'psql -h localhost -p 5432 -U postgres -f script.sql db_name',
stdin=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True)
print('this will print')
sudo_prompt = p2.communicate('THE_PASSWORD' + '\n')[1]
print('this will not')
A better option (more secure) than invoking psql with explicit mention of your password is to have a .pgpass file as described in the docs file (and keep it protected e.g. chmod 600 ~/.pgpass). This keeps your password out of the list of running processes.
On Windows:
On Microsoft Windows the file is named %APPDATA%\postgresql\pgpass.conf (where %APPDATA% refers to the Application Data subdirectory in the user's profile).
I am using Paramiko to do the standard SSH into a box, run commands, and display the STDOUT to my terminal. Due to sudo rules, I SSH into a machine with my username and run sudo /bin/su -s /bin/bash - <diff user account>. In my script, I am passing the following command into Paramiko but the STDOUT does not show on my screen. I believe this is because the sudo command is opening a new shell and Paramiko is watching the STDOUT on the new shell.
The commands DO run as I have logged onto the box and see the command history. How do I get the STDOUT of the commands I am running to show on my terminal?
import paramiko
def sshCommand(hostname, port, username, command, key_filename='/home/<my username>/.ssh/id_rsa'):
sshClient = paramiko.SSHClient()
sshClient.set_missing_host_key_policy(paramiko.AutoAddPolicy())
sshClient.connect(hostname=hostname, port=port, username=username, key_filename=key_filename)
stdin, stdout, stderr = sshClient.exec_command(command, get_pty=False)
output = stdout.readlines()
print(output)
sshCommand('<servername>', 22, '<my username>', """sudo /bin/su -s /bin/bash - <diff username> << \'EOF\'
echo "Hello World"
EOF
""")
I do not think that OpenSSH SSH server can accept the << 'EOF' shell construct on the "exec" channel.
But this should work:
echo echo "Hello World" | sudo /bin/su -s /bin/bash - <diff username>
I have to write a python script that logs on using ssh to a remote server and access the Cassandra database there . I am using paramiko but after login in to the server , it doesn't connect to Cassandra and script hangs .
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('10.65.XXX.XX', username='sinha.aman', password='', key_filename='/root/.ssh/id_rsa.pub')
stdin, stdout, stderr = ssh.exec_command('cqlsh 10.65.XXX.XX 9042 -u ABC123 -p 12345')
stdin, stdout, stderr = ssh.exec_command('ls')
print(stdout.readlines())
ssh.close()
Maybe the script waits from some user input since you're opening a cqlsh session?
Try adding the -e flag to cqlsh command:
cqlsh -e 'select * from test.emp'
Change accordingly to your script.
Check also cqlsh --help for -e flag.
-e EXECUTE, --execute=EXECUTE
Execute the statement and quit.
stdin, stdout, stderr = ssh.exec_command('cqlsh 10.65.XXX.XX 9042 -u ABC123 -p 12345')
Here it is opening a cqlsh prompt, which is expecting a command to be executed, not returning any output.
Script is waiting for an input command. We have to pass cqlsh command to get the output.
By adding "-e help" or any other command will solve the issue.
stdin, stdout, stderr = ssh.exec_command('cqlsh 10.65.XXX.XX 9042 -u ABC123 -p 12345 **-e help** ')
For better understanding, execute the command manually in remote server, where you will see a cqlsh prompt waiting for command.
For all the cqlsh commands please refer
https://docs.datastax.com/en/cql-oss/3.x/cql/cql_reference/cqlshCommandsTOC.html
I am trying to execute few scripts in remote linux machine from windows host machine. I am hoping to achieve this using python subprocess +putty/plink.
When I try Putty or plink commands from windows cmd, it works fine. But if I try the same command using python subprocess, I get a lot of errors.
C:\Users\username>plink.exe username#machinename -pw password
Works fine. But when I try from python,
process = subprocess.Popen('plink.exe username#machinename -pw password'.split(),
env={'PATH':'C:\\Program Files (x86)\\PuTTY\\'},
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
Throws the following error.
Unable to open connection:
gethostbyname: unknown error'
process = subprocess.Popen("putty.exe -ssh -2 -l username -pw password -m C:\\script.sh machinename",
env={'PATH':'C:\\Program Files (x86)\\PuTTY\\'},
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT
,shell=True);
Unable to open connection:
gethostbyname: unknown error'
I tried subprocess.check_ouput too with no luck.
output = subprocess.check_output("putty.exe -ssh -2 -l username -pw password -m C:\\script.sh machinename", stderr=subprocess.STDOUT,shell=True)
Throws the following error
CalledProcessError: Command 'putty.exe -ssh -2 -l username -pw
password -m C:\script.sh machinename' returned non-zero exit status 1
Could this be a firewall issue?
I highly advise against using PuTT or in general every external program to connect to shh and then interface with pipes.
Using the python library paramiko this can be done much better.
For example:
# ... connect like one of the examples on github
stdin, stdout, stderr = client.exec_command('ls')
for line in stdout:
print '... ' + line.strip('\n')
I am trying to connect to mysql in unix from a python script. I provided the password to connect to mysql in the script itself but terminal still prompts for the password. This is what i have till now:
import os
from subprocess import Popen, PIPE
passwd = "user"
command = "mysql -u root -p"
proc = Popen(command.split(), stdin=PIPE)
proc.communicate(passwd+'\n')[1]
Can any one suggest what am i doing wrong here. Or is there a better way to do this.
You can try this:
command = "mysql -u root -p" + passwd
I tried your script in Ubuntu 14.04. It is very easy to start a MySQL in terminal using shell script.
Here is the code..
#!/bin/bash
user=('root')
pass=('XXX')
mysql -u $user -p$pass
echo 'success'
Simply run this code & you can start the MySQL at terminal...