王芳的技术写作 —— 文档与分享

SSH 免密登录与 config 文件技巧

手里机器一多,每天 ssh 上去输密码能输到怀疑人生。这篇记录从密码登录切换到密钥登录的全过程,以及 ~/.ssh/config 这个被低估的神器。

第一步:生成密钥对

在本机(你的笔记本)执行:

ssh-keygen -t ed25519 -C "my-laptop"
# 一路回车,私钥存 ~/.ssh/id_ed25519,公钥存 ~/.ssh/id_ed25519.pub

用 ed25519,不用 rsa。短、安全、速度快,是现在的主流选择。passphrase 可以设也可以不设——设了更安全,但每次要用 ssh-agent;不设方便,适合可信的个人电脑。

第二步:把公钥传到服务器

ssh-copy-id -i ~/.ssh/id_ed25519.pub user@server_ip
# 输入一次密码,之后就不用了

这条命令干的事很简单:把你的公钥追加到服务器的 ~/.ssh/authorized_keys。如果服务器比较老没有 ssh-copy-id,手动复制粘贴也行,注意文件权限:

chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys

权限不对 sshd 会直接拒绝密钥登录,这是最常见的坑,没有之一。

第三步(关键):写 config 文件

密钥配好了,但每次还要敲 ssh -i ~/.ssh/id_ed25519 -p 2222 user@192.168.1.100,依然麻烦。~/.ssh/config 登场:

Host web1
    HostName 192.168.1.100
    User deploy
    Port 2222
    IdentityFile ~/.ssh/id_ed25519

Host db1
    HostName 192.168.1.101
    User root
    IdentityFile ~/.ssh/id_ed25519

Host *.internal
    User admin
    IdentityFile ~/.ssh/id_ed25519
    ServerAliveInterval 60

之后就是 ssh web1 回车直达。Host *.internal 这种通配写法适合一批命名规律的机器。ServerAliveInterval 防止长时间不动被网关掐掉。

几个实用技巧

注意:关密码登录之前,务必先开一个新终端测试密钥能登录!别把自己锁在门外,我吃过这个亏。

总结

三步:ssh-keygen 生成 → ssh-copy-id 分发 → ~/.ssh/config 起别名。配完之后管理十几台机器和串门一样轻松。密钥文件自己备份好,丢了就得一台台重置。

← 返回首页