1. 程式人生 > >Ubuntu伺服器安裝配置Mysql

Ubuntu伺服器安裝配置Mysql

在搞定VPS環境後,我在VPS上安裝了mysql,並開啟了遠端控制及許可權控制,本文簡單介紹一下安裝及配置的方法。

1. mysql安裝

使用apt安裝即可,命令操作如下:

sudo apt-get update
sudo apt-get install mysql-server

安裝過程中有可能會提示輸入密碼,可以輸入空或者輸入目標密碼,密碼可以改的,比如安裝成功後,root使用者登陸mysql,修改root使用者密碼,如下:

update mysql.user set authentication_string=password('new password') where user='root' and Host ='localhost';
flush privileges;

或者使用mysqladmin修改密碼,如下:

mysqladmin -u root -p password
Enter password: 
New password: 
Confirm new password: 
Warning: Since password will be sent to server in plain text, use ssl connection to ensure password safety.

如上步驟就可以將mysql root使用者密碼修改

2. mysql密碼重置

以上都是修改mysql使用者密碼的方式,前提是你事先知道使用者密碼。但如果root使用者密碼也忘記了,就不能通過上述方式修改了,可以選擇重置密碼。介紹修改密碼之前,先介紹一個檔案/etc/mysql/debian.cnf其主要內容如下圖:

 裡面有一個debian-sys-maint使用者,這個使用者只有Debian或Ubuntu伺服器才有,所以如果伺服器是Debain或Ubuntu,debian-sys-maint是個Mysql安裝之後自帶的使用者,具體作用是重啟及執行mysql服務。所以如果忘了root密碼,可以通過這個使用者來重設密碼。下面介紹具體操作:

#1. 檢視debian使用者使用者名稱及密碼
vi /etc/mysql/debian.cnf
#2. 使用debian-sys-maint使用者登陸mysql
mysql -u debian-sys-maint -p *****
#3. 修改相應使用者密碼(比如設定root使用者密碼123456)
use mysql
update mysql.user set authentication_string=password('123456') where user='root'
#4. quit退出mysql,並重啟mysql服務
service mysql restart

3. 建立遠端使用者並授權

使用root使用者登陸mysql,並檢視現有使用者:

select Host,User,authentication_string from mysql.user;

User表示使用者名稱,Host表示允許使用者登陸的ip地址,authentication_string為加密後的密碼。現在我們建立一個任何ip都可以登陸的使用者test,如下:

create user test identified by '123456';

可以看到test使用者已經建立完成了,允許所有ip登陸。接著對test使用者進行授權,如下:

grant all privileges on *.* to 'test'@'%'identified by '123456' with grant option;
flush privileges ;

all代表接受所有操作,比如 select,insert,delete….; *.* 代表所有庫下面的所有表;% 代表這個使用者允許從任何地方登入;為了安全期間,這個%可以替換為你允許的ip地址。如上zhuoli使用者就有兩個ip可以訪問,可以通過兩次上述grant命令授權兩個ip登陸。

最後為了可以遠端登陸,還要做一步重要設定,取消mysql本地ip繫結,首先要確定mysql配置檔案位置,一般都是在/etc/mysql目錄,目錄中有個檔案mysql.cnf,有的mysql版本直接將配置寫在這個檔案中,也有的mysql版本在這個檔案中只是記錄mysql配置檔案的地址,我們的目標是找到最終的配置檔案。比如我的mysql版本/etc/mysql/mysql.cnf檔案如下:

最終確定我的配置檔案路徑為/etc/mysql/mysql.conf.d/mysqld.cnf,開啟檔案,bind-address修改為0.0.0.0,如下:

#1. 將bind-address修改為0.0.0.0
bind-address  = 0.0.0.0
#2. 退出vim,重啟mysql服務
service mysql restart

4. 刪除使用者

delete from mysql.user where User='test' and Host='%';