由于国内GitHub时常不稳定,所以选择Gitee来备份自己的代码,下面的配置过程,GitHub同样适用。
1. 生成公钥和私钥
若当前用户~
路径下有.ssh
文件夹,就表明已经生成密钥,可以跳过这个步骤。否则:
ssh-keygen -t rsa -C "comment"
使用rsa
加密方式生成密钥,"comment"
可以写一段注释,最后会放在生成的公钥后面。一般都是写上自己有邮箱或者用户名,其他内容也可以。
2. 将公钥添加到Gitee中
cat ~/.ssh/id_rsa.pub
会得到公钥,将公钥添加到Gitee的配置[https://gitee.com/profile/sshkeys]中就配置好了。
3. 测试是否配置成功
在终端中输入 ssh -T git@gitee.com
: 出现下列提示,说明配置成功!
Hi username! You've successfully authenticated, but GITEE.COM does not provide shell access.
第一次配置,会提示添加认真,选择yes就行。
已经配置好SSH密钥,依然报错权限不允许。
$ ssh -T git@gitee.com
The authenticity of host 'gitee.com (212.64.62.183)' can't be established.
ED25519 key fingerprint is xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.
This key is not known by any other names
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added 'gitee.com' (ED25519) to the list of known hosts.
git@gitee.com: Permission denied (publickey).
解决方案
重新配置ssh密钥,更换加密算法
ssh-keygen
默认使用rsa进行加密,但是上面报错提示使用的使用ED25519算法进行解密的,所有只需要换成ED25519算法生成密钥就行。
ssh-keygen -t ed25519
cat ~/.ssh/id_ed25519.pub
保存 git 账户
git config --global credential.helper store
git 配置用户名和邮箱 ref
用户名和邮箱地址是本地git客户端的一个变量 . 用户每次提交代码都会记录用户名和邮箱 .
- 查看所有配置信息
git config --list
- 查看用户名和邮箱
git config user.name git config user.email
- 设置用户名
git config --global user.name "username"
- 设置邮箱(没有双引号)
git config --global user.email useremail@xx.com
update 2024/8/26: ssh 绑定多个 github 账号
- ssh 绑定多个github 账号. 我现在有一个自己的 github 账号, 同时实验室有一个账号. 现需要在本地配置
git
和ssh
, 使其可以push到不同账号上的repo.
ref: http://jartto.wang/2017/12/19/one-git-for-more-repository/
- 你只有一个 SSH 公钥的话,你只能连接一个 Github 账号, 所以我们需要再创建一个SSH密钥,来绑定实验室的github 账号.
ssh-keygen -t rsa -C "{name}" -f ~/.ssh/id_rsa_{name}
- 接下来, 需要创建
~/.ssh/config
文件, 配置不同的仓库指向不同的私钥文件。
# 第一个账号,默认使用的账号
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa
# 第二个账号
Host second.github.com # second为前缀名,可以任意设置
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_xxx
- 将对应的pub 密钥填入对应的github 账号中. 测试 ssh 是否可用
ssh -T git@github.com
ssh -T git@second.github.com
- git 绑定不同的remote.
- 查看当前的remote 地址:
git remote -v
>> origin https://github.com/xxx/yyyy.git (fetch)
>> origin https://github.com/xxx/yyyy.git (push)
- 重新绑定remote 地址
git remote set-url origin git@github.com:xxx/yyyy.git # 第一个账户
git remote set-url origin git@second.github.com:xxx/yyyy.git # 第二个账户, Host的名字