PostgreSQL是一個多用戶數據庫,可以為不同用戶指定允許的權限。
一 . 命令創建
-
角色
PostgreSQL使用角色的概念管理數據庫訪問權限。 根據角色自身的設置不同,一個角色可以看做是一個數據庫用戶,或者一組數據庫用戶。 角色可以擁有數據庫對象(比如表)以及可以把這些對象上的權限賦予其它角色, 以控制誰擁有訪問哪些對象的權限。
操作角色的語句:
create role db_role1; /--創建角色/
drop role db_role1; /--刪除角色/
select rolename from pg_roles; /--查看所有角色/
/du --在命令格式下查看所有角色的命令 -
角色的權限
一個數據庫角色可以有很多權限,這些權限定義了角色和擁有角色的用戶可以做的事情。
create role db_role1 LOGIN; --創建具有登錄權限的角色db_role1
create role db_role2 SUPERUSER; --創建具有超級用戶權限的角色
create role db_role3 CREATEDB; --創建具有創建數據庫權限的角色
create role db_role4 CREATEROLE --創建具有創建角色權限的角色
alter role db_role1 nologin nocreatedb; --修改角色取消登錄和創建數據庫權限 -
用戶
其實用戶和角色都是角色,只是用戶是具有登錄權限的角色。
create user db_user1 password '123'; --創建用戶
create role db_user1 password '123' LOGIN; --同上一句等價
drop user db_user1; --刪除用戶
alter user db_user1 password '123456'; --修改密碼
alter user db_user1 createdb createrole; --對用戶授權 -
賦予角色控制權限
我們可以使用GRANT 和REVOKE命令賦予用戶角色,來控制權限。
create user db_user1; --創建用戶1
create user db_user2; --創建用戶2
create role db_role1 createdb createrole; --創建角色1
grant db_role1 to db_user1,db_user2; --給用戶1,2賦予角色1,兩個用戶就擁有了創建數據庫和創建角色的權限
revoke db_role1 from db_user1; --從用戶1移除角色1,用戶不在擁有角色1的權限
二 . 連接Python進行創建
1 . 創建用戶
import psycopg2 connection = psycopg2.connect( host="127.0.0.1", port="5432",database="tables", user="postgres", password="postgres") cur = connection.cursor() user_name = "alice" pwd = 123456 # 創建用戶 cur.execute( f"CREATE USER {user_name} PASSWORD '{pwd}'".format(user_name=user_name, pwd=pwd)) connection.commit() cur.close() #關閉數據庫連接 connection.close()
2 . 賦予用戶角色
import psycopg2 connection = psycopg2.connect( host="127.0.0.1", port="5432",database="grid9", user="postgres", password="postgres") cur = connection.cursor() user_name = "alice" roles = "pg_monitor" cur.execute( f"grant {roles} to {user_name}".format(roles=roles, user_name=user_name)) connection.commit() cur.close() #關閉數據庫連接 connection.close()
3 . 更換角色
注意 : 更換用戶的角色需要先把原來的角色去掉 , 如果不去掉直接 grant 相當於給這個角色 又 賦予了一個角色 .
import psycopg2 connection = psycopg2.connect( host="127.0.0.1", port="5432",database="grid9", user="postgres", password="postgres") cur = connection.cursor() user_name = "alice" last_roles = "pg_monitor" # 目前的角色 roles = "pg_read_all_settings" # 要更換的角色 cur.execute( f"revoke {last_roles} from {user_name}".format(last_roles=last_roles, user_name=user_name)) cur.execute( f"grant {roles} to {user_name}".format(roles=roles, user_name=user_name)) connection.commit() cur.close() #關閉數據庫連接 connection.close()
4 . 刪除用戶
import psycopg2 connection = psycopg2.connect( host="127.0.0.1", port="5432",database="grid9", user="postgres", password="postgres") cur = connection.cursor() user_name = "alice" cur.execute( f"drop USER {user_name}".format(user_name=user_name)) connection.commit() cur.close() #關閉數據庫連接 connection.close()