Khi cài đặt xong, user root của MySQL chỉ có thể kết nối từ localhost. Muốn cho phép user root thực hiện kết nối từ xa, ta cần thực hiện một số thao tác sau.
Đầu tiên là kiểm tra xem MySQL đang listen trên port nào. Có thể kiểm tra trong cấu hình:
1 2 3 4 5 6 7 |
mysql> SHOW GLOBAL VARIABLES LIKE 'PORT'; +---------------+-------+ | Variable_name | Value | +---------------+-------+ | port | 3306 | +---------------+-------+ 1 row in set (0.01 sec) |
hoặc trên hệ thống
1 2 |
[root@mysql ~]# netstat -tlnp |grep mysql tcp 0 0 :::3306 :::* LISTEN 4244/mysqld |
Mặc định MySQL sẽ lắng nghe kết nối trên port 3306. Để cho phép kết nối từ xa, ta cần tắt firewall
1 2 3 4 |
[root@mysql ~]# service iptables stop iptables: Setting chains to policy ACCEPT: filter [ OK ] iptables: Flushing firewall rules: [ OK ] iptables: Unloading modules: [ OK ] |
hoặc cấu hình mở port 3306 cho phép kết nối
1 2 3 4 5 6 7 8 9 10 11 12 |
[root@mysql ~]# iptables -I INPUT 5 -i eth0 -p tcp -m tcp --dport 3306 -j ACCEPT [root@mysql ~]# service iptables save iptables: Saving firewall rules to /etc/sysconfig/iptables:[ OK ] [root@mysql ~]# service iptables restart iptables: Setting chains to policy ACCEPT: filter [ OK ] iptables: Flushing firewall rules: [ OK ] iptables: Unloading modules: [ OK ] iptables: Applying firewall rules: [ OK ] |
Lưu ý là khi add rule cho port 3306, rule này phải nằm trên rule REJECT khi kiểm tra bằng lệnh iptables status
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
[root@mysql ~]# service iptables status Table: filter Chain INPUT (policy ACCEPT) num target prot opt source destination 1 ACCEPT all -- 0.0.0.0/0 0.0.0.0/0 state RELATED,ESTABLISHED 2 ACCEPT icmp -- 0.0.0.0/0 0.0.0.0/0 3 ACCEPT all -- 0.0.0.0/0 0.0.0.0/0 4 ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:22 5 ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:3306 6 REJECT all -- 0.0.0.0/0 0.0.0.0/0 reject-with icmp-host-prohibited Chain FORWARD (policy ACCEPT) num target prot opt source destination 1 REJECT all -- 0.0.0.0/0 0.0.0.0/0 reject-with icmp-host-prohibited Chain OUTPUT (policy ACCEPT) num target prot opt source destination |
Sau đó, trên server MySQL, ta vào mysql với user root và cấp toàn quyền cho user root từ xa
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
[root@mysql ~]# mysql -u root -p Enter password: mysql_4U ... mysql> select authentication_string from mysql.user where user = 'root'; +-------------------------------------------+ | authentication_string | +-------------------------------------------+ | *BC8510FA20311E952349B21A9F3C0E047507A4B5 | +-------------------------------------------+ 1 row in set (0.01 sec) mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY PASSWORD '*BC8510FA20311E952349B21A9F3C0E047507A4B5' WITH GRANT OPTION; Query OK, 0 rows affected, 2 warnings (0.00 sec) |
Kết quả là ta đã có thể connect vào server MySQL từ xa. Ở đây mình dùng mysql client trên Windows.
Leave a Reply