在 Ubuntu 上配置 SSH 密钥(用于免密登录远程服务器)一般分为本地生成密钥和把公钥放到服务器两步。下面是最常用的做法:
ssh-keygen -t rsa -b 4096
或(更推荐,现代系统):
ssh-keygen -t ed25519
Enter file in which to save the key (/home/用户名/.ssh/id_ed25519):
Enter passphrase (empty for no passphrase):
生成后你会看到:
~/.ssh/id_ed25519 # 私钥(不能泄露)
~/.ssh/id_ed25519.pub # 公钥(可发给服务器)
ssh-copy-id 用户名@服务器IP
例如:
ssh-copy-id ubuntu@192.168.1.100
输入一次服务器密码后,以后就可以免密登录。
如果没法用 ssh-copy-id:
cat ~/.ssh/id_ed25519.pub
~/.ssh/authorized_keys
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
ssh 用户名@服务器IP
如果不再提示输入密码,说明配置成功 ✅
本地也要保证权限正确:
chmod 700 ~/.ssh
chmod 600 ~/.ssh/id_ed25519
编辑服务器上的:
sudo vim /etc/ssh/sshd_config
确保有:
PubkeyAuthentication yes
然后重启:
sudo systemctl restart ssh
确认密钥可用后,可设置:
PasswordAuthentication no
如果你是想:
可以告诉我具体场景,我可以给你更针对性的配置方式。