Shell腳本之Mysql授權

近段時間,由於項目較多,開發人員頻繁要求數據庫賬號授權。本來想着把測試環境的數據庫權限直接給他們自己管理就好了,可領導不同意。那好吧,只能給他們開權限唄。時間長了,感覺這樣的工作實在枯燥、乏味,但又不得不幹。於是就想着,寫個腳本吧,免得每次還得登陸數據庫grant授權,希望能對工作效率有所提高。


下面是我寫的一個簡單的shell腳本,


#!/bin/sh

#

# Mysql數據庫用戶權限管理

#

. /etc/rc.d/init.d/functions

#定義全局變量mysql

MYSQLCMD="/usr/local/mysql/bin/mysql"


#聲明添加用戶授權函數

function add_auth()

{

read -p 'Port: ' add_auth[0]

read -p 'DB [db.* | db.t1]: ' add_auth[1]

read -p 'Permisions [SELECT,UPDATE...]: ' add_auth[2]

read -p "Authorized to host's IP: " add_auth[3]

read -p 'Username: ' add_auth[4]

read -s -p 'Password: ' add_auth[5]#隱藏密碼回顯


#定義局部參數變量

PORT=${add_auth[0]} #數據庫端口

DB=${add_auth[1]}#需要授權的數據庫或表

LIMITS=${add_auth[2]}#權限類型

IP=${add_auth[3]}#授權遠程主機IP登陸

USERNAME=${add_auth[4]}#連接用戶名

PASSWD=${add_auth[5]}#密碼


SOCKT="/tmp/mysql${PORT}.sock"#數據庫連接SOCK文件


#授權

$MYSQLCMD -S $SOCKT -e "grant $LIMITS on ${DB} to \"${USERNAME}\"@\"${IP}\" identified by \"$PASSWD\";" && ret1=0

#刷新授權表

$MYSQLCMD -S $SOCKT -e "FLUSH PRIVILEGES;" && ret2=0

if [ $ret1 = 0 ] && [ $ret2 = 0 ]

then

echo -e "\n\033[32;49;1m Successfully Authorized for user $USER. \033[39;49;0m"

fi

}


#聲明撤銷用戶權限函數drop_user()

function drop_user()

{

read -p 'Port: ' revoke_auth[0]

read -p 'Need to revoke username: ' revoke_auth[1]

read -p 'Revoke Host: ' revoke_auth[2]

PORT=${revoke_auth[0]}

USER=${revoke_auth[1]}

HOST=${revoke_auth[2]}

SOCKT="/tmp/mysql${PORT}.sock"


$MYSQLCMD -S $SOCKT -e "drop user ${USER}@\"${HOST}\";" && ret1=0

$MYSQLCMD -S $SOCKT -e "FLUSH PRIVILEGES;" && ret2=0


if [ $ret1 = 0 ] && [ $ret2 = 0 ]

then

echo -e "\n\033[32;49;1m Successfully to drop user $USER. \033[39;49;0m"

fi


}


#讀取用戶輸入,判斷添加用戶授權OR撤銷用戶

read -p 'Add or revoke the Authorization? [ add | drop ] ' n


case "$n" in

'add')

add_auth

;;

'drop')

drop_user

;;

*)

echo "Select: add or drop"

esac


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章