Mac 配置用户自动使用指定的 SSH 密钥

前置准备:生成 SSH 密钥对
打开终端
使用 Spotlight (⌘+Space) 搜索 “Terminal” 并打开生成密钥对
执行以下命令(替换your_email@example.com
为你的邮箱):1
ssh-keygen -t ed25519 -C "your_email@example.com" -f ~/.ssh/git_example
- 遇到提示时按 Enter 使用默认设置
- 如需增加安全性,可设置密钥密码(passphrase)
查看生成的文件
在~/.ssh
目录会生成两个文件:1
2git_example # 私钥(需妥善保管)
git_example.pub # 公钥(需配置到Git服务端)
配置自动使用指定密钥
编辑 SSH 配置文件
1
2mkdir -p ~/.ssh && chmod 700 ~/.ssh
vim ~/.ssh/config添加配置内容
使用以下模板(按需修改参数):1
2
3
4
5
6
7
8
9
10
11
12
13# 主Git服务配置
Host git.example.com
HostName git.example.com
User git
Port 22
IdentityFile ~/.ssh/git_example
IdentitiesOnly yes
# 附加配置(用于其他Git服务)
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/github_key设置文件权限
1
chmod 600 ~/.ssh/config
服务端配置
- 添加公钥到Git服务
复制公钥内容:将公钥添加到:1
pbcopy < ~/.ssh/git_example.pub
- GitHub: Settings → SSH and GPG keys
- GitLab: Preferences → SSH Keys
- 自建Git服务:服务器
~/.ssh/authorized_keys
文件
验证配置
测试SSH连接
1
ssh -T git@git.example.com
成功时会显示服务商欢迎信息(如GitHub的”Hi username!”)
克隆仓库测试
1
git clone git@git.example.com:username/repo.git
系统将自动使用指定密钥,无需人工干预
故障排查
调试模式
添加-v
参数查看详细连接过程:1
ssh -Tv git@git.example.com
常见问题
- 错误提示
Permissions 0644 are too open
:执行chmod 600 ~/.ssh/*
- 连接超时:检查防火墙设置或网络代理配置
- 认证失败:确认服务端已正确添加公钥
- 错误提示
扩展应用
可通过配置多个Host
区块,实现:
- 不同平台使用不同密钥(GitHub/GitLab/Gitee)
- 工作账号与个人账号分离
- 多服务器环境下的密钥管理
注意:本文示例中的
git.example.com
为演示域名,实际使用时请替换为你的Git服务地址
- Title: Mac 配置用户自动使用指定的 SSH 密钥
- Author: Neurocoda
- Created at : 2025-02-21 10:44:03
- Updated at : 2025-02-21 10:44:03
- Link: https://neurocoda.com/p/40e2a8f8.html
- License: This work is licensed under CC BY-ND 4.0.
Recommend
Comments