使用ssh key来提交git代码

以github和gitee为例。

创建ssh keys

首先是创建一个ssh key。参见Generating a new SSH key and adding it to the ssh-agent生成/添加SSH公钥

1
ssh-keygen -t ed25519 -C "[email protected]"

添加ssh公钥到git服务

github参见Adding a new SSH key to your GitHub account

gitee参见生成/添加SSH公钥

验证

添加完ssh公钥可使用ssh -T来验证。

1
2
3
4
5
6
7
> ssh -T [email protected]
The authenticity of host '[ssh.github.com]:443 ([198.18.0.155]:443)' can't be established.
ED25519 key fingerprint is SHA256:WJxA1e/dM8m1V9Q+8tJjOt3K1T4M6g3V+LfZ6PQErUg.
This key is not known by any other names
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '[ssh.github.com]:443' (ED25519) to the list of known hosts.
Hi $your_name! You've successfully authenticated, but GitHub does not provide shell access.

配置多个ssh keys

如果存在多个ssh keys,需要添加配置文件~/.ssh/config来指定具体使用哪个key。参见Git配置多个SSH-Key

1
2
3
4
5
6
7
8
9
10
11
# gitee
Host gitee.com
HostName gitee.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/gitee_id_rsa

# github
Host github.com
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/github_id_rsa

ssh key密码

如果在创建ssh key时指定了密码,为了避免反复输入密码,可以使用ssh-agent。参见Working with SSH key passphrases

切换仓库地址

使用ssh key认证后,拉取仓库就需要使用ssh地址而不是https地址。

1
2
3
4
5
6
7
8
9
> git remote -v
origin https://github.com/username/repository.git (fetch)
origin https://github.com/username/repository.git (push)

> git remote set-url origin [email protected]:username/repository.git

> git remote -v
origin [email protected]:username/repository.git (fetch)
origin [email protected]:username/repository.git (push)

附录:github连接出错

如果碰到了这个问题:

1
2
3
4
5
6
7
8
9
10
> ssh -T [email protected]
kex_exchange_identification: Connection closed by remote host
Connection closed by 20.27.177.113 port 22

> ssh-keyscan github.com
github.com: Connection closed by remote host
github.com: Connection closed by remote host
github.com: Connection closed by remote host
github.com: Connection closed by remote host
github.com: Connection closed by remote host

问题原因是翻墙软件只代理了常见的80和443而没有代理22端口,需要在config里修改两个地方:

  1. 指定使用443端口
  2. 同时将HostName指定为ssh.github.com
1
2
3
4
5
6
7
# github
Host github.com
HostName ssh.github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/github_id_rsa
IdentitiesOnly yes
Port 443

附录:使用ssh key登录云服务器

使用ssh key来登录云服务器也非常方便。

首先在云服务器端,将公钥添加到~/.ssh/authorized_keys文件中。

1
cat cloud_id_rsa.pub >> ~/.ssh/authorized_keys

然后在客户机可以这样定义config:

1
2
3
4
5
# cloud
Host cloud
HostName 11.22.33.44
User root
IdentityFile ~/.ssh/cloud_id_rsa

接着只要使用ssh cloud就可以登录云服务器了。