vi /etc/ssh/sshd_config

在Port 22下方加入你要修改的端口

Port 22
Port 2048

保存 sshd_config 文件后重启 sshd 服务:

systemctl restart sshd

打开 SELinux 端口

yum provides semanage
yum -y install policycoreutils-python

为 ssh 添加新的允许端口

semanage port -a -t ssh_port_t -p tcp 2048

查看当前 SELinux 允许的端口

semanage port -l | grep ssh

输出的结果为 ssh_port_t tcp 2048, 22

配置防火墙 firewalld

systemctl enable firewalld
systemctl start firewalld
systemctl status firewalld

启用防火墙

提示警告:WARNING: AllowZoneDrifting is enabled. This is considered an insecure configuration option. It will be removed in a future release.
解决方法:

修改防火墙配置文件:

vi /etc/firewalld/firewalld.conf

搜索:AllowZoneDrifiting 把对应的值 yes 改为 no

重启防护墙 即可

systemctl restart firewalld

为 public zone 永久开放 2048/TCP 端口

firewall-cmd --permanent --zone=public --add-port=22/tcp
firewall-cmd --permanent --zone=public --add-port=2048/tcp
firewall-cmd --reload

查看已开放端口

firewall-cmd --permanent --list-port

输出的结果为 443/tcp 80/tcp 22/tcp 2048/tcp
到此端口添加工作完毕 可以用新添加的端口连接服务器了

禁用 22 端口

vi /etc/ssh/sshd_config

注释掉Port 22 这一行 用注释符号#

systemctl restart sshd

firewalld防火墙移除 22 端口

firewall-cmd --permanent --zone=public --remove-port=22/tcp
firewall-cmd --reload

至此端口修改工作完毕

允许特定IP访问服务器特定端口

允许192.168.142.166访问5432端口

firewall-cmd --permanent --add-rich-rule="rule family="ipv4" source address="192.168.142.166" port protocol="tcp" port="5432" accept"

允许192.168.142.166访问6379端口

firewall-cmd --permanent --add-rich-rule="rule family="ipv4" source address="192.168.142.166" port protocol="tcp" port="6379" accept"

重启防火墙,使配置生效

systemctl restart firewalld.service

查看配置结果,验证配置

firewall-cmd --list-all

删除规则

firewall-cmd --permanent --remove-rich-rule="rule family="ipv4" source address="192.168.142.166" port protocol="tcp" port="11300" accept"

systemctl restart firewalld.service

参考链接

https://sebastianblade.com/how-to-modify-ssh-port-in-centos7/
https://www.cnblogs.com/moxiaoan/p/5683743.html
http://www.jb51.net/article/135124.htm
https://cloud.tencent.com/developer/article/1404088

标签: Centos

添加新评论