文章目錄
- MariaDB 數據庫管理
- 介紹 MariaDB
- 數據庫介紹
- 數據庫種類
- 關系數據庫
- MariaDB 介紹
- 部署 MariaDB
- 安裝 MariaDB
- 加固 MariaDB
- 連接 MariaDB
- 配置 MariaDB
- MariaDB 中 SQL
- 描述 SQL
- 連接數據庫
- 數據庫操作
- 查詢數據庫列表
- 使用數據庫
- 創建數據庫
- 刪除數據庫
- 表操作
- 環境準備
- 查詢表
- 查詢表列表
- 查詢表結構
- 查詢表中數據
- WHERE子句
- 多表查詢
- 函數
- 創建表
- 插入記錄
- 更新記錄
- 刪除記錄
- 刪除表
- 管理 MariaDB 用戶
- 創建用戶賬戶
- 控制用戶權限
- 查詢用戶權限
- 授予用戶權限
- 回收用戶權限
- 刪除用戶
- 更改用戶密碼
- 排故數據庫訪問
- 忘記 root 用戶密碼
- 備份和恢復
- 備份方式
- 邏輯備份
- 物理備份特征
- 執行備份
- 執行邏輯備份
- 執行物理備份
- 執行恢復
- 恢復邏輯備份
- 恢復物理備份
- WEB 服務器
- WEB 服務器簡介
- 常見web服務器
- Apache
- Nginx
- Lighttpd
- Tomcat
- IIS
- Apache
- 簡介
- 服務器配置
- 安裝和配置
- 配置文件
- Apache 手冊
- 啟用 Userdir
- 虛擬主機
- 基于主機名的虛擬主機
- 基于端口的虛擬主機
- 配置 SSL/TLS
- 支持動態腳本
- 使用 perl
- 使用 PHP
- 使用 Python Scripts
- 使用 Ruby Scripts
- 配置認證
- 配置基本認證
- 配置操作系統賬戶認證
- 配置LDAP認證
- Nginx
- 安裝 nginx
- 啟用 UserDir
- 虛擬主機
- 根據名稱
- 根據 port
- 配置SSL/TLS
- 生成證書
- 配置站點
- 配置基本認證
- 支持動態腳本
- 使用 PHP
- 使用 FastCGI
- 部署反向代理
- 角色說明
- 代理服務器配置
- 真實服務器配置
MariaDB 數據庫管理
章節內容:
- 介紹 MariaDB 數據庫
- 部署 MariaDB 數據庫
- 實踐 MariaDB 中 SQL
- 管理 MariaDB 用戶
- 備份和恢復 MariaDB
介紹 MariaDB
數據庫介紹
**數據庫,是一個存放計算機數據的倉庫。**這個倉庫是按照一定的數據結構來對數據進行組織和存儲的,我們可以通過數據庫提供的多種方法來管理其中的數據。
數據結構,是指數據的組織形式或數據之間的聯系。
數據庫種類
按照早期的數據庫理論,比較流行的數據庫模型有三種,分別為:
- 層次式數據庫,以層次模型建立的數據庫,例如文件系統。
- 網狀數據庫,以網狀模型建立的數據庫,例如網絡通信。
- 關系型數據庫,以二維表模型建議的數據庫,例如圖書館管理系統。
在當今的互聯網企業中,最常用的數據庫模式主要有兩種:
- 關系型數據庫,把復雜的數據結構歸結為簡單的二維表形式。在關系型數據庫中,對數據的操作幾乎全部建立在一個或多個關系表格上,通過對這些關聯的表格分類、合并、連接或選取等運算來實現數據庫的管理。例如:Oracle、MySql和PostgreSQL等。
- 非關系型數據庫,也被稱為 NoSQL 數據庫,本意是“Not Only SQL”,而非“NO SQL”的意思,因此,NoSQL的產生并不是要徹底否定關系型數據庫,而是作為傳統數據庫的一個有效補充。典型產品有Redis(持久化緩存)、Mongodb、Memcached(純內存)等。
關系數據庫
關系數據庫將結構化數據存儲在一組相互關聯的表中。 這意味著一個表中的信息可以輕松地與另一表中的信息組合在一起,以處理和提供有關該數據的報告。
關系數據庫管理系統(RDBMS-relational database management system)是用于管理關系數據庫的軟件。大多數關系數據庫管理系統都允許您使用結構化查詢語言(SQL)查找和管理數據庫中的數據。
許多組織使用關系數據庫存儲業務信息,例如:庫存,銷售和財務。 關系數據庫管理系統在許多應用中起著關鍵作用。 例如,許多需要支持動態生成內容的Web應用程序都是圍繞LAMP(LNMP)解決方案構建:
- Linux 操作系統提供了基本的環境。
- Apache HTTPS Server或Nginx,提供Web服務器。
- MariaDB,MySQL或其他關系數據庫,例如PostgreSQL,用于存儲站點數據。
- 由 Web 服務器運行的編程語言,例如 PHP,Python,Perl,Ruby,Java,服務器端JavaScript或其他,可以更新數據庫中的數據并使用它為用戶動態構建網頁。
由于關系數據庫通常與系統管理員管理的應用程序集成在一起,因此即使您不是數據庫管理員,也有必要了解這些服務及其數據的安裝和管理知識。
MariaDB 介紹
MariaDB數據庫管理系統是MySQL數據庫的一個分支,主要由開源社區維護,采用GPL授權許可。開發這個MariaDB數據庫分支的可能原因之一是:甲骨文公司收購了MySQL后,有將MySQL閉源的潛在風險,因此MySQL開源社區采用分支的方式來避開這個風險。
MariaDB數據庫完全兼容MySQL數據庫,包括API和命令行,使之能輕松的成為MySQL的代替品。
MariaDB數據庫管理系統可以包含多個database,每個database包涵多張表。
關系數據庫的表采用二維表格來存儲數據,類似于Excle工作表。
- 表中的一行即為一個元組,或稱為一條記錄。
- 數據表中的每一列稱為一個字段(屬性),表是由其包含的各種字段定義,每個字段描述了它所含有的數據意義,為每個字段分配一個數據類型,定義它們的數據長度和其他屬性。
- 行和列的交叉位置表示某個屬性值。
部署 MariaDB
安裝 MariaDB
在Rocky 8中,MariaDB由AppStream存儲庫提供。
安裝
# 安裝服務端
[root@server ~ 11:01:56]# yum install -y mariadb-server# 安裝客戶端
[root@client ~ 11:05:16]# yum install -y mariadb
啟用并啟動服務
[root@server ~ 11:02:15]# systemctl enable --now mariadb
配置防火墻
[root@server ~ 11:02:36]# firewall-cmd --permanent --add-service=mysql
success
[root@server ~ 11:02:42]# firewall-cmd --reload
success
加固 MariaDB
MariaDB數據庫默認具有test數據庫和一些不太安全的配置。運行mysql_secure_installation
修改這些配置。
[root@server ~ 11:02:49]# mysql_secure_installation
交互式提示您進行更改,包括:
- 為root帳戶設置密碼。
- 禁止root帳戶從本地主機外部訪問數據庫。
- 刪除匿名用戶帳戶。
- 刪除用于演示的test數據庫。
連接 MariaDB
MariaDB客戶端可以通過兩種方式連接到服務器:
-
如果客戶端與服務器在同一臺計算機上運行,則它可以使用特殊的套接字文件與MariaDB通信。 這種方式更安全,因為MariaDB不需要偵聽來自網絡客戶端的連接。 但是,使用該數據庫的服務都需要在MariaDB服務器上運行,會影響性能。
[root@server ~ 10:04:57]# mysql -uroot Welcome to the MariaDB monitor. Commands end with ; or \g. Your MariaDB connection id is 2 Server version: 5.5.68-MariaDB MariaDB ServerCopyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.MariaDB [(none)]>
-
客戶端可以使用TCP/IP網絡連接到MariaDB服務。 遠程服務器與MariaDB服務器運行在不同主機。 此時服務器需要配置偵聽端口3306/TCP上的連接。
# 數據庫服務器本機創建連接用戶 [root@server ~ 11:03:37]# mysql -uroot MariaDB [(none)]> grant all privileges on *.* to zzh@'%' identified by 'redhat'; Query OK, 0 rows affected (0.00 sec)MariaDB [(none)]> quit Bye# 客戶端測試 [root@client ~ 11:05:40]# mysql -uzzh -predhat -h server
配置 MariaDB
默認情況下,MariaDB 偵聽系統中所有網絡地址上3306/TCP端口。
MariaDB 配置文件:
- 主配置文件 /etc/my.cnf
- 輔助配置文件 /etc/my.conf.d/*
/etc/my.cnf.d/mariadb-server.cnf 文件是數據庫服務主要配置。 在該文件的 [mysqld] 塊中可以定義以下參數:
- bind-address,該指令指定MariaDB用來偵聽客戶端連接的網絡地址。 只能輸入一個選項。 可能的選項包括:
- 單個IPv4地址。
- 單個IPv6地址。
- ::連接到所有可用地址(IPv6和IPv4)。
- 對于所有IPv4地址,保留為空白(或設置為0.0.0.0)。
- 如果只希望本地客戶端訪問MariaDB,則可以使用127.0.0.1或**::1**作為網絡地址。
- skip-networking,如果在配置文件的[mysqld]部分中設置skip-networking或skip-networking = 1,則將禁用網絡連接,并且客戶端必須使用套接字文件與MariaDB通信。 如果您設置skip-networking = 0(默認值),MariaDB會偵聽網絡連接。
- port, 您可以使用此設置指定3306/TCP以外的網絡端口。
客戶端配置示例:
[root@server ~ 11:03:52]# vim /etc/my.cnf.d/mysql-clients.cnf
[mysql]user=zzhpassword=redhathost=serverport=3306
# database=test
MariaDB 中 SQL
描述 SQL
SQL(Structured Query Language),結構化查詢語言,是1986年10 月由美國國家標準局頒布的數據庫語言。國際標準化組織(ISO)也頒布了SQL國際標準。
結構化查詢語言是關系數據庫最重要的操作語言,它的影響已經超出數據庫領域,得到其他領域的重視和采用,如人工智能領域的數據檢索,第四代軟件開發工具中嵌入SQL的語言等。
SQL語句可簡單分為如下幾類:
- 數據查詢語言(DQL:Data Query Language):也稱為“數據檢索語句”,用以從表中獲得數據,保留字SELECT WHERE,ORDER BY,GROUP BY和HAVING。
- 數據操作語言(DML:Data Manipulation Language):其語句包括動詞INSERT,UPDATE和DELETE。
- 數據定義語言(DDL):其語句包括動詞CREATE和DROP。例如,在數據庫中創建新表(CREATE TABLE)、刪除表(DROP TABLE),為表添加索引等。
- 事務處理語言(TPL):它的語句能確保被DML語句影響的表的所有行及時得以更新。TPL語句包括BEGIN TRANSACTION,COMMIT和ROLLBACK。
- 數據控制語言(DCL):它的語句通過GRANT或REVOKE獲得許可,確定單個用戶和用戶組對數據庫對象的訪問。
連接數據庫
mariadb軟件包提供了命令mysql,該命令支持對MariaDB數據庫的交互式和非交互式訪問。
- 交互式執行時,結果以ASCII表的格式顯示。
- 非交互執行時,結果以制表符分隔的格式顯示。
示例:
[root@server ~]# mysql -u root -h localhost -p
首次安裝時,MariaDB默認設置root用戶帳戶無需密碼即可進行訪問。
[root@server ~ 11:08:23]# mysql -u root
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 8
Server version: 10.3.17-MariaDB MariaDB ServerCopyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.MariaDB [(none)]>
執行交互式SQL語句時,MariaDB提示符在方括號中顯示您當前選擇數據庫。
數據庫操作
查詢數據庫列表
MariaDB [(none)]> SHOW DATABASES;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
+--------------------+
3 rows in set (0.019 sec)MariaDB [(none)]>
數據庫說明:
- mysql 數據庫,是一個系統數據庫,保存數據庫用戶及其訪問權限等信息。
- INFORMATION_SCHEMA 數據庫,保存關于數據庫或者數據表的元數據信息。
- **PERFORMANCE_SCHEMA **數據庫,保存數據庫服務器性能信息。
使用數據庫
您可以使用 USE 語句選擇數據庫之一,例如:USE mysql;
,后續默認操作的表屬于mysql數據庫。
MariaDB [(none)]> USE mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -ADatabase changed
MariaDB [mysql]>
SQL語句不區分大小寫,但數據庫名稱區分大小寫。 通常的做法是數據庫名稱全為小寫字母,SQL語句全為大寫字母,以區分SQL語句與語句的目標或參數。
創建數據庫
MariaDB [mysql]> CREATE DATABASE laoma;
Query OK, 1 row affected (0.010 sec)MariaDB [mysql]> USE laoma;
Database changed
刪除數據庫
DROP DATABASE語句刪除數據庫中的所有表并刪除數據庫。 這將破壞數據庫中的所有數據。 只有對該數據庫具有DROP特權的用戶才能運行此語句。 這不會更改數據庫的用戶特權。 如果重新創建具有該名稱的數據庫,則為舊數據庫設置的用戶權限仍然有效。
MariaDB [inventory]> DROP DATABASE zzh;
Query OK, 0 rows affected (0.006 sec)
表操作
SQL CRUD操作(create 添加數據 read讀取數據 update 修改數據delete刪除數據)。
環境準備
# 導入備份
[root@server ~ 11:23:05]# mysql -uroot -predhat -e 'create database inventory;'
[root@server ~ 11:24:29]# mysql -uroot -predhat inventory < inventory.dump
查詢表
查詢表列表
查詢表列表
MariaDB [(none)]> USE inventory;
MariaDB [inventory]> SHOW TABLES;
+---------------------+
| Tables_in_inventory |
+---------------------+
| category |
| manufacturer |
| product |
+---------------------+
3 rows in set (0.001 sec)
查詢表結構
MariaDB [inventory]> DESCRIBE product;
+-----------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(100) | NO | | NULL | |
| price | double | NO | | NULL | |
| stock | int(11) | NO | | NULL | |
| id_category | int(11) | NO | | NULL | |
| id_manufacturer | int(11) | NO | | NULL | |
+-----------------+--------------+------+-----+---------+----------------+
6 rows in set (0.008 sec)MariaDB [inventory]>
輸出顯示,表格中有六列(屬性):
- Field 列,顯示該屬性名稱。
- Type 列,顯示該屬性的數據必須采用的格式。例如,stock屬性必須是最多11位數字的整數。
- Null 列,指示此屬性是否可以為null。
- Default 列,指示如果未指定該屬性,則是否設置了默認值。
- Key 列,顯示屬性ID是primary key。 主鍵是表中一行的唯一標識符。 該屬性的任何其他行都不能具有相同的值。
- Extra列,提供該列額外信息,對于id字段標記為auto_increment。 這意味著每次將新項目插入表中時,該條目的屬性值都會增加。 這樣可以更輕松地使數字主鍵保持唯一。
查詢表中數據
查詢表中所有記錄所有字段
MariaDB [inventory]> SELECT * FROM product;
+----+-------------------+---------+-------+-------------+-----------------+
| id | name | price | stock | id_category | id_manufacturer |
+----+-------------------+---------+-------+-------------+-----------------+
| 1 | ThinkServer TS140 | 539.88 | 20 | 2 | 4 |
| 2 | ThinkServer RD630 | 2379.14 | 20 | 2 | 4 |
| 3 | RT-AC68U | 219.99 | 10 | 1 | 3 |
| 4 | X110 64GB | 73.84 | 100 | 3 | 1 |
+----+-------------------+---------+-------+-------------+-----------------+
4 rows in set (0.004 sec)MariaDB [inventory]> SELECT * FROM category;
+----+------------+
| id | name |
+----+------------+
| 1 | Networking |
| 2 | Servers |
| 3 | Ssd |
+----+------------+
3 rows in set (0.001 sec)MariaDB [inventory]> SELECT * FROM manufacturer;
+----+----------+----------------+-------------------+
| id | name | seller | phone_number |
+----+----------+----------------+-------------------+
| 1 | SanDisk | John Miller | +1 (941) 329-8855 |
| 2 | Kingston | Mike Taylor | +1 (341) 375-9999 |
| 3 | Asus | Wilson Jackson | +1 (432) 367-8899 |
| 4 | Lenovo | Allen Scott | +1 (876) 213-4439 |
+----+----------+----------------+-------------------+
4 rows in set (0.001 sec)MariaDB [inventory]>
查詢表中所有記錄特定字段
MariaDB [inventory]> SELECT name,price,stock FROM product;
+-------------------+---------+-------+
| name | price | stock |
+-------------------+---------+-------+
| ThinkServer TS140 | 539.88 | 20 |
| ThinkServer RD630 | 2379.14 | 20 |
| RT-AC68U | 219.99 | 10 |
| X110 64GB | 73.84 | 100 |
+-------------------+---------+-------+
4 rows in set (0.001 sec)
WHERE子句
MariaDB [inventory]> SELECT * FROM product WHERE price > 100;
+----+-------------------+---------+-------+-------------+-----------------+
| id | name | price | stock | id_category | id_manufacturer |
+----+-------------------+---------+-------+-------------+-----------------+
| 1 | ThinkServer TS140 | 539.88 | 20 | 2 | 4 |
| 2 | ThinkServer RD630 | 2379.14 | 20 | 2 | 4 |
| 3 | RT-AC68U | 219.99 | 10 | 1 | 3 |
+----+-------------------+---------+-------+-------------+-----------------+
3 rows in set (0.020 sec)
條件操作數
Operator | Description |
---|---|
= | Equal |
<> | Not equal. Note: In some versions of SQL, this operator may be written as != |
> | Greater than |
< | Less than |
>= | Greater than or equal |
<= | Less than or equal |
BETWEEN | Between an inclusive range |
LIKE | Search for a pattern |
IN | Specify multiple possible values for a column |
# 條件操作符包括:=、<>、>、<、>=、<=
MariaDB [inventory]> SELECT * FROM product WHERE price > 100;# BETWEEN,匹配2個數字之間(包括數字本身)的記錄。
MariaDB [inventory]> SELECT * FROM product WHERE id BETWEEN 1 AND 3;# IN,匹配列表中記錄。
MariaDB [inventory]> SELECT * FROM product WHERE id IN (1,3);
MariaDB [inventory]> SELECT * FROM category WHERE name IN ('Servers','Ssd');# LIKE,用于匹配字符串。%表示一個或多個字符,_表示一個字符,[charlist]表示字符列中的任何單一字符,[^charlist]或者[!charlist]不在字符列中的任何單一字符。
MariaDB [inventory]> SELECT * FROM product WHERE name like '%Server%';# 邏輯與AND
MariaDB [inventory]> SELECT * FROM product WHERE name like '%RD%' AND price>1000;# 邏輯或or
MariaDB [inventory]> SELECT * FROM product WHERE name like '%RD%' OR price>500;# ORDER BY 關鍵字用于對結果集進行排序。
MariaDB [inventory]> SELECT * FROM product ORDER BY price;
MariaDB [inventory]> SELECT * FROM product ORDER BY price desc;
多表查詢
# 示例1:產品類型是Servers的產品名稱和價格
MariaDB [inventory]> SELECT product.name,product.price
FROM product,category
WHERE product.id_category = category.id
AND category.name='Servers';# 示例2:查詢廠商是Lenovo的產品名稱和價格
MariaDB [inventory]> SELECT product.name,product.price
FROM product,manufacturer
WHERE product.id_manufacturer = manufacturer.id
AND manufacturer.name='Lenovo';
函數
# 示例1:查詢產品價格平均值
MariaDB [inventory]> SELECT avg(price) FROM product;# 示例2:查詢產品價格最大值
MariaDB [inventory]> SELECT max(price) FROM product;# 示例3:查詢產品價格最小值
MariaDB [inventory]> SELECT min(price) FROM product;# 示例4:查詢產品存量
MariaDB [inventory]> SELECT sum(stock) FROM product;# 示例5:查詢產品價格最小值的那個產品信息
MariaDB [inventory]> SELECT min(price) FROM product;
MariaDB [inventory]> SELECT * FROM product WHERE price=73.84;
或者
MariaDB [inventory]> SELECT * FROM product WHERE price=(SELECT min(price) FROM product);# 示例6:查詢Lenovo廠商提供了幾種產品
MariaDB [inventory]> SELECT count(product.name)
FROM product,manufacturer
WHERE product.id_manufacturer = manufacturer.id
AND manufacturer.name='Lenovo';# GROUP BY 語句用于結合聚合函數,根據一個或多個列對結果集進行分組。
MariaDB [inventory]> SELECT id_category,sum(stock) FROM product GROUP BY id_category;
創建表
MariaDB [inventory]> CREATE TABLE staff(
id INT(11) NOT NULL,
name VARCHAR(100) NOT NULL,
age INT(11) DEFAULT 10,
id_department INT(11)
);
Query OK, 0 rows affected (0.017 sec)
MariaDB [inventory]> SHOW TABLES;
插入記錄
MariaDB [inventory]> INSERT INTO staff (id,name,age,id_department)
VALUES (1,'zzh1',28,10);
MariaDB [inventory]> INSERT INTO staff (id,name,age) VALUES (2,'zzh2',20);
MariaDB [inventory]> INSERT INTO staff (id,name) VALUES (3,'zzh3');
更新記錄
MariaDB [inventory]> UPDATE staff SET age=30 WHERE id=3;
MariaDB [inventory]> UPDATE staff SET age=30
如果使用不帶WHERE子句的UPDATE,則表中的所有記錄都會更新。
刪除記錄
MariaDB [inventory]> DELETE FROM staff WHERE id=3 ;
MariaDB [inventory]> DELETE FROM staff ;
如果使用不帶WHERE子句的DELETE子句,則表中的所有記錄都會刪除。
刪除表
MariaDB [inventory]> DROP TABLE staff ;
管理 MariaDB 用戶
創建用戶賬戶
默認情況下,MariaDB有自己的用戶和密碼,與本地系統的用戶和密碼分開。這意味著MariaDB數據庫用戶與服務器的Linux用戶不同, 即使用戶帳戶具有相同的名稱。
為了控制用戶對數據庫服務器的訪問級別,必須在MariaDB中設置數據庫用戶并授予他們在服務器及其數據上執行操作的權限。
您可以配置MariaDB使用
pam
身份驗證插件將系統用戶帳戶和密碼集成為MariaDB數據庫用戶,本課程不介紹該配置。 在大多數情況下,最好分開管理數據庫和系統用戶賬戶。
要創建新用戶,您需要以下權限級別之一:
- MariaDB的root用戶。
- 被授予全局CREATE USER特權的用戶。
- 被授予對mysql數據庫的INSERT特權的用戶。
我們可以使用CREATE USER語句,在mysql數據庫的user表中創建一條新記。
用戶名格式:user_name@host_name。 這樣就可以根據主機源,創建具有相同名稱但具有不同特權的多個用戶帳戶。
MariaDB [(none)]> CREATE USER zzh@'%' IDENTIFIED BY 'redhat';
當前,zzh帳戶只能使用密碼redhat從**%**連接。
用戶的密碼,會被加密存在在mysql.user表:
MariaDB [mysql]> SELECT host,user,password FROM user WHERE user = 'zzh';
+-----------+--------+-------------------------------------------+
| host | user | password |
+-----------+--------+-------------------------------------------+
| % | zzh | *84BB5DF4823DA319BBF86C99624479A198E6EEE9 |
+-----------+--------+-------------------------------------------+
1 row in set (0.000 sec)
用戶帳戶定義示例
Account | Description |
---|---|
laoma | User laoma can connect from any host. |
laoma@‘%’ | User laoma can connect from any host. |
laoma@‘localhost’ | User laoma can only connect from localhost. |
laoma@‘192.168.1.5’ | User laoma can only connect from the IP address192.168.1.5. |
laoma@‘192.168.1.%’ | User laoma can connect from any address that belongs to the network 192.168.1.0/24. |
laoma@‘2001:db8:18:b51:c32:a21’ | User laoma can connect from the IP address 2001:db8:18:b51:c32:a21. |
控制用戶權限
默認情況下,新帳戶被授予最小特權。 在不授予其他特權的情況下,laoma用戶只能訪問最少的帳戶信息,大多數其他操作均被拒絕。
示例:
[root@server ~]# mysql -u zzh -p
Enter password: redhat
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 12
Server version: 10.3.17-MariaDB MariaDB ServerCopyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.MariaDB [(none)]> SELECT USER();
+------------------+
| USER() |
+------------------+
| laoma@localhost |
+------------------+
1 row in set (0.003 sec)MariaDB [(none)]> SHOW DATABASES;
+--------------------+
| Database |
+--------------------+
| information_schema |
+--------------------+
1 row in set (0.004 sec)MariaDB [(none)]> USE mysql;
ERROR 1044 (42000): Access denied for user 'laoma'@'localhost' to database 'mysql'
MariaDB [(none)]> CREATE DATABASE inventory;
ERROR 1044 (42000): Access denied for user 'laoma'@'localhost' to database 'inventory'
MariaDB [(none)]>
privileges是用戶在MariaDB中擁有的能力,確定用戶可以做什么以及用戶在MariaDB中可以做什么。特權按范圍進行組織:
-
全局特權,用于管理MariaDB數據庫服務器本身,例如CREATE USER。
-
數據庫特權,用于在MariaDB服務器上創建數據庫和使用數據庫,例如CREATE DATABASE。
-
表特權,用于在特定數據庫中創建表和處理數據,例如CRUD命令。
CRUD是指在做計算處理時的增加(Create)、查詢(Retrieve)(重新得到數據)、更新(Update)和刪除(Delete)幾個單詞的首字母簡寫。
-
列特權,用于授予類似表的命令用法,但用于特定的列(通常很少見)。
詳情參考本節末尾引用的MariaDB文檔。
查詢用戶權限
MariaDB [(none)]> SHOW GRANTS FOR root@localhost;
+----------------------------------------------------------------------------------------------------------------------------------------+
| Grants for root@localhost |
+----------------------------------------------------------------------------------------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY PASSWORD '*84BB5DF4823DA319BBF86C99624479A198E6EEE9' WITH GRANT OPTION |
| GRANT PROXY ON ''@'%' TO 'root'@'localhost' WITH GRANT OPTION |
+----------------------------------------------------------------------------------------------------------------------------------------+
2 rows in set (0.006 sec)
授予用戶權限
GRANT語句可用于向帳戶授予特權。 要授予GRANT特權,連接的用戶必須具有GRANT OPTION且必須具有他們所授予的特定特權。
例如,laoma用戶無法授予數據庫表SELECT特權,除非他們已經具有SELECT特權和GRANT OPTION表特權。
在此示例中,MariaDB根用戶向清單數據庫中類別表上的laoma用戶授予CRUD特權。
[root@server ~]# mysql -u root -p
Enter password: redhatMariaDB [(none)]> GRANT SELECT, UPDATE, DELETE, INSERT-> ON inventory.category-> TO laoma@localhost ;
Query OK, 0 rows affected (0.006 sec)MariaDB [inventory]> exit
Bye
驗證權限
[root@server ~]# mysql -u laoma -p
Enter password: redhatMariaDB [(none)]> USE inventory;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -ADatabase changed
MariaDB [inventory]> SELECT * FROM category;
+----+------------+
| id | name |
+----+------------+
| 1 | Networking |
| 2 | Servers |
| 3 | Ssd |
+----+------------+
3 rows in set (0.004 sec)
授權示例
Grant | Description |
---|---|
GRANT SELECT ON database.table TO username@hostname | Grant SELECT privilege for a specific table in a specific database to a specific user. |
GRANT SELECT ON database. TO username@hostname* | Grant SELECT privilege for all tables in a specific database to a specific user. |
GRANT SELECT ON *.* TO username@hostname | Grant SELECT privilege for all tables in all databases to a specific user. |
GRANT CREATE, ALTER, DROP ON database. to username@hostname* | Grant CREATE, ALTER, and DROP TABLES privileges in a specific database to a specific user. |
GRANT ALL PRIVILEGES ON *.* to username@hostname | Grant all available privileges for all databases to a specific user, effectively creating a superuser, similar toroot. |
回收用戶權限
REVOKE語句從帳戶中刪除特權。 連接的用戶必須具有GRANT OPTION特權,并且必須具有被撤消的特定特權。
MariaDB [(none)]> REVOKE SELECT, UPDATE, DELETE, INSERT-> ON inventory.category FROM zzh@localhost;
Query OK, 0 rows affected (0.011 sec)
刪除用戶
當不再需要特定的用戶帳戶時,可以使用DROP USER將其從數據庫中刪除。
用戶名使用**‘user’@‘host’**格式。
MariaDB [(none)]> DROP USER zzh@localhost;
Query OK, 0 rows affected (0.001 sec)
如果刪除了當前連接的帳戶,則在關閉連接之前不會刪除該帳戶,關閉連接之后才會刪除該帳戶。
更改用戶密碼
# root用戶修改普通用戶賬戶密碼
MariaDB [(none)]> USE mysql;
MariaDB [(mysql)]> UPDATE user SET password=PASSWORD('mypass') WHERE user='zzh' and host=’localhost’;# 或者
MariaDB [(none)]> SET PASSWORD FOR 'zzh'@'localhost' = PASSWORD('mypass');# 普通用戶修改自己賬戶密碼
MariaDB [(none)]> SET PASSWORD = PASSWORD('mypass');
MariaDB [(none)]> FLUSH PRIVILEGES;
排故數據庫訪問
下表總結了用戶在身份驗證和訪問方面可能遇到的一些問題,以及可能的原因。
問題 | 解決方法 |
---|---|
已授予用戶從任何主機進行連接的訪問權限,但只能使用數據庫服務器本地mysql命令進行連接。 | 如果在配置文件/etc/my.cnf.d/mariadb-server.cnf中設置了skip-networking,請刪除該指令并重新啟動服務。 |
用戶可以與localhost上的任何應用程序連接,但不能遠程連接。 | 確保/etc/my.cnf.d/mariadb-server.cnf中的bind-address配置正確。 確保用戶表中包含用戶要嘗試與其連接的主機的條目。 |
用戶可以連接,但看不到除information_schema以外的任何數據庫。 | 確保已授予用戶訪問其數據庫的權限。 剛創建的用戶具有最小權限,會遇到這個問題。 |
用戶可以連接,但不能創建任何數據庫。 | 考慮向用戶授予全局CREATE特權(這也授予DROP特權)。 |
用戶可以連接,但不能讀取或寫入任何數據。 | 向用戶授予他們打算使用的數據庫的CRUD特權。 |
忘記 root 用戶密碼
-
編輯**/etc/my.cnf.d/mariadb-server.cnf**配置文件,在[mysqld]下添加
skip-grant-tables=1
。 -
重啟 mariadb 服務。
-
執行
mysql -u root
命令進入mysql命令行,修改root用戶密碼。[root@server ~ 13:57:54]# mysql -u root MariaDB [(none)]> UPDATE mysql.user SET password=PASSWORD('新密碼') where USER='root'; MariaDB [(none)]> exit
-
把**/etc/my.cnf.d/mariadb-server.cnf配置文件中的
skip-grant-tables=1
注釋掉,然后重啟mariadb**服務。
備份和恢復
備份方式
邏輯備份
邏輯備份,將數據庫導出為包含重新創建數據庫所需的SQL命令的文本文件。
- 通過查詢數據庫,檢索數據庫結構。
- 備份速度較慢,因為服務器必須訪問數據庫信息并將其轉換為邏輯格式。
- 邏輯備份具有高度的可移植性,在某些情況下可以還原到其他數據庫提供程序(例如PostgreSQL)。
- 在服務器聯機時執行。
- 備份不包括日志或配置文件。
物理備份特征
物理備份,復制原始數據庫目錄和包含數據庫內容的文件。
- 備份可以包括日志和配置文件。
- 僅可移植到具有類似硬件和軟件的其他計算機上。
- 比邏輯備份更快。
- 在服務器脫機或數據庫中的所有表均已鎖定時執行,以防止在備份期間進行更改。
執行備份
執行邏輯備份
您在運行mysqldump時所連接的MariaDB用戶至少需要對轉儲表具有SELECT特權,對轉儲視圖至少需要SHOW VIEW,對于轉儲觸發器至少需要TRIGGER特權。
使用mysqldump命令執行邏輯備份。
語法:
Usage: mysqldump [OPTIONS] database [tables]
OR mysqldump [OPTIONS] --databases [OPTIONS] DB1 [DB2 DB3...]
OR mysqldump [OPTIONS] --all-databases [OPTIONS]
For more options, use mysqldump --help
常用選項:
-A, --all-databases Dump all the databases. This will be same as --databaseswith all databases selected.--ignore-database=name Do not dump the specified database. To specify more thanone database to ignore, use the directive multiple times,once for each database. Only takes effect when usedtogether with --all-databases|-A-B, --databases Dump several databases. Note the difference in usage; inthis case no tables are given. All name arguments areregarded as database names. 'USE db_name;' will beincluded in the output.-Y, --all-tablespaces Dump all the tablespaces.--ignore-table=name Do not dump the specified table. To specify more than onetable to ignore, use the directive multiple times, oncefor each table. Each table must be specified with bothdatabase and table names, e.g.,--ignore-table=database.table.-y, --no-tablespaces Do not dump any tablespace information.--add-drop-database Add a DROP DATABASE before each create.--add-drop-table Add a DROP TABLE before each create.-x, --lock-all-tables Locks all tables across all databases. This is achievedby taking a global read lock for the duration of thewhole dump. Automatically turns --single-transaction and--lock-tables off.
示例:
[root@server ~]# mysqldump -u root -p inventory > /backup/inventory.dump
[root@server ~]# mysqldump -u root -p --all-databases > /backup/mariadb.dump
導出的文本文件部分內容示例:
DROP TABLE IF EXISTS `category`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `category` (`id` int(11) NOT NULL AUTO_INCREMENT,`name` varchar(100) NOT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;--
-- Dumping data for table `category`
--LOCK TABLES `category` WRITE;
/*!40000 ALTER TABLE `category` DISABLE KEYS */;
INSERT INTO `category` VALUES (1,'Networking'),(2,'Servers'),(3,'Ssd');
/*!40000 ALTER TABLE `category` ENABLE KEYS */;
UNLOCK TABLES;
執行物理備份
mariabackup工具由AppStream存儲庫中的mariadb-backup包提供。 mariabackup工具執行MariaDB服務器的完整物理備份。
# 在安裝mariadb-server軟件包時,也會安裝mariadb-backup軟件包。
[root@server ~]# yum install mariadb-backup# 準備備份目錄
[root@server ~]# mkdir -p /var/mariadb/backup/# 執行備份
[root@server ~]# mariabackup --backup --target-dir /var/mariadb/backup/ \
> --user root --password redhat
[00] 2021-03-11 17:34:31 Connecting to MySQL server host: localhost, user: root, password: set, port: not set, socket: not set
[00] 2021-03-11 17:34:31 Using server version 10.3.17-MariaDB
mariabackup based on MariaDB server 10.3.17-MariaDB Linux (x86_64)
[00] 2021-03-11 17:34:31 uses posix_fadvise().
[00] 2021-03-11 17:34:31 cd to /var/lib/mysql/
[00] 2021-03-11 17:34:31 open files limit requested 0, set to 1024
[00] 2021-03-11 17:34:31 mariabackup: using the following InnoDB configuration:
......
[00] 2021-03-11 17:34:34 >> log scanned up to (1699497)
[00] 2021-03-11 17:34:34 Executing UNLOCK TABLES
[00] 2021-03-11 17:34:34 All tables unlocked
[00] 2021-03-11 17:34:34 Copying ib_buffer_pool to /var/mariadb/backup/ib_buffer_pool
[00] 2021-03-11 17:34:34 ...done
[00] 2021-03-11 17:34:34 Backup created in directory '/var/mariadb/backup/'
[00] 2021-03-11 17:34:34 Writing backup-my.cnf
[00] 2021-03-11 17:34:34 ...done
[00] 2021-03-11 17:34:34 Writing xtrabackup_info
[00] 2021-03-11 17:34:34 ...done
[00] 2021-03-11 17:34:34 Redo log (from LSN 1699488 to 1699497) was copied.
[00] 2021-03-11 17:34:34 completed OK!#確認目錄中內容
[root@server ~]# ls /var/mariadb/backup/
aria_log.00000001 ib_buffer_pool inventory xtrabackup_checkpoints
aria_log_control ibdata1 mysql xtrabackup_info
backup-my.cnf ib_logfile0 performance_schema
為了避免交互式輸入密碼,可以將密碼配置在配置文件中。
示例:
[root@server ~]# cat /etc/my.cnf.d/mariabackup.cnf
[xtrabackup]
user=root
password=redhat
還可以創建一個具有RELOAD, LOCK TABLES和REPLICATION CLIENT權限的用戶代替root用戶執行此備份。
執行恢復
還原備份時,它將用備份的內容覆蓋數據庫服務器的內容。 如果數據庫中的數據比備份中的數據新,該部分數據將會丟失。
恢復邏輯備份
[root@server ~]# mysql -u root -p inventory < /backup/mariadb.dump
恢復物理備份
mariabackup工具使用以下選項之一,以從物理備份執行還原:
- –copy-back,保留原始備份文件。
- –move-back,將備份文件移動到數據目錄,然后刪除原始備份文件。
操作過程如下:
# 停止mariadb服務
[root@server ~]# systemctl stop mariadb# 確保數據庫數據目錄是空
[root@server ~]# grep '^datadir' /etc/my.cnf.d/mariadb-server.cnf
datadir=/var/lib/mysql
[root@server ~]# rm -rf /var/lib/mysql/*# 恢復備份
[root@server ~]# mariabackup --copy-back --target-dir=/var/mariadb/backup/
...output omitted...
[00] 2020-06-08 22:26:08 completed OK!# 清空數據庫數據目錄
[root@server ~]# chown -R mysql:mysql /var/lib/mysql/# 啟動mariadb服務
[root@server ~]# systemctl start mariadb
WEB 服務器
WEB 服務器簡介
WEB也稱為WWW(WORLD WIDE WEB),中文名字為萬維網、全球信息網等,主要功能是提供網上信息瀏覽服務。Web服務器可以為Internet上的用戶提供WWW、Email和FTP等各種Internet服務。
WEB起源于1989年3月,伯納斯-李 (Tim Berners-Lee) 為了更有效率地讓歐洲核物理實驗室的科學家可以分享及更新他們的研究成果, 于是他開發出超文件傳輸協議(Hyper Text Transport Protocol, HTTP)。為了讓 HTTP 這個協議得以順利的應用,大約在90 年代初期,由伊利諾大學的國家超級計算機應用中心 開發出了HTTPd (HTTP daemon )服務器,也就是后來的Apache。
常見的WEB服務器,除了Apache,還有一些Nginx,Lighttpd,IIS等。
常見web服務器
Apache
Apache HTTP Server,非正式的稱呼 Apache,是世界上應用最廣泛的WEB服務器。
其優勢在于,Apache一個可擴展的Web服務器,支持的模塊非常豐富。
Apache的源代碼是開放的、支持跨平臺應用等。
Apache 是屬于重量級產品,在速度和性能上不及其他輕量級WEB服務器,所消耗的內存也比其他WEB服務器要高。
Nginx
Nginx是一款高性能的HTTP和反向代理服務器,能夠選擇高效的epoll、kqueue、eventport最為網絡I/O模型,在高連接并發的情況下,能夠支持高達5萬個并發連接數的響應,而內存、CPU等系統資源消耗卻非常低,運行非常穩定。
Lighttpd
Lighttpd提供一個專門針對高性能網站,安全、快速、兼容性好并且靈活的WEB Server環境,它具有內存開銷低、CPU占有率低、效能好,以及模塊豐富等特點。支持FastCGI、CGI、Auth、輸出壓縮、URL重寫及Alias等重要功能,屬于輕量級WEB服務器。
Tomcat
Tomcat 是一個開放源代碼、運行servlet和JSP Web應用軟件的基于Java的web應用軟件容器。Tomcat server 是根據servlet和jsp規范執行的,因此也可以說Tomcat server實行了Apache-Jakarta規范,且比絕大多數商用應用軟件服務器要好。tomcat對靜態文件和高并發的處理比較弱。
IIS
Microsoft的Web服務器產品為 Internet Information Server (IIS), IIS 是允許在公共Intranet或Internet上發布信息的Web服務器。IIS是目前最流行的Web服務器產品之一,很多著名的網站都是建立在IIS的平臺上。IIS提供了一個圖形界面的管理工具,稱為 Internet服務管理器,可用于監視配置和控制Internet服務。
IIS是一種Web服務組件,其中包括Web服務器、FTP服務器、NNTP服務器和SMTP服務器,分別用于網頁瀏覽、文件傳輸、新聞服務和郵件發送等方面,它使得在網絡(包括互聯網和局域網)上發布信息成了一件很容易的事。它提供ISAPI(IntranetServer API)作為擴展Web服務器功能的編程接口;同時它還提供一個Internet數據庫連接器,可以實現對數據庫的查詢和更新。
Apache
簡介
Apache HTTP Server,非正式的稱呼 Apache,是世界上應用最廣泛的WEB服務器。
其優勢在于,Apache一個可擴展的Web服務器,支持的模塊非常豐富。
Apache的源代碼是開放的、支持跨平臺應用等。
Apache是屬于重量級產品,在速度和性能上不及其他輕量級WEB服務器,所消耗的內存也比其他WEB服務器要高。
服務器配置
系統:Rocky 8.10(minimal 安裝)
硬件:1CPU/2G 內存/20G 硬盤/1個 NAT模式網卡
網絡信息:10.1.8.10/24 網關10.1.8.2 DNS 223.5.5.5
**配置主機名 網絡信息 /etc/hosts **
安裝和配置
# 安裝
[root@www ~ 15:45:22]# yum -y install httpd# 啟動服務
[root@www ~ 15:45:43]# systemctl enable httpd --now# 可選:修改 ServerName
[root@www ~ 15:46:15]# vim /etc/httpd/conf/httpd.conf
ServerName www.laoma.cloud:80# 配置解析
[root@www ~ 15:46:28]# echo '10.1.8.10 www.laoma.cloud'>> /etc/hosts# 查看主頁目錄
[root@www ~ 15:47:30]# grep ^DocumentRoot /etc/httpd/conf/httpd.conf
DocumentRoot "/var/www/html"# 準備主頁
[root@www ~ 15:47:52]# echo Hello World From Apache. > /var/www/html/index.html# 防火墻放行
[root@www ~ 15:48:24]# firewall-cmd --add-service=http --permanent
[root@www ~]# firewall-cmd --reload# 測試
[root@client ~]# curl http://www.zzh.cloud
# windows客戶端修改C:\Windows\System32\drivers\etc\hosts
# Linux或Unix修改 /etc/hosts
# 添加如下記錄
10.1.8.10 www.zzh.cloud
配置文件
主配置文件:/etc/httpd/conf/httpd.conf
部分參數說明:
-
ServerRoot "/etc/httpd"
,定義配置文件所在位置,后面出現的文件相對路徑都是基于該目錄。 -
IncludeOptional conf.d/*.conf
,定義從配置文件,絕對路徑為/etc/httpd/conf.d/*.conf
-
DocumentRoot "/var/www/html"
,定義網站主目錄位置。 -
以下命令塊定義目錄中主頁文件名。
<IfModule dir_module>DirectoryIndex index.html </IfModule>
建議以上代碼塊定義在目錄中,以限定特定目錄的主頁文件。
Apache 手冊
# 安裝手冊軟件包
[root@www ~]# yum install -y httpd-manual# 重啟服務
[root@www ~]# systemctl restart httpd# 訪問測試
[root@client ~]# firefox http://www.laoma.cloud/manual/

啟用 Userdir
[root@www ~]# vim /etc/httpd/conf.d/userdir.conf
# 修改17行
UserDir enabled# 修改24行
UserDir public_html[root@www ~]# systemctl restart httpd# SELinux
[root@www ~]# setsebool -P httpd_enable_homedirs on
[root@www ~]# restorecon -R /home# 準備測試頁
[root@www ~]# useradd laoma
[root@www ~]# mkdir /home/zzh/public_html
[root@www ~]# chmod 711 /home/zzh
[root@www ~]# chmod 755 /home/zzh/public_html
[root@www ~]# cat << 'EOF' > /home/zzh/public_html/index.html
<html>
<body>
<div style="width: 100%; font-size: 40px; font-weight: bold; text-align: laomaer;">
UserDir Test Page
</div>
</body>
</html>
EOF# 測試
[root@client ~]# curl http://www.laoma.cloud/~laoma/
虛擬主機
同一個web服務器提供多個站點。
一個虛擬網站常見參數說明:
DocumentRoot /var/www/laoma/
,定義主頁目錄。ServerName www.laoma.cloud
,定義虛擬主機名。ServerAdmin laoma@laoma.cloud
,定義網站管理員郵箱。ErrorLog logs/www.laoma.cloud-error_log
,定義錯誤日志位置。CustomLog logs/www.laoma.cloud-access_log combined
,定義正常訪問日志位置。
基于主機名的虛擬主機
示例:兩個虛擬網站www1和www2。
[root@www ~]# vim /etc/httpd/conf.d/vhost-www1.conf
# for www1 virtual domain
<VirtualHost *:80>DocumentRoot /var/www/www1/ServerName www1.laoma.cloudServerAdmin www1@laoma.cloudErrorLog logs/www1.laoma.cloud-error_logCustomLog logs/www1.laoma.cloud-access_log combined<Directory "/var/www/www1">Options Indexes FollowSymLinksAllowOverride NoneRequire all granted</Directory></VirtualHost>[root@www ~]# vim /etc/httpd/conf.d/vhost-www2.conf
# for www2 virtual domain
<VirtualHost *:80>DocumentRoot /var/www/www2/ServerName www2.laoma.cloudServerAdmin www2@laoma.cloudErrorLog logs/www2.laoma.cloud-error_logCustomLog logs/www2.laoma.cloud-access_log combined<Directory "/var/www/www2">Options Indexes FollowSymLinksAllowOverride NoneRequire all granted</Directory></VirtualHost># 準備目錄和測試頁
[root@www ~]# cd /var/www
[root@www www]# mkdir www1 www2
[root@www www]# echo hello www1 > www1/index.html
[root@www www]# echo hello www2 > www2/index.html# 重啟服務
[root@www ~]# systemctl restart httpd# 測試
# windows客戶端修改C:\Windows\System32\drivers\etc\hosts
# Linux或Unix修改 /etc/hosts
# 添加如下記錄
10.1.8.10 www1.laoma.cloud
10.1.8.10 www2.laoma.cloud[root@client ~]# curl http://www1.laoma.cloud/
[root@client ~]# curl http://www2.laoma.cloud/
基于端口的虛擬主機
配置文件示例:
[root@www ~]# vim /etc/httpd/conf.d/vhost-port.conf
Listen 8081
<VirtualHost *:8081>ServerAdmin site1@laoma.cloudDocumentRoot "/var/www/site1"ServerName www.laoma.cloudErrorLog "/var/log/httpd/site1.laoma.cloud-error_log"CustomLog "/var/log/httpd/site1.laoma.cloud-access_log" common<Directory "/var/www/site1">AllowOverride NoneRequire all granted</Directory></VirtualHost>Listen 8082
<VirtualHost *:8082>ServerAdmin site2@laoma.cloudDocumentRoot "/var/www/site2"ServerName www.laoma.cloudErrorLog "/var/log/httpd/site2.laoma.cloud-error_log"CustomLog "/var/log/httpd/site2.laoma.cloud-access_log" common<Directory "/var/www/site2">AllowOverride NoneRequire all granted</Directory></VirtualHost>
# 準備目錄和測試頁
[root@www ~]# cd /var/www
[root@www www]# mkdir site1 site2
[root@www www]# echo hello site1 > site1/index.html
[root@www www]# echo hello site2 > site2/index.html# 重啟服務
[root@www ~]# systemctl restart httpd# 測試
[root@client ~]# curl http://www.laoma.cloud:8081/
hello site1
[root@client ~]# curl http://www.laoma.cloud:8082/
hello site2
配置 SSL/TLS
補充TLS知識
生成自簽名SSL證書
#--1--生成私鑰
[root@www ~]# openssl genrsa -out www.key 2048 #--2--生成請求文件csr,該文件需要簽名
[root@www ~]# openssl req -new -key www.key -out www.csr
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:JS
Locality Name (eg, city) [Default City]:NJ
Organization Name (eg, company) [Default Company Ltd]:LM
Organizational Unit Name (eg, section) []:DEVOPS
Common Name (eg, your name or your server's hostname) []:www.laoma.cloud
Email Address []:laoma@laoma.cloudPlease enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:回車
An optional company name []:回車# 以下非交互方式生成
[root@www ~]# openssl req -new -key www.key -out www.csr -subj "/C=CN/ST=JS/L=NJ/O=LM/OU=DEVOPS/CN=www.laoma.cloud/emailAddress=laoma@laoma.cloud"
#CN的值必須是網站域名 #--3--使用自己的私鑰對請求文件簽名,以生成證書
[root@www ~]# openssl x509 -req -days 3650 -in www.csr -signkey www.key -out www.crt
安裝和配置
[root@www ~]# yum -y install mod_ssl
[root@www ~]# vim /etc/httpd/conf.d/vhost-ssl.conf
<VirtualHost _default_:443>DocumentRoot "/var/www/html"ServerName www.laoma.cloud:443#使用私鑰簽名的證書SSLCertificateFile /etc/ssl/certs/www.laoma.cloud/www.crt#私鑰SSLCertificateKeyFile /etc/ssl/certs/www.laoma.cloud/www.key
</VirtualHost>[root@www ~]# mkdir /etc/ssl/certs/www.laoma.cloud
[root@www ~]# mv www.* /etc/ssl/certs/www.laoma.cloud[root@www ~]# systemctl restart httpd # 設置防火墻
[root@www ~]# firewall-cmd --add-service=https --permanent
success
[root@www ~]# firewall-cmd --reload
success# 測試
[root@client ~]# curl -k https://www.laoma.cloud/# 重定向http請求到https
[root@www ~]# vim /etc/httpd/conf.d/vhost-Rewrite.conf
<VirtualHost *:80>DocumentRoot /var/www/htmlServerName www.laoma.cloudRewriteEngine OnRewriteCond %{HTTPS} offRewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</VirtualHost>[root@www ~]# systemctl restart httpd# 測試
[root@client ~]# curl http://www.laoma.cloud/
支持動態腳本
CGI(公共網關接口)定義了Web服務器與外部內容生成程序交互的方式,這些程序通常被稱為CGI程序或CGI腳本。
By default, CGI is allowed under the “/var/www/cgi-bin” directory。
使用 perl
[root@www ~]# yum -y install perl perl-CGI # 準備新目錄
[root@www ~]# mkdir /var/www/html/cgi-enabled#準備測試頁
[root@www ~]# vim /var/www/html/cgi-enabled/index.cgi
#!/usr/bin/perl
print "Content-type: text/html\n\n";
print "<html>\n<body>\n";
print "<div style=\"width: 100%; font-size: 40px; font-weight: bold; text-align: laomaer;\">\n";
print "CGI Test Page";
print "\n</div>\n";
print "</body>\n</html>\n";# 準備配置文件
[root@www ~]# vim /etc/httpd/conf.d/cgi-enabled.conf
# create new
# processes .cgi and .pl as CGI scripts
<Directory "/var/www/html/cgi-enabled">Options +ExecCGIAddHandler cgi-script .cgi .pl
</Directory>[root@www ~]# systemctl restart httpd# 設置SELinux
[root@www ~]# chcon -R -t httpd_sys_script_exec_t /var/www/html/cgi-enabled
[root@www ~]# semanage fcontext -a -t httpd_sys_script_exec_t /var/www/html/cgi-enabled[root@www ~]# chmod 705 /var/www/html/cgi-enabled/index.cgi# 測試
[root@client ~]# curl http://www.laoma.cloud/cgi-enabled/index.cgi
使用 PHP
[root@www ~]# yum -y install php
[root@www ~]# systemctl restart httpd
[root@www ~]# vim /var/www/html/index.php
<html>
<body>
<div style="width: 100%; font-size: 40px; font-weight: bold; text-align: laomaer;">
<?phpprint Date("Y/m/d");
?>
</div>
</body>
</html># 測試
[root@client ~]# curl http://www.laoma.cloud/index.php
使用 Python Scripts
[root@www ~]# yum -y install python3# the settings below is the one for CGI
[root@www ~]# grep -n "^ *ScriptAlias" /etc/httpd/conf/httpd.conf
247: ScriptAlias /cgi-bin/ "/var/www/cgi-bin/" # 配置訪問其他位置
[root@www ~]# vim /etc/httpd/conf.d/cgi-enabled.conf
# create new
# processes .py as CGI scripts
<Directory "/var/www/html/cgi-enabled">Options +ExecCGIAddHandler cgi-script .py
</Directory>[root@www ~]# systemctl restart httpd# 設置SELinux
[root@www ~]# chcon -R -t httpd_sys_script_exec_t /var/www/html/cgi-enabled
[root@www ~]# semanage fcontext -a -t httpd_sys_script_exec_t /var/www/html/cgi-enabled # 創建測試頁
[root@www ~]# vim /var/www/html/cgi-enabled/index.py
#!/usr/bin/env python3
print ("Content-type: text/html\n\n")
print ("<html>\n<body>")
print ("<div style=\"width: 100%; font-size: 40px; font-weight: bold; text-align: laomaer;\">")
print ("Python Script Test Page")
print ("</div>\n</body>\n</html>")[root@www ~]# chmod 705 /var/www/html/cgi-enabled/index.py# 測試
[root@client ~]# curl http://www.laoma.cloud/cgi-enabled/index.py
使用 Ruby Scripts
[root@www ~]# yum -y install ruby # the settings below is the one for CGI
[root@www ~]# grep -n "^ *ScriptAlias" /etc/httpd/conf/httpd.conf
247: ScriptAlias /cgi-bin/ "/var/www/cgi-bin/" [root@www ~]# vim /etc/httpd/conf.d/cgi-enabled.conf
# create new
# processes .rb as CGI scripts
<Directory "/var/www/html/cgi-enabled">Options +ExecCGIAddHandler cgi-script .rb
</Directory>[root@www ~]# systemctl restart httpd # 設置SELinux
[root@www ~]# chcon -R -t httpd_sys_script_exec_t /var/www/html/cgi-enabled
[root@www ~]# semanage fcontext -a -t httpd_sys_script_exec_t /var/www/html/cgi-enabled[root@www ~]# vim /var/www/html/cgi-enabled/index.rb
#!/usr/bin/ruby
print "Content-type: text/html\n\n"
print "<html>\n<body>\n"
print "<div style=\"width: 100%; font-size: 40px; font-weight: bold; text-align: laomaer;\">\n"
print "Ruby Script Test Page"
print "\n</div>\n"
print "</body>\n</html>\n" [root@www ~]# chmod 705 /var/www/html/cgi-enabled/index.rb # 測試
[root@client ~]# curl http://www.laoma.cloud/cgi-enabled/index.py
配置認證
配置基本認證
#目錄示例/var/www/html/auth-basic
# create new
[root@www ~]# vim /etc/httpd/conf.d/auth_basic.conf
<Directory /var/www/html/auth-basic>AuthType BasicAuthName "Basic Authentication"AuthUserFile /etc/httpd/conf/.htpasswdrequire valid-user
</Directory># add a user : create a new file with "-c" ( add the "-c" option only for the initial registration )
[root@www ~]# htpasswd -c /etc/httpd/conf/.htpasswd laoma
New password:redhat # set password
Re-type new password:redhat # confirm
Adding password for user laoma[root@www ~]# mkdir /var/www/html/auth-basic# create a test page
[root@www ~]# vim /var/www/html/auth-basic/index.html
<html>
<body>
<div style="width: 100%; font-size: 40px; font-weight: bold; text-align: laomaer;">
Test Page for Basic Auth
</div>
</body>
</html>[root@www ~]# systemctl restart httpd# 測試
[root@client ~]# curl http://www.laoma.cloud/auth-basic
配置操作系統賬戶認證
提前配置好https
#目錄示例/var/www/html/auth-pam# install from EPEL
[root@www ~]# yum --enablerepo=epel -y install mod_authnz_external pwauth # add to the end
[root@www ~]# vim /etc/httpd/conf.d/authnz_external.conf
<Directory /var/www/html/auth-pam>SSLRequireSSLAuthType BasicAuthName "PAM Authentication"AuthBasicProvider externalAuthExternal pwauthrequire valid-user
</Directory>[root@www ~]# mkdir /var/www/html/auth-pam# create a test page
[root@www ~]# vim /var/www/html/auth-pam/index.html
<html>
<body>
<div style="width: 100%; font-size: 40px; font-weight: bold; text-align: laomaer;">
Test Page for PAM Auth
</div>
</body>
</html>[root@www ~]# systemctl restart httpd # 測試
[root@client ~]# curl http://www.laoma.cloud/auth-pam/
配置LDAP認證
提前準備好 LDAP 服務器和配置好https
# install from EPEL
[root@www ~]# yum --enablerepo=epel -y install mod_authnz_external pwauth
[root@www ~]# yum -y install mod_ldap[root@www ~]# vim /etc/httpd/conf.d/auth_ldap.conf
# add follows to the end
<Directory /var/www/html/auth-ldap>SSLRequireSSLAuthName "LDAP Authentication"AuthType BasicAuthBasicProvider ldapAuthLDAPURL ldap://www.laoma.cloud/dc=srv,dc=world?uid?sub?(objectClass=*)Require ldap-filter objectClass=posixAccount
</Directory># create a test page
[root@www ~]# mkdir /var/www/html/auth-ldap
[root@www ~]# vim /var/www/html/auth-ldap/index.html
<html>
<body>
<div style="width: 100%; font-size: 40px; font-weight: bold; text-align: laomaer;">
Test Page for LDAP Auth
</div>
</body>
</html>[root@www ~]# systemctl restart httpd# 測試
[root@client ~]# curl http://www.laoma.cloud/auth-ldap
Nginx
Nginx是一款高性能的HTTP和反向代理服務器,能夠選擇高效的epoll、kqueue、eventport最為網絡I/O模型,在高連接并發的情況下,能夠支持高達5萬個并發連接數的響應,而內存、CPU等系統資源消耗卻非常低,運行非常穩定。
安裝 nginx
# 安裝 nginx
[root@server 15:20:05]# yum -y install nginx# 啟動 nginx
[root@server 15:20:37]# systemctl enable nginx --now# 準備主頁
[root@server 15:20:42]# mv /usr/share/nginx/html/index.html{,.ori}
[root@server 15:20:51]# echo Hello World From Nginx > /usr/share/nginx/html/index.html# 防火墻
[root@server 15:21:11]# firewall-cmd --add-service=http --permanent
success
[root@server 15:21:13]# firewall-cmd --reload
success[root@client ~ 17:10:45]# curl http://www.zzhpersonal.com
# windows客戶端修改C:\Windows\System32\drivers\etc\hosts
# Linux或Unix修改 /etc/hosts
# 添加如下記錄
10.1.8.10 www.zzhpersonal.com
啟用 UserDir
# 配置 nginx
[root@server ~ 15:54:18]# vim /etc/nginx/nginx.conf
# add into [server] section
server {location ~ ^/~(.+?)(/.*)?$ {alias /home/$1/public_html$2;index index.html index.htm;}
}
[root@server ~ 15:55:21]# systemctl restart nginx# If SELinux is enabled, change boolean setting.
[root@server ~ 16:05:11]# setsebool -P httpd_enable_homedirs on# Create a test page with a common user to make sure it works normally.
[root@server ~ 16:05:23]# chmod 711 /home/zzh
[root@server ~ 16:05:35]# mkdir ~/public_html
[root@server ~ 16:05:41]# chmod 755 ~/public_html
[root@server ~ 16:05:46]# vim ~/public_html/index.html
<html>
<body>
<div style="width: 100%; font-size: 40px; font-weight: bold; text-align: zzher;">
Nginx UserDir Test Page
</div>
</body>
</html># 測試
[root@server ~ 16:07:35]# curl http://www.zzhpersonal.com/~zzhpersonal/
虛擬主機
同一個web服務器提供多個站點。
根據名稱
[root@server ~ 16:11:44]# vim /etc/nginx/conf.d/vhost-name.conf
server {server_name web1.zzhpersonal.com;root /usr/share/nginx/web1;
}
server {server_name web2.zzhpersonal.com;root /usr/share/nginx/web2;
}
根據 port
[root@server ~ 16:12:33]# vim /etc/nginx/conf.d/vhost-port.conf
server {listen 8081;server_name www.zzhpersonal.com;root /usr/share/nginx/8081;
}
server {listen 8082;server_name www.zzhpersonal.com;root /usr/share/nginx/8082;
}
配置SSL/TLS
生成證書
#--1--生成私鑰
[root@server ~ 16:13:12]# openssl genrsa -out www.key 2048#--2--生成請求文件csr
[root@www ~]# openssl req -new -key www.key -out www.csr -subj "/C=CN/ST=JS/L=NJ/O=LM/OU=DEVOPS/CN=www.laoma.cloud/emailAddress=laoma@laoma.cloud"
#CN的值必須是網站域名 #--3--使用自己的私鑰對請求文件簽名,以生成證書
[root@www ~]# openssl x509 -req -days 3650 -in www.csr -signkey www.key -out www.crt
配置站點
[root@server ~ 16:14:58]# mkdir /etc/ssl/certs/www.zzhpersonal.com
[root@server ~ 16:15:12]# mv www* /etc/ssl/certs/www.zzhpersonal.com
[root@server ~ 16:15:23]# vim /etc/nginx/conf.d/ssl.conf
server {listen 443 ssl http2 default_server;listen [::]:443 ssl http2 default_server;server_name www.laoma.cloud;root /usr/share/nginx/html;# 證書ssl_certificate "/etc/ssl/certs/www.laoma.cloud/www.crt";# 私鑰ssl_certificate_key "/etc/ssl/certs/www.laoma.cloud/www.key";
}[root@server ~ 16:16:39]# systemctl restart nginx# 配置HTTP重定向到https.
[root@server ~ 17:15:35]# vim /etc/nginx/nginx.confserver {listen 80 default_server;listen [::]:80 default_server;server_name www.laoma.cloud;root /usr/share/nginx/html;# 添加 重定向return 301 https://$host$request_uri;}
[root@server ~ 17:15:49]# systemctl restart nginx# 防火墻設置
[root@server ~ 17:16:34]# firewall-cmd --add-service=https --permanent
success
[root@server ~ 17:16:41]# firewall-cmd --reload
success# 測試
[root@server ~ 17:16:46]# curl http://www.zzhpersonal.com/
[root@server ~ 17:16:59]# curl -k https://www.zzhpersonal.com/
配置基本認證
用戶名和密碼使用plain text發送,所以最好配置SSL/TLS。
#安裝工具
[root@server ~ 17:17:22]# yum -y install httpd-tools
[root@server ~ 17:18:16]# vim /etc/nginx/conf.d/ssl.conf
# add into the [server] section
server {.....location /auth-basic/ {auth_basic "Basic Auth";auth_basic_user_file "/etc/nginx/.htpasswd";}
}[root@server ~ 17:18:49]# systemctl restart nginx# add user for Basic authentication
[root@server ~ 17:19:10]# htpasswd -c /etc/nginx/.htpasswd zzh
New password:
Re-type new password:
Adding password for user zzh# create a test page
[root@server ~ 17:19:10]# mkdir /usr/share/nginx/html/auth-basic
[root@server ~ 17:19:46]# vim /usr/share/nginx/html/auth-basic/index.html
<html>
<body>
<div style="width: 100%; font-size: 40px; font-weight: bold; text-align: zzher;">
Test Page for Basic Authentication
</div>
</body>
</html># 測試
[root@client ~ 17:22:19]# curl http://www.zzhpersonal.com/auth-basic/
支持動態腳本
使用 PHP
# 安裝PHP和php-fpm,建議把其他的擴展包一起安裝
[root@www ~]# yum install -y php php-fpm# 建議把其他的擴展包一起安裝
[root@www ~]# yum install -y php-gd php-common php-pear php-mbstring php-mcrypt# 查看 php 版本
[root@www ~]# php -v# 測試 php 是否正常
[root@www ~]# echo "<?php echo 'PHP Test Page'.\"\n\"; ?>" > php_test.php
[root@www ~]# php php_test.php
PHP Test Page# 準備測試頁,使用phpinfo查看詳細信息
[root@www ~]# echo "<?php phpinfo(); ?>" > /usr/share/nginx/html/info.php # 測試
[root@client ~]# curl http://www.laoma.cloud/info.php
使用 FastCGI
# install from EPEL
[root@www ~]# yum install -y fcgiwrap
[root@www ~]# vim /etc/nginx/fcgiwrap.conf
# for example, enable CGI under [/cgi-bin]
location /cgi-bin/ {gzip off;root /usr/share/nginx;fastcgi_pass unix:/var/run/fcgiwrap.socket;include /etc/nginx/fastcgi_params;fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}[root@www ~]# mkdir -m 755 /usr/share/nginx/cgi-bin
[root@www ~]# vim /etc/nginx/conf.d/ssl.conf
# add settings into [server] section of a site definitionserver {.....include fcgiwrap.conf;
}[root@www ~]# systemctl restart nginx
# Create Systemd file for FastCGI Wrap service and Start them.
[root@www ~]# vim /usr/lib/systemd/system/fcgiwrap.service
[Unit]
Description=Simple CGI Server
After=nss-user-lookup.target
Requires=fcgiwrap.socket[Service]
EnvironmentFile=/etc/sysconfig/fcgiwrap
ExecStart=/usr/sbin/fcgiwrap ${DAEMON_OPTS} -c ${DAEMON_PROCS}
User=nginx
Group=nginx[Install]
Also=fcgiwrap.socket
[root@www ~]# vim /usr/lib/systemd/system/fcgiwrap.socket
[Unit]
Description=fcgiwrap Socket[Socket]
ListenStream=/run/fcgiwrap.socket[Install]
WantedBy=sockets.target
[root@www ~]# systemctl enable --now fcgiwrap# If SELinux is enabled, change policy.
[root@www ~]# vim nginx-www.te
module nginx-server 1.0;require {type httpd_t;type var_run_t;class sock_file write;
}#============= httpd_t ==============
allow httpd_t var_run_t:sock_file write;[root@www ~]# checkmodule -m -M -o nginx-server.mod nginx-server.techeckmodule: loading policy configuration from nginx-server.te
checkmodule: policy configuration loaded
checkmodule: writing binary representation (version 19) to nginx-server.mod
[root@www ~]# semodule_package --outfile nginx-server.pp --module nginx-server.mod[root@www ~]# semodule -i nginx-server.pp
測試
# 準備測試文件
# Create a test scripts with a language (example below is Python3) under the directory you set CGI executable ([/usr/share/nginx/cgi-bin] on this example) and Access to it to verify CGI works normally.
[root@www ~]# vim /usr/share/nginx/cgi-bin/index.cgi
#!/usr/bin/python3
print("Content-type: text/html\n")
print("<html>\n<body>")
print("<div style=\"width: 100%; font-size: 40px; font-weight: bold; text-align: laomaer;\">")
print("CGI Script Test Page")
print("</div>")
print("</body>\n</html>")[root@www ~]# chmod 755 /usr/share/nginx/cgi-bin/index.cgi # 測試
[root@client ~]# curl http://www.laoma.cloud/cgi-bin/index.cgi
部署反向代理
客戶端訪問代理服務器,代理服務器會將客戶端請求發送給真實服務器。
反向代理實現了隱藏內部服務器。
角色說明
-
代理服務器 proxy 10.1.8.20
-
真實服務器 server 10.1.8.10
代理服務器配置
# 配置解析
[root@proxy ~]# echo '10.1.8.10 www.laoma.cloud' >> /etc/hosts# 安裝 nginx
[root@proxy ~]# yum -y install nginx# 啟動 nginx
[root@proxy ~]# systemctl enable --now nginx# 防火墻
[root@proxy ~]# firewall-cmd --add-service=http --permanent
[root@proxy ~]# firewall-cmd --reload# 配置代理,server部分更改如下
[root@proxy ~]# vim /etc/nginx/nginx.conf
# change [server] section like followsserver {listen 80 default_server;listen [::]:80 default_server;server_name _;root /usr/share/nginx/html;#添加如下內容proxy_redirect off;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;proxy_set_header Host $http_host;......#新增 location 規則location /proxy/ {proxy_pass http://www.laoma.cloud/;}}
[root@proxy ~]# systemctl restart nginx# If SELnux is enabled, change boolean setting.
[root@proxy ~]# setsebool -P httpd_can_network_connect on
真實服務器配置
# 安裝nginx
[root@www ~]# yum -y install nginx# 啟動nginx
[root@www ~]# systemctl enable --now nginx# 防火墻
[root@www ~]# firewall-cmd --add-service=http --permanent
[root@www ~]# firewall-cmd --reload# 準備測試頁
[root@www ~]# echo hello laoma > /usr/share/nginx/html/test.html# 測試效果
[root@client ~]# curl http://www.laoma.cloud/test.html