From b23bd2d5ec4798eeae8095d53c78e112ba5df7ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BC=A0=E8=82=B2=E6=96=B0?= Date: Sat, 22 Aug 2026 18:17:13 +0800 Subject: [PATCH] =?UTF-8?q?docs(note):=20=E6=96=B0=E5=A2=9E=20SSH=20?= =?UTF-8?q?=E5=AF=86=E9=92=A5=E7=99=BB=E5=BD=95=E9=85=8D=E7=BD=AE=E7=AC=94?= =?UTF-8?q?=E8=AE=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- note/随手记/ssh密钥登录.md | 82 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 note/随手记/ssh密钥登录.md diff --git a/note/随手记/ssh密钥登录.md b/note/随手记/ssh密钥登录.md new file mode 100644 index 0000000..4706572 --- /dev/null +++ b/note/随手记/ssh密钥登录.md @@ -0,0 +1,82 @@ + + + + +> 私钥永不出生(生成)于服务器,且永不离开客户端 + + + +### 客户端生成密钥对 + +```bash +ssh-keygen -t ed25519 -C "mail" +``` + +- `-t`:指定密钥算法。`ed25519` 在同等安全强度下密钥更短、性能更好、是当前最佳实践;`RSA 4096` 依然安全,且兼容性更广,如果是很老的系统(OpenSSH < 6.5),可能需要`RSA` +- `-C`:添加注释,不影响加密、解密或登录认证的安全性,纯粹是一个给人看的备注字段 + +使用上述命令会生成一对密钥,通常位于`~/.ssh`目录下:公钥是`id_ed25519.pub`,私钥是`id_ed25519`。 + +### 上传公钥到目标服务器 + +方式1 + +```bash +ssh-copy-id -i ~/.ssh/id_ed25519.pub root@服务器IP +``` + +方式2 + +```bash +cd ~/.ssh +echo "公钥内容" >> ~/.ssh/authorized_keys +chmod 600 ~/.ssh/authorized_keys +chmod 700 ~/.ssh +``` + +> 手动 echo 是通用方法,但更推荐 `ssh-copy-id`,它会自动处理目录创建、权限设置和追加 + +### 测试密钥登录 + +```bash +ssh root@服务器IP +``` + +- 如果直接登录成功,没有询问密码,说明密钥配置完全正确,继续下一步。 +- 如果仍然要求输密码,需要检查上一步的公钥是否粘贴完整,或 `authorized_keys` 权限是否为 `600`。 + +### 修改`sshd_config` + +修改服务器的`/etc/ssh/sshd_config`文件,将下方这些行取消注释或者添加: + +``` +PubkeyAuthentication yes # 开启密钥认证 +PasswordAuthentication no # 关闭密码认证 +PermitRootLogin prohibit-password # root账户禁用密码登录 +``` + +保存退出后,使用`sshd -t`检查配置文件语法是否正确 + +重启SSH服务 + +> SSH服务名因发行版而异: +> +> `Debian`/`Ubuntu`使用`systemctl restart ssh` +> +> ``RHEL`/`CentOS`/`Fedora` 上使用`systemctl restart sshd` + +### 最终验证 + +1. 使用SSH发起连接后没有输入密码的提示,能直接连接服务器 + + ```bash + ssh root@服务器IP + ``` + +2. 临时删除私钥后再次登录会报错,大概如下 + + ``` + root@服务器IP: Permission denied (publickey,gssapi-keyex,gssapi-with-mic). + + +