linux启动或关闭防火墙,开放端口

版权声明:本文为博主原创文章,欢迎转载,转载请注明作者、原文超链接 https://blog.csdn.net/Lin_xiaofeng/article/details/87629229

本文摘自本人的原创博客从零开始搭建Linux服务器开发运行环境-详细步骤,第六章。

1.查看防火墙

查看防火墙状态:service iptables status
开启防火墙:service iptables start
关闭防火墙:service iptables stop

如果出现报错:Unit iptables.service could not be found.

这是因为CentOS7默认的防火墙不是iptables,而是firewalle。出现此情况可能是iptables防火墙未安装。

如果你只是想开放某个端口的防火墙,那么你有两种选择:1.firewalld 防火墙;2.iptables防火墙。如果你选择第一种,则不用安装iptables。

下面介绍firewalld 防火墙开放端口的方法和iptables的安装方法。

2.firewalld 防火墙开放端口

查看firewalld状态:systemctl status firewalld

开启firewalld:systemctl start firewalld

如果启动报错:Failed to start firewalld.service: Unit is masked.

是因为被锁定了,取消firewalld的锁定:systemctl unmask firewalld,再启动即可。

开放某个端口:firewall-cmd --zone=public --add-port=3306/tcp --permanent

重新载入:firewall-cmd --reload

这样,3306端口都开放啦。

3.安装iptables服务

首先,停止firewalld服务,执行:systemctl stop firewalld
禁用firewalld服务,执行:systemctl mask firewalld
执行:systemctl unmask firewalld
安装iptables服务,执行:yum -y install iptables-services
设置开机启动,执行:

systemctl enable iptables
systemctl stop iptables
systemctl start iptables
systemctl restart iptables
service iptables save

然后就可以启动防火墙啦!

4.iptables防火墙开放端口

先停掉防火墙service iptables stop

关闭firewalld:

systemctl stop firewalld  
systemctl mask firewalld

开放3306端口,执行:iptables -A INPUT -p tcp --dport 3306 -j ACCEPT

后面如果还有端口要开放,直接在文件/etc/sysconfig/iptables里照着样子添加一行即可

保存,执行:service iptables save

开启服务,执行:systemctl restart iptables.service

查看防火墙状态:service iptables status

可以看到,防火墙已经在运行了,讲道理此时3306端口也已经开放了。

但是!有可能你跟我一样,mysql客户端还是连不上!,这是因为如果是阿里云的服务器,需要在阿里云的控制台去开放端口。

博主表示在写这篇博客的时候一度怀疑人生,思前想后想不通,最后发现是阿里云在作祟,坑不坑!!!

5.开放阿里云服务器的端口

登陆你的阿里云,进入控制台,找到你的云服务器实例,点击后面的更多,选择【网络和安全组】下的【安全组配置】

点进去以后,点击【配置规则】,添加一个新的或者克隆一个规则

协议类型要选Mysql(3306),然后保存

这样就生效啦,赶快使用你的mysql客户端连接一下(注意防火墙要保证3306端口开放)

如果你此时连接还是报错:

这个报错1130,说明你所连接的用户账户没有远程连接的权限,只能在本机localhost登录,。需要更改 mysql 数据库里的 user表里的 host字段 把localhost改成%,下面介绍方法:

执行mysql -u root -p,输入密码

进入mysql控制台,进入数据库:use mysql;
更改host字段值:update user set host='%' where host='localhost';
刷新:flush pricilges;
查看:select host,user from user;

退出:quit;

此时,你就可以使用mysql客户端连接你的mysql啦,实在不行的话你重启一下mysql试试:service mysql start,或者修改一下root的密码,保证你输入的密码正确。

可以看见已经连接成功。怎么样,6不6!!!
--------------------- 
作者:林晓风 
来源:CSDN 
原文:https://blog.csdn.net/Lin_xiaofeng/article/details/87454717
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自blog.csdn.net/Lin_xiaofeng/article/details/87629229