生成密钥

同样的方式可以生成多个

ssh-keygen -t rsa -C soyl@live.cn

执行命令 ssh-keygen -t rsa -C email 创建 github 对应的 sshkey,命名为 id_rsa_github,命名之后下面的可以直接跳过

shell
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/soyl/.ssh/id_rsa): id_rsa_github
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in id_rsa_github.
Your public key has been saved in id_rsa_github.pub.
The key fingerprint is:
SHA256:rZQO751cjfzzjDxJq5ZjI6pKKMWFlO6J+ZdvnWcra6M soyl@live.cn
The key's randomart image is:
+---[RSA 2048]----+
| .. |
| ... |
| .. . |
| ... o |
| +o. . S . |
|o.o. = . . o. |
|... .. .+. +o.o |
| ...o ..*o+o*o=o |
| ..+E++B==.+++o|
+----[SHA256]-----+

Config 配置

在.ssh 目录创建 config 文件 (无后缀名),并完成下面相关配置

配置文件如下:

shell
# github.com的配置
Host github.com               
HostName github.com
IdentityFile ~/.ssh/id_rsa_github
PreferredAuthentications publickey
User HeySoyl
# github.com_2的配置
Host github_2.com               
HostName github.com
IdentityFile ~/.ssh/id_rsa_github_2
PreferredAuthentications publickey
User HeySoyl
# code.aliyun.com的配置
Host code.aliyun.com
HostName code.aliyun.com
IdentityFile ~/.ssh/id_rsa_aliyun
PreferredAuthentications publickey
User Soyl

每个账号单独配置一个 Host,每个 Host 要取一个别名,每个 Host 主要配置 HostName 和 IdentityFile 两个属性即可

  1. Host 别名可以取为自己喜欢的名字,不过这个会影响 git 相关命令,调取这个 Host 会自动替换掉用 HostName 中真实域名地址,可以设置多个 github key。例如:
    Host github_2 这样定义的话,命令如下,即 git@后面紧跟的名字改为 github_2
shell
git clone git@github.com:HeySoyl/HeyAT-API.git
# clone代码的命令就变成下面的了,但是调用的是HostName中配置的域名
git clone git@github_2:HeySoyl/HeyAT-API.git

git remote add origin git@github.com:HeySoyl/HeyAT-API
# 同样,上传代码时也需要修改
git remote add origin git@github_2.com:HeySoyl/HeyAT-API
  1. HostName 这个是真实的域名地址
  2. IdentityFile 这里是 id_rsa 的地址
  3. PreferredAuthentications 配置登录时用什么权限认证–可设为 publickey,password publickey,keyboard-interactive 等,这里默认用 publickey
  4. User 配置使用用户名

Git 设置用户名与邮箱地址

设置全局用户名

shell
git config --global --user.name "yourname"
git config --global --user.email "youremail"

在仓库目录下设置局部用户名和邮箱

shell
git config user.name "yourname"  
git config user.email "youremail"