How to list databases owned by rolename in postgresql

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-11 16:16:36

问题


The code i tried in bash executed by root.

#!/bin/bash
su - postgres <<EOF1 
F="$(psql -d postgres --tuples-only -P format=unaligned -c "SELECT datname FROM pg_database JOIN pg_authid ON pg_database.datdba = pg_authid.oid WHERE rolname = 'username'")"
EOF1 
echo $F

It gives output as ERROR: permission denied for relation pg_authid

But when i try

su - postgres <<EOF1 
psql -d postgres --tuples-only -P format=unaligned -c "SELECT datname FROM pg_database JOIN pg_authid ON pg_database.datdba = pg_authid.oid WHERE rolname = 'username'"
EOF1 

This prints all db of that username. Why so?

I need to store the ouput to a bash variable for further processing.

Is there any mistake or anyother way to try this out..

Thanks.


回答1:


The inner $(...) expression gets executed before the su part, so it will not be run as postgres but as the current user. This is probably better written as:

command="psql -d postgres --tuples-only -P format=unaligned -c \"SELECT datname FROM pg_database JOIN pg_authid ON pg_database.datdba = pg_authid.oid WHERE rolname = 'username'\""
F=$( su - postgres -c "$command" )

You could put it all together, however:

F=$( su - postgres -c "psql -d postgres --tuples-only -P format=unaligned -c \"SELECT datname FROM pg_database JOIN pg_authid ON pg_database.datdba = pg_authid.oid WHERE rolname = 'username'\"" )

I should also note that the first example that failed for you probably would not set F to anything you could read outside of the su. However, Ubuntu and I presume other modern Linux systems do not allow you to use su in this way. You should use, e.g., sudo -l -u postrges and configure /etc/sudoers appropriately for people to have permission to run psql or whatnot as the postgres user.



来源:https://stackoverflow.com/questions/25691263/how-to-list-databases-owned-by-rolename-in-postgresql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!