1

I am trying to create an automatic pg dump backup script for PostgreSQL DB. The script ask for a DB password. I am trying to put the password using stdin. But, it's not working. 'popen.stdin.write("rootpasswordhere123#!\n")', this line not inserting the password into the script terminal.

import gzip
import subprocess

with gzip.open('backup.gz', 'wb') as f:
    popen = subprocess.Popen(['pg_dump', '--no-owner', '--no-acl', '-U', 'postgres', '-d', 'database_name', '-h', '178.111.11.111'], stdout=subprocess.PIPE, stdin=subprocess.PIPE, universal_newlines=True)
    time.sleep(5)
    popen.stdin.write("rootVidhyaDhan123#!\n") # code not working
    for stdout_line in iter(popen.stdout.readline, ""):
        f.write(stdout_line.encode('utf-8'))
    popen.stdin.close()
    popen.stdout.close()
    popen.wait()
3
  • You probably need to use Pexpect here: pexpect.readthedocs.io/en/stable. Popen is just dumping the password into stdin right away without waiting for the prompt to appear. Commented May 19, 2020 at 14:24
  • @shadowtalker Ok...that's why I put a sleep(10 in there). Commented May 19, 2020 at 14:26
  • 1
    Maybe pg_dump is trying to read the password from /dev/tty rather than stdn. You may want to specify a command-line flag to pg_dump to change this behavior. Commented May 19, 2020 at 14:29

1 Answer 1

1

Probably pg_dump is trying to read the password from /dev/tty rather than stdin.

Instead of using stdin, set the PGPASSWORD environment variable (os.environ['PGPASSWORD'] = '...') or create a .pgpass file. Details here: How to pass in password to pg_dump?

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

2 Comments

@JintoAntony: Not with pg_dump, but with other Unix command-line tools.
Even better, use the env= parameter of Popen, as demonstrated here: stackoverflow.com/a/4453495/2954547

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.