CentOS 7 修改SSH端口

增强Linux安全的措施很多,将ssh默认端口22修改成其它端口也是重要的一个方法。这里介绍CentOS7下修改sshd端口以及相关防火墙的设置。

一、新增加sshd监听端口

为了防止把自己关在主机外面,保险起见,首先增加新的端口,让sshd同时监听22及新的端口。

  1. 编辑sshd配置文件:

    vi /etc/ssh/sshd_config
    

    修改内容:

    • #Port 22一行去掉第一个字符注释用的#
    • Port 22一行下面为新端口新增一行:例如Port 1022
  2. 保存ssh配置文件后,执行重启sshd的命令

    systemctl restart sshd
    
  3. 查看服务器监听端口,确认新端口被正常启动。

    netstat -tuplen
    

二、增加新的防火墙服务定义

CentOS7 默认采用的是firewalld防火墙服务,与旧版本的iptables的配置方法有很大不同。

  1. 启动firewalld服务

    systemctl enable firewalld
    
  2. 增加新的自定义firewall服务

    vi /etc/firewalld/services/ssh-alt.xml 
    

    文件内容如下:

    <?xml version="1.0" encoding="utf-8"?>
    <service>
      <short>SSH ALT</short>
      <description>SSH new PORT</description>
      <port protocol="tcp" port="1022"/>
    </service>
    
  3. 加载firewalld服务

    firewall-cmd --permanent --add-service=ssh-alt
    firewall-cmd --reload
    

三、客户端测试新端口的ssh登录

  1. 一定要先确认在ssh客户端或unix终端下能正常登陆新的端口

    ssh -p 1022 root@xxx.xxx.xxx.xxxx
    
  2. 只有确认新端口能正常使用以后,才能关停默认的22端口

四、停用22端口

  1. 修改/etc/ssh/sshd_config文件,将Port 22一行用#注释掉。

  2. 重启sshd服务

    systemctl restart sshd
    
  3. 去掉防火墙中默认ssh端口的设置

    firewall-cmd --permanent --remove-service=ssh
    firewall-cmd --reload
    firewall-cmd --list-all
    
  4. 再次确认服务器监听端口,确认22端口没有被启动

    netstat -tuplen
    
Share Comments
comments powered by Disqus