生成密钥

同样的方式可以生成多个

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

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

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文件(无后缀名),并完成下面相关配置

配置文件如下:

# 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
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设置用户名与邮箱地址

设置全局用户名

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

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

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