免密访问

本地服务器操作

1
2
3
4
5
6
7
8
9
10
11
# 进入用户根目录
$ cd

# 检查是否已有文件id_rsa.pub
$ ls -l .ssh

# 若没有, 执行命令, 生成密钥, 该过程所有提示选项均直接按回车键即可
$ ssh-keygen

# 获取公钥内容, 并复制
$ cat .ssh/id_rsa.pub

在本地服务器上

1
2
3
4
5
# 配置git使用的用户
$ git config --global user.name [username]

# 配置git使用的email
$ git config --global user.email [email]

github网站上

  1. 登录账号
  2. 依次点击: ☞ 头像 ☞ SettingsSSH and GPG keysNew SSH key
  3. 粘贴之前复制的公钥到 Key 选框中, 再点击 Add SSH key

Windows下操作

Win + R 键,输入PowerShell打开Window终端,输入下面命令生成密钥,三次询问均直接回车

1
ssh-keygen -t rsa -b 4096

上传公钥到远端

1
scp .\.ssh\id_rsa.pub 远端用户名@远端IP:~/

警告

若仍需输入密码,需修改用户目录权限不低于755(即数值不大于755)

1
chmod 755 /home/[usr_name]

登录远端服务器操作

1
2
cat ~/id_rsa.pub >> ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys

配置多个ssh公钥

一个ssh公钥只能用于一个github账户,因此需要配置多个SSH公钥以便使用不同的GitHub账户

生成新的SSH密钥

使用命令ssh-keygen来生成新的SSH密钥对。当提示输入文件名时,应该为新密钥对指定一个唯一的名称,例如: ~/.ssh/id_rsa_github_personal~/.ssh/id_rsa_github_work,其他提示直接回车即可

注意

文件名应使用绝对路径,否则秘钥会生成在当前目录下

为每个git仓库配置用户信息

1
2
git config user.name "Your Name"
git config user.email "your@email.com"

为每个Git仓库配置不同的SSH密钥

1
git config core.sshCommand "ssh -i ~/.ssh/id_rsa_github_personal"

若是本地新建的仓库,则需要设置远程仓库的URL

1
git remote set-url origin git@github.com:yourusername/your-repo.git

在 ~/.ssh/ 目录下创建或编辑 config 文件,添加以下内容为每个GitHub帐户定义了一个别名,通过别名来选择要使用的SSH密钥文件

1
2
3
4
5
6
7
8
9
10
11
# Personal GitHub account
Host github.com-personal
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_github_personal

# Work GitHub account
Host github.com-work
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_github_work

注意

在使用Git时,需要将远程URL更改为之前定义的别名例如: git@github.com:yourusername/your-repo.git 需要修改为 git@github.com-personal:yourusername/your-repo.git

本地git仓库目录下执行命令配置远程仓库的URL

1
git remote set-url origin git@github.com-personal:yourusername/your-repo.git