4案例4:配置一個數據庫
4.1問題
本例要求在虛擬機server0上部署MariaDB數據庫,具體要求如下:
- 此數據庫系統只能被localhost訪問
- 新建一個數據庫名爲Contacts,其中應該包含來自數據庫複製的內容,複製文件的URL爲:http://classroom/pub/materials/users.sql
- 除了root用戶,此數據庫智能被用戶Raikon查詢,此用戶的密碼爲atenorth
- root用戶的密碼爲atenorth
4.2方案
爲數據庫賬號修改密碼:
mysqladmin [-u用戶名] [-p[舊密碼]] password '新密碼'
導入/恢復到數據庫:
mysql [-u用戶名] [-p[密碼]] 數據庫名 < 備份文件.sql
爲數據庫用戶授權/撤銷權限:
grant 權限1,權限2... on 庫名.表名 to 用戶名@客戶機地址 identified by '密碼';
revoke 權限1,權限2... on 庫名.表名 from 用戶名@客戶機地址;
4.3步驟
實現此案例需要按照如下步驟進行。
步驟一:禁止mariadb服務提供網絡監聽(只服務於本機)
1)修改配置文件
[root@server0 ~]# vim /etc/my.cnf
[mysqld]
skip-networking //跳過網絡
2)重啓mariadb服務
[root@server0 ~]# systemctl restart mariadb //重啓服務
3)確認結果
[root@server0 ~]# netstat -anptu | grep :3306 //已經不提供端口監聽
[root@server0 ~]# pgrep -l mysqld //但進程仍在
3127 mysqld_safe
3297 mysqld
步驟二:配置數據庫管理密碼
1)使用mysqladmin爲用戶root設置密碼
原管理賬號root的密碼爲空,因此無需驗證舊密碼:
[root@server0 ~]# mysqladmin -u root password 'atenorth'
2)驗證新密碼是否可用
root使用空密碼從本機連接將會失敗:
[root@server0 ~]# mysql -uroot
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)
必須指定正確的新密碼才能連接成功:
[root@server0 ~]# mysql -uroot -patenorth
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 4
Server version: 5.5.35-MariaDB MariaDB Server
Copyright (c) 2000, 2013, Oracle, Monty Program Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
.. ..
步驟三:建Contacts庫並導入備份數據
1)創建新庫Contacts,並退出操作環境
MariaDB [(none)]> CREATE DATABASE Contacts;
Query OK, 1 row affected (0.00 sec)
MariaDB [(none)]> QUIT
Bye
2)下載指定的數據庫備份
[root@server0 ~]# wget http://classroom.example.com/pub/materials/users.sql
--2016-11-26 19:00:37-- http://classroom.example.com/pub/materials/users.sql
Resolving classroom.example.com (classroom.example.com)... 172.25.254.254
Connecting to classroom.example.com (classroom.example.com)|172.25.254.254|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 2634 (2.6K) [application/sql]
Saving to: ‘users.sql’
100%[=====================>] 2,634 --.-K/s in 0s
2016-11-26 19:00:37 (269 MB/s) - ‘users.sql’ saved [2634/2634]
[root@server0 ~]# ls -lh users.sql //確認下載的文件
-rw-r--r--. 1 root root 2.6K Mar 31 2016 users.sql
3)導入數據庫
[root@server0 ~]# mysql -uroot -patenorth Contacts < users.sql
4)重新連入操作環境,確認導入結果
[root@server0 ~]# mysql -uroot -patenorth
.. ..
MariaDB [(none)]> USE Contacts; //使用指定庫
Database changed
MariaDB [Contacts]> SHOW TABLES; //列出有哪些表
+--------------------+
| Tables_in_Contacts |
+--------------------+
| base |
| location |
+--------------------+
2 rows in set (0.00 sec)
步驟四:爲Contacts庫授權
1)允許用戶Raikon從本機訪問,具有查詢權限,密碼爲atenorth
MariaDB [Contacts]> GRANT select ON Contacts.* TO Raikon@localhost IDENTIFIED BY 'atenorth';
Query OK, 0 rows affected (0.00 sec)
2)退出操作環境
MariaDB [Contacts]> QUIT
Bye
[root@server0 ~]#