Postgresql: Scripting psql execution with password

后端 未结 16 2456
谎友^
谎友^ 2020-11-28 18:54

How can I call psql so that it doesn\'t prompt for a password?

This is what I have:

psql -Umyuser < myscript.sql         


        
16条回答
  •  孤城傲影
    2020-11-28 19:02

    Given the security concerns about using the PGPASSWORD environment variable, I think the best overall solution is as follows:

    1. Write your own temporary pgpass file with the password you want to use.
    2. Use the PGPASSFILE environment variable to tell psql to use that file.
    3. Remove the temporary pgpass file

    There are a couple points of note here. Step 1 is there to avoid mucking with the user's ~/.pgpass file that might exist. You also must make sure that the file has permissions 0600 or less.

    Some have suggested leveraging bash to shortcut this as follows:

    PGPASSFILE=<(echo myserver:5432:mydb:jdoe:password) psql -h myserver -U jdoe -p 5432 mydb
    

    This uses the <() syntax to avoid needing to write the data to an actual file. But it doesn't work because psql checks what file is being used and will throw an error like this:

    WARNING: password file "/dev/fd/63" is not a plain file
    

提交回复
热议问题