萬盛學電腦網

 萬盛學電腦網 >> 數據庫 >> mysql教程 >> CentOS系統下mysql綁定多個ip地址訪問

CentOS系統下mysql綁定多個ip地址訪問

為了安全起見,我們將centos服務器上的mysql綁定允許訪問的ip,這樣就實現了mysql只允許指定ip訪問,具體實現請看本文。

msyql配置文件my.cnf中有選項bind-address=127.0.0.1,就是說mysql server監聽的是本地發來的請求,如果開放任意主機都可以請求,則寫為0.0.0.0,但是這樣又不太安全。監聽某ip,指定此ip地址即可,但是要保證mysql的user中有允許此ip訪問,否則不能對數據庫操作。那麼是否可以在配置裡只規定幾個ip呢?

簡單直接回答:不可能

請參考:#option_mysqld_bind-address

The MySQL server listens on a single network socket for TCP/IP connections. This socket is bound to a single address, but it is possible for an address to map onto multiple network interfaces. The default address is 0.0.0.0. To specify an address explicitly, use the ?bind-address=addr option at server startup, where addr is an IPv4 address or a host name. If addr is a host name, the server resolves the name to an IPv4 address and binds to that address. The server treats different types of addresses as follows:

If the address is 0.0.0.0, the server accepts TCP/IP connections on all server host IPv4 interfaces.
If the address is a “regular” IPv4 address (such as 127.0.0.1), the server accepts TCP/IP connections only for that particular IPv4 address.

但是有此需求,就會到訪問控制,那麼使用防火牆iptables可實現此效果

mysql-server為192.168.1.3,只允許192.168.1.4,  192.168.1.5,  192.168.1.6來訪問3306端口

在my.cnf中

bind-address = 0.0.0.0

在訪問3306端口的主機中,只允許192.168.1.4-6,其他ip一律DROP掉
/sbin/iptables -A INPUT -p tcp -s 192.168.1.4 --dport 3306 -j ACCEPT /sbin/iptables -A INPUT -p tcp -s 192.168.1.5 --dport 3306 -j ACCEPT /sbin/iptables -A INPUT -p tcp -s 192.168.1.6 --dport 3306 -j ACCEPT /sbin/iptables -A INPUT -p tcp --dport 3306 -j DROP


/sbin/iptables -A INPUT -p tcp --dport 3306 ! -s 192.168.1.4 -j DROP /sbin/iptables -A INPUT -p tcp --dport 3306 ! -s 192.168.1.5 -j DROP /sbin/iptables -A INPUT -p tcp --dport 3306 ! -s 192.168.1.6 -j DROP

保存防火牆規則
service iptables save

查看INPUT鏈包含3306的規則
echo -e "target prot opt source destination\n$(iptables -L INPUT -n | grep 3306)"

這樣就實現了mysql只允許指定ip訪問。

總結

雖然mysql沒有直接綁定多個ip訪問的,但是我們可以通過防火牆iptables可實現,也是一個不錯的辦法。

copyright © 萬盛學電腦網 all rights reserved