How to continue the execution of python script as a different user - python

I want to execute a python script which executes the following command in order:
sudo su - postgres #change user to postgres
psql #enter the psql command promt from
create user user_name with password 'mypassword'; #
create database voylla_development with encoding = 'utf8'; #all the 3 commands are to be executed in psql command prompt
grant all on database voylla_development to user_name; #
exit #psql prompt
exit #postgres user
cat <backup_file_name> | zcat - | PGPASSWORD=mypassword psql -d voylla_development -h localhost -p 5432 -U user_name
I tried using subprocess and os.system():
cmd='sudo -u postgres psql'
args = shlex.split(cmd)
p=subprocess.Popen(args)
p.wait()
cmd1='psql'
args1 = shlex.split(cmd1)
p=subprocess.Popen(args1)
p.wait()
##and so on for each command
But the script stops after I login as postgres user. How can I continue the script after user change?
Thanks
EDIT: using psycopg2 helped the cause

When you create a new Popen() object, you start a new program. You are not communicating with an open psql shell.
You either have to drive psql directly by setting stdin to subprocess.PIPE, or, much easier, use pexpect to drive the psql shell:
import pexpect
psql = pexpect.spawn('psql')
psql.expect('=>') # wait for the prompt
psql.send('create user user_name with password 'mypassword';')
# etc.

Related

How to run multiple Putty commands from Notepad

I have created Python TkInter to open a Putty session as below
# If the server name is not empty, open an SSH connection using PuTTY
if server_name:
#set the putty path
putty_path = 'C:\\Program Files\\PuTTY\\putty.exe'
check_db_type = db_type.get().lower()
check_db_type_action = get_action().lower()
abs_path = resource_path(f"sudo\\{check_db_type}\\{check_db_type}_sudo.txt")
# THIS IS WHAT STARTS THE SSH PUTTY SESSION
server_command = f'{putty_path} -ssh {username}#{server_name} -pw {password} -m "{abs_path}" -t'
subprocess.Popen(server_command)
# close the subprocess if it is already running and open a new subprocess
# with contextlib.suppress(Exception):
# subprocess.Popen.terminate()
# subprocess.Popen(server_command)
else:
window.destroy()
I am passing the notepad filepath in the server_command. The file contains these commands.
sudo su - postgres works well but other commands are not working
sudo su - postgres || df -kh
I have tried 3 variants of command separation as below but nothing works
sudo su - postgres; df -kh
sudo su - postgres && df -kh
sudo su - postgres
df -kh
Is there any other way to run multiple commands like these apart from using a text file? Thank you so much
I have tried to separate the 2 commands in the notepad in 3 different ways but only the first command <sudo su - postgres> is working. The next command <df -kh>, shows filesystem space, is not working as expected
I am using Windows on my laptop but access database servers through Putty remotely
++Update
When my team login as ADM (ADM account for users) and then sudo su - username, it opens a different subshell than the previous one. Can check by echo $$.
To put it simply, ADM is parent shell and sudo su - username will open child shell. After sudo su - postgres, all my following commands <uptime; df -kh, etc> running in parent shell in the background. Until I exit sudo su - postgres <CTRL + D> I cannot see the output.

"stdin is not a tty" when populating Postgres database

Please help, I have this stdin is not a tty message when i run the command below in my terminal.
psql -U postgres kdc < kdc.psql
kdc is the database and kdc.psql is the psql file with commands to populate the database. I am in the directory that holds the psql file.
I am not sure what causes that message (it does not happen here), but you should be able to avoid it using the -f option:
psql -U postgres -d kdc -f kdc.psql

Executing password-protected psql from python

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).

Python script to login to a remote server and access Cassandra database

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

unix command execution with password via python

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...

Categories