用 SSH 密钥代替密码登录,安全且免密。
生成密钥
ssh-keygen -t ed25519 -C "you@example.com"
# 按提示选择保存路径和 passphrase,一路回车使用默认值
生成两个文件:
~/.ssh/id_ed25519—— 私钥,绝不能泄露~/.ssh/id_ed25519.pub—— 公钥,放到服务器
上传公钥
ssh-copy-id user@server # 最方便的方式
手动方式:
cat ~/.ssh/id_ed25519.pub | ssh user@server "mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"
修改服务器配置
/etc/ssh/sshd_config:
PasswordAuthentication no
PubkeyAuthentication yes
sudo systemctl reload sshd
先确保密钥登录可用再关密码登录,否则可能把自己锁在外面。
配置 config 文件
~/.ssh/config 支持别名与多服务器:
Host web1
HostName 123.45.67.89
User ubuntu
IdentityFile ~/.ssh/id_ed25519
Port 22
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_github
之后 ssh web1 即可连接。
免密 git 推送
git remote set-url origin git@github.com:user/repo.git
git push
端口转发
本地转发(把远程服务映射到本地端口):
ssh -L 8080:localhost:8080 user@server
远程转发:
ssh -R 8080:localhost:3000 user@server
安全建议
- 私钥设置 passphrase,或用
ssh-agent记忆 - 服务器上
PermitRootLogin prohibit-password - 定期检查
authorized_keys里的公钥是否都是自己的