Select Page

Linux 修改默认SSH端口22 更换密钥登录

Linux 修改默认SSH端口22 更换密钥登录
因为是默认的端口,所以很容易成为扫描的目标,容易被试探。于是修改默认的端口22就很有必要,减少被攻击的可能。利用公钥和私钥实现SSH无密码登录也能有效提高系统的安全性。
修改默认SSH端口22
添加SSH端口
vim /etc/ssh/sshd_config
在默认的SSH端口22下面添加新的端口,比如:
Port 22

Port 23456

重启SSH

/etc/init.d/ssh restart
# 或者 /etc/init.d/sshd restart
# CentOS7 则用 systemctl restart sshd.service

配置防火墙
#如果是用iptables的话 iptables -I INPUT -p tcp --dport 23456 -j ACCEPT

#如果是用firewalld的话 firewall-cmd --zone=public --add-port=23456/tcp --permanent

保存规则、重启防火墙
#如果是用iptables的话 service iptables save

systemctl restart iptables.service

#如果是用firewalld的话 firewall-cmd --reload

systemctl restart firewalld.service

配置防火墙开机启动 CentOS:

service iptables save
chkconfig --level 2345 iptables on

以后需要保存防火墙规则只需要执行:

service iptables save

Debian/Ubuntu 系统:

iptables-save > /etc/iptables.up.rules
echo -e '#!/bin/bash\n/sbin/iptables-restore < /etc/iptables.up.rules' > /etc/network/if-pre-up.d/iptables
chmod +x /etc/network/if-pre-up.d/iptables

以后需要保存防火墙规则只需要执行:

iptables-save > /etc/iptables.up.rules

测试新的端口能否成功登录SSH后,再删除默认的SSH端口22
vim /etc/ssh/sshd_config
重启SSH

/etc/init.d/ssh restart
# 或者 /etc/init.d/sshd restart
# CentOS7 则用 systemctl restart sshd.service

配置SSH无密码密钥登录
用root用户登录
ssh-keygen -t rsa
#输入密码短语 可直接回车留空
Enter passphrase (empty for no passphrase):
在/root/.ssh/目录下生成了2个文件,id_rsa为私钥,id_rsa.pub为公钥,妥善保存。
Enter passphrase (empty for no passphrase):
导入公钥
cat /root/.ssh/id_rsa.pub >> /root/.ssh/authorized_keys
配置SSH
vim /etc/ssh/sshd_config
打开配置文件,找到下面几个参数
#RSAAuthentication yes
#PubkeyAuthentication yes
#AuthorizedKeysFile .ssh/authorized_keys
删除 # 后保存,重启SSH
service sshd restart

#或者 service ssh restart

将VPS上的/root/.ssh/id_rsa下载到本地,利用PUTTYGEN转换为Open SSH Key

配置Xshell或者Putty这里就不再赘述。

关闭密码登陆方式
vim /etc/ssh/sshd_config
找到PasswordAuthentication参数并修改为no,如果没有就新建
PasswordAuthentication no
重启SSH

/etc/init.d/ssh restart
# 或者 /etc/init.d/sshd restart
# CentOS7 则用 systemctl restart sshd.service

参考链接

About The Author

Jackie Sung

Jackie Sung, also known by his nick-name KK, always strives for the best and learn from the best. Influenced by the age of Internet, for the last few years, in his spare time, he's been working and living as a Freelance Web Engineer/ Web Developer & Designer/ Amateur Photographer/ Husky Lover. The work he provides is of highest quality, fully-customized responsive, and tested in a wide range of devices, which typically covers both front-end (HTML5/ CSS3/ JavaScript) and back-end (WordPress as the CMS) responsibilities.

Leave a reply

电子邮件地址不会被公开。 必填项已用*标注

9 − 6 =

Pin It on Pinterest

Share This