插件窝 干货文章 Centos7 SSH如何用密钥登陆及密码密钥双重验证

Centos7 SSH如何用密钥登陆及密码密钥双重验证

密钥 SSH bash 配置 474    来源:    2025-05-11

CentOS 7 SSH 密钥登录及密码密钥双重验证配置指南

一、配置SSH密钥登录

1. 生成密钥对(在客户端操作)

ssh-keygen -t rsa -b 4096
  • 默认会在~/.ssh/目录下生成id_rsa(私钥)和id_rsa.pub(公钥)
  • 可以设置密钥密码增加安全性(可选)

2. 将公钥上传到服务器

ssh-copy-id -i ~/.ssh/id_rsa.pub username@server_ip

或者手动操作:

cat ~/.ssh/id_rsa.pub | ssh username@server_ip "mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"

3. 服务器端配置(CentOS 7)

编辑SSH配置文件:

sudo vi /etc/ssh/sshd_config

确保以下设置:

PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
PasswordAuthentication no  # 先保持yes,测试密钥登录成功后再改为no

重启SSH服务:

sudo systemctl restart sshd

4. 测试密钥登录

ssh -i ~/.ssh/id_rsa username@server_ip

二、配置密码+密钥双重验证

1. 修改SSH配置文件

sudo vi /etc/ssh/sshd_config

设置以下参数:

PasswordAuthentication yes
AuthenticationMethods publickey,password

2. 可选:使用PAM模块进行更严格的双因素认证

安装Google Authenticator:

sudo yum install google-authenticator -y

为当前用户生成验证码:

google-authenticator

按照提示操作,保存生成的应急代码

修改PAM配置:

sudo vi /etc/pam.d/sshd

添加:

auth required pam_google_authenticator.so

修改sshd_config:

ChallengeResponseAuthentication yes
UsePAM yes
AuthenticationMethods publickey,keyboard-interactive

3. 重启SSH服务

sudo systemctl restart sshd

三、安全加固建议

  1. 修改默认SSH端口:
Port 2222  # 或其他非22端口
  1. 限制root登录:
PermitRootLogin no
  1. 使用fail2ban防止暴力破解:
sudo yum install epel-release -y
sudo yum install fail2ban -y
sudo systemctl enable fail2ban
sudo systemctl start fail2ban
  1. 设置防火墙规则:
sudo firewall-cmd --permanent --add-port=22/tcp  # 或你设置的SSH端口
sudo firewall-cmd --reload

四、测试与验证

  1. 测试密钥+密码双重认证:
ssh -p 22 username@server_ip

系统应要求先验证密钥,然后输入密码

  1. 测试仅密码登录(应失败):
ssh -o PreferredAuthentications=password -o PubkeyAuthentication=no username@server_ip
  1. 测试仅密钥登录(在未启用双重认证时):
ssh -o PreferredAuthentications=publickey -o PasswordAuthentication=no username@server_ip

注意事项

  1. 在禁用密码认证前,确保密钥登录已测试成功
  2. 始终保持至少一个活动的SSH连接,直到确认新配置可用
  3. 备份原始sshd_config文件以便恢复
  4. 对于生产环境,建议先在测试服务器上验证配置