CentOS SSH密钥认证步骤如下:
生成密钥对
在本地终端执行:
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
(默认生成私钥~/.ssh/id_rsa和公钥~/.ssh/id_rsa.pub,可按需设置密码短语)
上传公钥到服务器
ssh-copy-id命令:ssh-copy-id user@remote_host~/.ssh/authorized_keys)cat ~/.ssh/id_rsa.pub | ssh user@remote_host "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"配置服务器SSH服务
编辑/etc/ssh/sshd_config:
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
PasswordAuthentication no # 可选:禁用密码登录(需确保密钥配置正确)
重启服务:sudo systemctl restart sshd
测试密钥认证
执行ssh user@remote_host,若配置正确可直接登录,无需输入密码
可选优化:
~/.ssh/config中添加:Host remote_host
HostName remote_host_ip
User user
IdentityFile ~/.ssh/id_rsa
之后可直接用ssh remote_host登录。安全提示:
~/.ssh目录权限为700,authorized_keys文件权限为600。