4

I want to execute following commands in sequence using a python script:

sudo su - postgres   #login as postgres user
psql

I tried using :

import os

cmd = 'sudo su - postgres'
os.system(cmd)

cmd1='psql'
os.system(cmd1)

The problem with this is that the 2nd command gets executed only after I log out from the postgres user, but I want to run it as postgres user. How can I can I continue the execution of python script after the user change?

Thanks

4
  • what's the goal ? managing a new schema or database from the "dba user" named postgres ? Commented Sep 13, 2013 at 13:27
  • @FoxMaSk: Creating a postgres database from dumpfile Commented Sep 13, 2013 at 13:34
  • sudo -u postgres psql dbname < dump does not do the trick ? Commented Sep 13, 2013 at 13:38
  • @FoxMaSk I'm using "cat dump | zcat - | PGPASSWORD=password psql -d voylla_development -h localhost -p 5432 -U user_name" As I need localhost and port to be able to index solr by giving the url of the database. For this I need to enter the psql prompt Commented Sep 13, 2013 at 13:46

1 Answer 1

1

You can use:

sudo su - postgres --command='cat … | psql …'

But you shouldn't. You should configure your database server to allow a user running your python script access to your database without password. Or at least use .pg_pass file in this user home directory to provide username and password for this database.

If you use PGPASSWORD, as you indicated in a comment, then any other user in your system can display it simply using ps auxwww.

Sign up to request clarification or add additional context in comments.

1 Comment

Interesting. This would work. But is there a way to continue the execution of the script, to handle the cases where I need to execute multiple commands as a different user?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.