在 Ubuntu 上配置 SSH 密钥(公钥 / 私钥) 一般用于 无密码登录服务器 或 Git(GitHub / GitLab)。下面我按最常见场景一步一步说明。
ssh-keygen -t ed25519 -C "your_email@example.com"
✅ 推荐:
ed25519(更安全、更快)
如果你的系统较老,也可以用:
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
Enter file in which to save the key (/home/user/.ssh/id_ed25519):
/home/user/.ssh/github_keyEnter passphrase (empty for no passphrase):
ls ~/.ssh
你会看到类似:
id_ed25519 # 私钥(⚠️ 不能泄露)
id_ed25519.pub # 公钥(可以放到服务器 / Git 网站)
查看公钥内容:
cat ~/.ssh/id_ed25519.pub
ssh-copy-id user@server_ip
示例:
ssh-copy-id root@192.168.1.100
输入一次服务器密码即可
cat ~/.ssh/id_ed25519.pub
ssh user@server_ip
mkdir -p ~/.ssh
nano ~/.ssh/authorized_keys
粘贴公钥内容并保存
设置权限:
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
编辑:
nano ~/.ssh/config
示例配置:
Host myserver
HostName 192.168.1.100
User root
IdentityFile ~/.ssh/id_ed25519
以后直接:
ssh myserver
⚠️ 先确保 SSH 密钥能正常登录
在服务器编辑:
sudo nano /etc/ssh/sshd_config
修改或确认:
PasswordAuthentication no
PubkeyAuthentication yes
重启 SSH:
sudo systemctl restart ssh
cat ~/.ssh/id_ed25519.pub
Settings → SSH and GPG keys → New SSH keyPreferences → SSH Keysssh -T git@github.com
chmod 700 ~/.ssh
chmod 600 ~/.ssh/id_ed25519
authorized_keyssshd_configsudo tail -f /var/log/auth.log
如果你愿意,可以告诉我:
✅ 是 本地 Ubuntu → 服务器
✅ 还是 GitHub / GitLab
✅ 或 Windows + Ubuntu 双系统 / WSL
我可以按你的具体环境提供更精准的配置方案。