温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

PostgreSQL对现有,新建的表和视图授权给用户

发布时间:2020-07-06 17:52:04 来源:网络 阅读:15163 作者:Darren_Chen 栏目:MySQL数据库

由于开发提出需求:

(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)具体如何实现可以参考测试过程:

https://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


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI