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()
Jinto Antony
  • 458
  • 8
  • 26
  • You probably need to use Pexpect here: https://pexpect.readthedocs.io/en/stable/. Popen is just dumping the password into stdin right away without waiting for the prompt to appear. – shadowtalker May 19 '20 at 14:24
  • @shadowtalker Ok...that's why I put a sleep(10 in there). – Jinto Antony May 19 '20 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. – pts May 19 '20 at 14:29

1 Answers1

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?

pts
  • 80,836
  • 20
  • 110
  • 183