天天看點

PostgreSQL對現有,建立的表和視圖授權給使用者

由于開發提出需求:

(1)在多個PostgreSQL的instacne上面建立一個readonly使用者,僅對資料庫裡面的表或者視圖(包括物化視圖)有僅有select權限,并且對以後建立的表和視圖也要有select權限,我們知道PostgreSQL

    在schema下建立的表,對于一個已經存在的使用者不會自動賦予select的權限的,需要我們使用grant select...手動去執行,這樣就比較麻煩,總不能每次建立表,我們就賦權一次,要知道我們有很多執行個體,總不能把時間都放在這樣沒有       意義的事情上,再說了我們也不能時刻監督有哪些PostgreSQL有建立的表,是以我們需要對未來的表提前授權,檢視了一下PostgreSQL網站,發現指令alter default privileges...可以實作這個功能.

(2)alter default privileges沒有對已經存在的表和視圖授權的功能,是以想要對現在和未來的對象都賦權,還需要使用grant select對現有的表賦權.

(3)由于需要執行的db/schenma非常多,一條一條指令執行的話不太現實,需要編寫腳本,批量執行.

(4)具體如何實作可以參考測試過程:

http://blog.51cto.com/darrenmemos/2086198 腳本如下:

#!/bin/ksh -x
# ###########################################################################
#       Name:            postgreSQL_grant_readonly_privileges.sh
#       Location:
#       Function:        PostgreSQL grant readonly privileges
#       Author:
#       Create Date:
#       update Date:
#############################################################################

/usr/local/pgsql/bin/psql -d postgres -q -t -c "select datname from pg_catalog.pg_database where datname not in('postgres','template1','template0');" | grep -v "^$" > /tmpb_list.log

while read db_name
do
   /usr/local/pgsql/bin/psql -d ${db_name} -q -t -c "select schema_name from information_schema.schemata where schema_name not in pg_catalog','information_schema','pg_toast','pg_temp_1','pg_toast_temp_1');" | grep -v "^$" > /tmp/schema_list.log

   while read schema_name
   do
    /usr/local/pgsql/bin/psql -d ${db_name} -q -t -c "grant select on all tables in schema ${schema_name} to readonly;"
    /usr/local/pgsql/bin/psql -d ${db_name} -q -t -c "grant usage on schema ${schema_name} to readonly;"
    /usr/local/pgsql/bin/psql -d ${db_name} -q -t -c "alter default privileges in schema ${schema_name} grant select on tables to readonly;"
   done < /tmp/schema_list.log

done < /tmp/db_list.log

exit 0      

然後就可以在伺服器上批量執行了。

參考連結:

https://www.postgresql.org/docs/9.3/static/sql-grant.html https://www.postgresql.org/docs/9.4/static/sql-alterdefaultprivileges.html

繼續閱讀