参考链接:
使用 SSH 连接到 GitHub https://docs.github.com/cn/github/authenticating-to-github/connecting-to-github-with-ssh
服务器上的 Git - 生成 SSH 公钥 https://git-scm.com/book/zh/v2/服务器上的-Git-生成-SSH-公钥
1. 打开 Git Bash
2. 检查现存的SSH密钥
$ ls -al [your .ssh directory]
e.g.
$ ls -al ~/.ssh
3. 生成新的SSH密钥
How to use ssh-keygen to generate a new SSH key: https://www.ssh.com/ssh/keygen/
- 【2021年10月12日】gitee 暂不支持
RSA-SHA2
https://gitee.com/help/articles/4352
$ ssh-keygen -t rsa -b 4096 -C "[your_email@example.com]"
>Generating public/private rsa key pair.
4. 存储新的SSH密钥
提示Enter file in which to save the key
(输入要保存密钥的文件)”时,输入密钥文件的保存位置。(按Enter,将使用默认的文件位置C:\\Users\\you\\.ssh/id_rsa
)
- 文件的保存位置,不是文件夹(我一般新建一个文件之后覆盖)
5. 输入SSH密钥密码
提示Enter passphrase
时,输入SSH密钥密码。
6. 将SSH密钥添加到ssh-agent
# 启动ssh-agent
$ eval $(ssh-agent -s)
> Agent pid (number)
# 添加SSH私钥到 ssh-agent
$ ssh-add [path to your private key]
7. 在 git 站点中添加公钥
拷贝密钥.pub
文件到剪切板
clip < .pub 文件地址
将信息粘贴到 git 站点的 ssh 文件列表中。
8. 验证连接
# 验证连接
$ ssh -T git@xxx.com
当出现类似警告
> The authenticity of host 'github.com (IP ADDRESS)' can't be established.
> RSA key fingerprint is 16:27:ac:a5:76:28:2d:36:63:1b:56:4d:eb:df:a6:48.
> Are you sure you want to continue connecting (yes/no)?
或
> The authenticity of host 'github.com (IP ADDRESS)' can't be established.
> RSA key fingerprint is SHA256:nThbg6kXUpJWGl7E1IGOCspRomTxdCARLviKw6E5SY8.
> Are you sure you want to continue connecting (yes/no)?
验证警告消息中的指纹后,输入 yes
> Hi username! You've successfully authenticated, but xxxx does not provide shell access.
9. 在 Git for Windows 上自动启动 ssh-agent
参考:https://docs.github.com/cn/github/authenticating-to-github/working-with-ssh-key-passphrases
设置在打开 bash 或 Git shell 时自动运行 ssh-agent
。拷贝粘贴以下内容到 Git shell 中的 ~/.profile
或 ~/.bashrc
文件中:
~/.profille
会在用户登录时执行~/.bashrc
会在用户启动 bash shell 时执行
env=~/.ssh/agent.env
agent_load_env () { test -f "$env" && . "$env" >| /dev/null ; }
agent_start () {
(umask 077; ssh-agent >| "$env")
. "$env" >| /dev/null ; }
agent_load_env
# agent_run_state: 0=agent running w/ key; 1=agent w/o key; 2= agent not running
agent_run_state=$(ssh-add -l >| /dev/null 2>&1; echo $?)
if [ ! "$SSH_AUTH_SOCK" ] || [ $agent_run_state = 2 ]; then
agent_start
ssh-add
elif [ "$SSH_AUTH_SOCK" ] && [ $agent_run_state = 1 ]; then
ssh-add
fi
unset env
10. Git 多账号管理
新建或修改 ~./ssh/config
#config文件通过host区分不同的托管库
#Default GitHub
Host github
HostName github.com
User your_github_name
IdentityFile ~/.ssh/id_github_rsa
Host gitee
HostName gitee.com
User your_gitee_name
IdentityFile ~/.ssh/id_gitee_rsa
附:添加或更改密码
参考:https://docs.github.com/cn/github/authenticating-to-github/working-with-ssh-key-passphrases
$ ssh-keygen -p
# Start the SSH key creation process
> Enter file in which the key is (/Users/you/.ssh/id_rsa): [Hit enter]
> Key has comment '/Users/you/.ssh/id_rsa'
> Enter new passphrase (empty for no passphrase): [Type new passphrase]
> Enter same passphrase again: [One more time for luck]
> Your identification has been saved with the new passphrase.