Linux添加或修改ssh端口

1)  查看ssh服务是否安装齐全

  这里使用”rpm –qa|grep ssh”命令查看。

[root@xuexi ~]# rpm -qa | grep ssh
libssh2-1.4.3-10.el7_2.1.x86_64
openssh-7.4p1-16.el7.x86_64
openssh-server-7.4p1-16.el7.x86_64
openssh-clients-7.4p1-16.el7.x86_64

  如果不全请使用yum命令安装,版本无需在意,以本地机器为主。

2)修改ssh的配置文件

  在root用户下使用”vim /etc/ssh/sshd_config”命令(注意这里是sshd_config),找到#Port 22(初始情况)改为Port 22,并添加一行Port 12345。保存并退出。

  接着使用”systemctl restart sshd”命令,重启服务。

3)在防火墙中添加端口

  同样在root用户下使用命令”firewall-cmd --permanent --add-port=12345/tcp”将端口添加到防火墙中。

  接着使用命令”firewall-cmd --reload”重启防火墙。重启好后使用命令”firewall-cmd --list-port”查看端口情况。(如下)

[xf@xuexi ~]$ firewall-cmd --list-ports
12345/tcp 22/tcp

4)SELinux内部操作

  最简单的方法是关闭SELinux。关闭SELinux方法请看https://www.cnblogs.com/diantong/p/9604602.html

  为安全着想而不想关闭SELinux的用户,可以先尝试”semanage -h”命令,如果有显示帮助信息可以跳过这一步,如果不是帮助信息,请安装SELinux管理工具semanage。先安装依赖包”yum install policycoreutils-python”,再安装管理工具”yum provides semanage”。

  安装好后使用”semanage port –l|grep ssh”查看ssh当前端口。

[root@xuexi ~]# semanage port -l | grep ssh
ssh_port_t                     tcp      22

  如果没有我们指定的端口请使用命令”semanage port –a –t ssh_port_t –p tcp 12345”。

[root@xuexi ~]# semanage port -a -t ssh_port_t -p tcp 12345
[root@xuexi ~]# semanage port -l | grep ssh
ssh_port_t                     tcp      12345, 22

         最后重启系统。

注意:在确保sshd_config文件端口、firewall-cmd端口和SELinux端口正确一致的情况下,shhd处于auto-activing(自动激活)但无法打开,那么请关闭SELinux再尝试,很大可能是SELinux配置乱了,我暂时没找到好的解决办法。

5)尝试使用新端口连接

[root@CentOS6 桌面]# ssh root@192.168.128.240 -p 12345
The authenticity of host '[192.168.128.240]:12345 ([192.168.128.240]:12345)' can't be established.
RSA key fingerprint is 23:83:de:25:21:72:77:d1:9d:ae:59:4b:d7:a4:e3:17. Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '[192.168.128.240]:12345' (RSA) to the list of known hosts.
reverse mapping checking getaddrinfo for xuexi [192.168.128.240] failed - POSSIBLE BREAK-IN ATTEMPT!
root@192.168.128.240's password: Last failed login:
Tue Oct 30 15:24:03 CST 2018 from centos6 on ssh:notty There was 1 failed login attempt since the last successful login. Last login:
Tue Oct 30 15:06:48 2018
[root@xuexi ~]#

6)如果希望做到修改效果的,将不想要的端口在sshd_config文件、firewall-cmd命令和semanage命令中去除,再尝试连接即可。

原文地址:https://www.cnblogs.com/diantong/p/9877132.html