[Solved]-How to test postgresql credentials from bash?

25πŸ‘

βœ…

It’s bash, not python, so not sure if it fits you needs:

vao@vao-X102BA:~$ psql -d "postgresql://p:goodpassword@localhost/t" -c "select now()"
              now
-------------------------------
 2017-07-14 11:42:40.712981+03
(1 row)

vao@vao-X102BA:~$ echo $?
0
vao@vao-X102BA:~$ psql -d "postgresql://p:badpassword@localhost/t" -c "select now()"
psql: FATAL:  password authentication failed for user "p"
FATAL:  password authentication failed for user "p"
vao@vao-X102BA:~$ echo $?
2

If you want to suppres output, instead of select now(), you can just quit with -c "\q"

πŸ‘€Vao Tsun

4πŸ‘

Do you not have psql on your machine? It’d be more simple to use a command app than python to do what you want.

if PGHOST=127.0.0.1 PGPORT=5432 PGUSER=$POSTGRESQL_USER PGPASSWORD=$POSTGRESQL_PWD \
        PGDATABASE=myappdb psql -c \q 2>/dev/null
then
    echo "[OK]"
else
    echo "[FAIL]"
fi

PGHOST=127.0.0.1 ... is temporarily exporting variables to psql.
The \q just tells the client to quit immediately if the connection was successful.

πŸ‘€Dunes

0πŸ‘

It turns out that the pg_hba.conf file that was in use was:

local   all             all                                     trust
# IPv4 local connections:
host    all             all             127.0.0.1/32            trust
# IPv6 local connections:
host    all             all             ::1/128                 trust

I changed it to:

local   all             all                                     md5
# IPv4 local connections:
host    all             all             127.0.0.1/32            md5
# IPv6 local connections:
host    all             all             ::1/128                 md5

and both answers above work.

Leave a comment