更新于 2021/12/15

Linux设置ssh并通过ssh密钥登陆

进入 .ssh

# 进入 .ssh 文件夹
cd ~/.ssh

处理旧密钥

# 处理旧的密钥文件
mv id_rsa id_rsa.bak
mv id_rsa.pub id_rsa.pub.bak

创建密钥

# 输入后按3次回车
ssh-keygen -t rsa

公钥写入到文件

# 将公钥写入authorized_keys
cat id_rsa.pub >> authorized_keys

问题

若出现问题无法登陆,则检查日志 /var/log/secure

写入公钥后无法登陆

Authentication refused: bad ownership or modes for file /root/.ssh/authorized_keys

原因:

sshd 为了安全,对属主的目录和文件权限有所要求。如果权限不对,则 ssh 的免密码登陆不生效

用户目录权限为 755 或者 700,就是不能是 77x

.ssh 目录权限一般为 755 或者 700

rsa_id.pub 及 authorized_keys 权限一般为 644

rsa_id 权限必须为 600

# 设置权限(权限错误会无法登陆)
cd ~/.ssh
chmod 644 authorized_keys id_rsa.pub && chmod 600 id_rsa && chmod 700 .