Linux 修改 SSH 连接的端口

1、登录服务器,打开sshd_config文件

[root@centos ~]# vim /etc/ssh/sshd_config

2、找到 #Port 22,默认是注释掉的,先把前面的#号去掉,再插入一行设置成你想要的端口号,注意不要跟现有端口号重复

......

# The strategy used for options in the default sshd_config shipped with
# OpenSSH is to specify options with their default value where
# possible, but leave them commented.  Uncommented options override the
# default value.

Include /etc/ssh/sshd_config.d/*.conf

Port 22
Port 10022
.....

SSH默认监听端口是22,如果你不强制说明别的端口,”Port 22”注不注释都是开放22访问端口。上面我保留了22端口,防止之后因为各种权限和配置问题,导致连22端口都不能访问了,那就尴尬了。等一切都ok了,再关闭22端口。

此处增加了10022端口,大家修改端口时候最好挑10000~65535之间的端口号,10000以下容易被系统或一些特殊软件占用,或是以后新应用准备占用该端口的时候,却被你先占用了,导致软件无法运行。

3、重启SSH服务,最好也重启下服务器

service sshd restart

shutdown -r now  

4、防火墙开通该端口

如果服务器是云服务器,需要配置安全组规则,允许10022端口访问

还不通的话去本机防火墙,开通10022端口的访问

sudo iptables -I INPUT -p tcp --dport 10022 -j ACCEPT

注意要去持久化iptables配置,防止服务器重启导致无法登陆了

5、尝试通过10022端口登录SSH,或者进入该服务器直接本地访问SSH如下:

[root@centos7 ~]# ssh -p 10022 root@localhost 

如果成功,说明10022已经可以使用了,接下来你就可以根据上述步骤把sshd_config的Port 22注释掉就OK了!