ssh-keygen -t rsa -b 4096
~/.ssh/
目录下生成id_rsa
(私钥)和id_rsa.pub
(公钥)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"
编辑SSH配置文件:
sudo vi /etc/ssh/sshd_config
确保以下设置:
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
PasswordAuthentication no # 先保持yes,测试密钥登录成功后再改为no
重启SSH服务:
sudo systemctl restart sshd
ssh -i ~/.ssh/id_rsa username@server_ip
sudo vi /etc/ssh/sshd_config
设置以下参数:
PasswordAuthentication yes
AuthenticationMethods publickey,password
安装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
sudo systemctl restart sshd
Port 2222 # 或其他非22端口
PermitRootLogin no
sudo yum install epel-release -y
sudo yum install fail2ban -y
sudo systemctl enable fail2ban
sudo systemctl start fail2ban
sudo firewall-cmd --permanent --add-port=22/tcp # 或你设置的SSH端口
sudo firewall-cmd --reload
ssh -p 22 username@server_ip
系统应要求先验证密钥,然后输入密码
ssh -o PreferredAuthentications=password -o PubkeyAuthentication=no username@server_ip
ssh -o PreferredAuthentications=publickey -o PasswordAuthentication=no username@server_ip