跳到主要内容
lanzai.co
返回

SSH 密钥配置与免密登录

用 SSH 密钥代替密码登录,安全且免密。

生成密钥

ssh-keygen -t ed25519 -C "you@example.com"
# 按提示选择保存路径和 passphrase,一路回车使用默认值

生成两个文件:

上传公钥

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

安全建议


分享这篇文章:

上一篇
Linux 服务器常见问题排查
下一篇
Nginx 常用指令与配置速查