Yiner

Sep 28, 2021

Git添加SSH key

添加SSH Key

 

生成新的 SSH 密钥对

  1. 生成密钥
    1. ssh-keygen -o -t rsa -C "your.email@example.com" -b 4096
      Git Bash on Windows / GNU/Linux / macOS
      • 注:参数-o不行可以去掉。
 
  1. 指定保存密钥的文件
    1. 生成后会提示需要指定保存密钥的文件,会有一个默认地址~/.ssh/id_rsa,如果已经存在,想存另一个文件,可以指定,例如~/.ssh/xxx_id_rsa
      • 会生成两个文件,私钥:xxx_id_rsa,公钥:xxx_id_rsa.pub
 
  1. 修改配置文件
    1. 如果不是使用默认密钥文件地址,需要将密钥文件信息写入配置文件~/.ssh/config中。
      • 首先,检查 ~/.ssh/config 文件是否在默认位置。
        • $ open ~/.ssh/config > The file /Users/you/.ssh/config does not exist.
      • 如果文件不存在,请创建该文件。
        • $ touch ~/.ssh/config
      • 打开 ~/.ssh/config 文件,然后修改文件以包含以下行。
        • Host xxx AddKeysToAgent yes UseKeychain yes IdentityFile ~/.ssh/xxx_id_rsa
          # GitLab.com server Host gitlab.com RSAAuthentication yes IdentityFile ~/.ssh/config/private-key-filename-01 # Private GitLab server Host gitlab.company.com RSAAuthentication yes IdentityFile ~/.ssh/config/private-key-filename
          样例
          注意: 
        • 如果您选择不向密钥添加密码,应该省略 UseKeychain 行。
        • 如果您看到如下错误:/Users/USER/.ssh/config: line 16: Bad configuration option: usekeychain,向 Host * 部分添加一个额外的配置行:
          • Host * IgnoreUnknown UseKeychain
           

将 SSH 密钥添加到网站帐户

  1. 将公钥信息拷贝到剪贴板
    1. # macOS: pbcopy < ~/.ssh/~/xxx_id_rsa.pub # GNU/Linux (requires the xclip package): xclip -sel clip < ~/.ssh/xxx_id_rsa.pub # Windows Command Line: type %userprofile%\.ssh\xxx_id_rsa.pub | clip # Git Bash on Windows / Windows PowerShell: cat ~/.ssh/xxx_id_rsa.pub | clip
      注:公钥是以ssh-rsa开头,邮箱结尾的文本。
 
  1. 添加到网站指定位置
  1. 测试是否生效
    1. ssh -T git@example.com # 加-v显示调试信息 ssh -Tv git@example.com
      将 example.com 换成网站域名,如GitLab,看是否收到类似 Welcome to GitLab的信息。

Copyright © 2024 Yiner

logo