SSH 密钥登录比单纯密码登录更适合长期维护 VPS。下面以本地电脑生成密钥、上传公钥、测试登录为例。
生成 SSH 密钥
在本地电脑执行:
ssh-keygen -t ed25519 -C "bwgon-vps"一路回车会生成默认密钥。生成后查看公钥:
cat ~/.ssh/id_ed25519.pub复制输出的整行内容。
写入服务器
先用密码登录 VPS:
ssh root@你的服务器IP在服务器上创建 SSH 目录并写入公钥:
mkdir -p ~/.ssh
chmod 700 ~/.ssh
nano ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys把刚才复制的公钥粘贴进去,保存退出。
测试密钥登录
重新打开一个终端窗口,不要关闭原来的 SSH 会话,然后测试:
ssh root@你的服务器IP如果可以免密码登录,说明密钥已经生效。
可选:关闭密码登录
确认密钥登录稳定后,再考虑关闭密码登录。编辑 SSH 配置:
nano /etc/ssh/sshd_config找到并调整:
PasswordAuthentication no
PubkeyAuthentication yes重启 SSH:
systemctl restart ssh关闭密码登录前一定要保留一个已登录窗口,避免配置错误导致自己进不去服务器。