#!/bin/bash #菜单 function menu(){ echo -e "\t\t\t************************" echo -e "\t\t\t* 操作数据库 *" echo -e "\t\t\t************************" echo -e "\t\t\t* 1、登录数据库 *" echo -e "\t\t\t* 2、创建用户或增加权限*" echo -e "\t\t\t* 3、sql语句操作数据库 *" echo -e "\t\t\t* 4、更改用户密码 *" echo -e "\t\t\t* 0、退出 *" echo -e "\t\t\t************************" } #输入MySQL的用户名和密码 function input(){ echo -e "\t\t\t请登录数据库" read -p "请输入mysql用户名:" user read -s -p "请输入mysql的密码:" passwd } #判断输入的用户名密码是否正确 function panduan(){ mysql -u$user -p$passwd -e exit 1>/dev/null 2>&1 if [ $?!= 0 ] then echo -e "\n\t\t\t用户名或密码错误,请重新输入!" input else echo -e "\n\t\t\t数据库登录成功!" fi } #创建用户并授权 function createuser(){ echo -e "已存在的用户如下,如果输入的用户已存在,则增加该用户到权限" mysql -u$user -p$passwd -e "select user,host from mysql.user;" read -p "请输入要创建的用户名:" newuser read -s -p "请输入新用户的密码:" newpasswd echo -e "请输入此用户的主机名(%代表所有的主机都能用此账户访问数据库,具体到某几个主机名中间用英文的逗号隔开,如localhost,192.168.1.1):" read hostname echo -e "请输入授予此用户操作数据库的权限(all代表全部,具体到某几个权限中间用英文的逗号隔开,如create,select):" read grant echo -e "请输入授予此用户的访问的库和表的权限(*.*代表全部的库和表,具体到某几个库中间用英文的逗号隔开,如database1.table1,database2.table2):" read database mysql -u$user -p$passwd -e "grant $grant on $database to '$newuser'@'$hostname' identified by '$newpasswd';" 2>/tmp/error.txt if [ -s /tmp/error.txt ] then echo -e "\t\t数据库的权限或库名、表名输入错误!" else echo -e "\n\t\t\t用户创建成功!" fi } #命令行操作数据库 function orders(){ while true do echo -e "\n" echo -e "请输入mysql语句:" read order mysql -u$user -p$passwd -e "$order" 2>/dev/null if [ $?!=0 ] then echo -e "\t\t\tsql语句输入错误!" fi done } #修改密码 function change(){ echo -e "数据库中已存在的用户如下:" tuser=`mysql -u$user -p$passwd -e "select distinct User from mysql.user;"|awk '{print $1}'|sed -n '2,$p'` echo $tuser while true do echo -e "请输入要修改的用户名:" read cuser echo -e "请输入新密码" read -s cpasswd echo -e "请再次输入新密码" read -s zpasswd echo $tuser|grep $cuser>/tmp/tuser.txt if [ "$cpasswd" = ""$zpasswd"" -a -s /tmp/tuser.txt ] then mysql -u$user -p$passwd </tmp/mysql.txt if [ -s /tmp/mysql.txt ] then echo -e "\n\t\t\t用户名或密码错误,请重新输入!" else break fi done ;; 2) input panduan createuser ;; 3) input orders ;; 4) input panduan change ;; 0) exit 0;; *) echo -e "\t\t\t请输入有效数字!" ;; esac done