SSH使用实践

SSH 使用实践

  1. 如何 SSH 密钥

  2. 使用公钥访问仓库的配置

  3. 通过 SSH 克隆仓库

SSH 使用实践

生成新的 SSH 密钥

注意: 本机已有RSA密钥,直接到最后一步: 4.将公钥放到 Gogs

  1. Git Bash on Windows / GNU/Linux / macOS:

    1
    ssh-keygen -t rsa -C "your.email@example.com" -b 4096

    在这里 email 建议用公司邮箱

  2. 一路回车

    最终会生成一个无密码的密钥。如果以后要更改密钥密码,使用命令:ssh-keygen -p <keyname>

  3. 复制公钥

    • macOS:

      1
      pbcopy < ~/.ssh/id_rsa.pub
    • GNU/Linux (requires the xclip package):

      1
      xclip -sel clip < ~/.ssh/id_rsa.pub
    • Windows Command Line:

      1
      type %userprofile%\.ssh\id_rsa.pub | clip
    • Git Bash on Windows / Windows PowerShell:

      1
      cat ~/.ssh/id_rsa.pub | clip
  4. 将公钥放到 Gogs

    登录 Gogs :用户设置->SSH密钥->增加密钥

使用公钥访问仓库的配置

以下推荐 Windows 下最佳实践方式,其他系统相似

  1. cd 到公钥所在位置

    Git Bash on Windows / Windows PowerShell:

    1
    cd ~/.ssh
  2. 添加 config 文件

    Git Bash on Windows / Windows PowerShell:

    1
    touch config
  3. 配置 config 文件

    Git Bash on Windows / Windows PowerShell:

    • 打开编辑

      1
      vi config
    • 添加配置

      1
      2
      3
      4
      5
      6
      # Gogs Keys
      Host Gogs
      Hostname <IP/域名>
      User git
      RSAAuthentication yes
      IdentityFile ~/.ssh/gitid_rsa # 记得把路径改为你的私钥路径
  4. 测试连接

    1
    ssh -T <IP/域名> 22

    第一次连接会做以下询问,输入 yes

    1
    2
    3
    The authenticity of host '<IP/域名> (<IP/域名>)' can't be established.
    RSA key fingerprint is SHA256:Tgp9GgkFu6HgJZ8Cn8kkWrylKGZOXvFE6GLfuMo8eQY.
    Are you sure you want to continue connecting (yes/no)?

    接下来会有以下提醒

    1
    2
    3
    Warning: Permanently added '<IP/域名>' (RSA) to the list of known hosts.
    Hi there, You've successfully authenticated, but Gogs does not provide shell access.
    If this is unexpected, please log in with password and setup Gogs under another user.

    到了这里,系统提醒当前密钥已经认证。

SSH 克隆仓库

  1. 命令

    1
    git clone <仓库SSH链接>
  2. cd 到仓库目录下

    • 查看仓库配置

      1
      git config -l
    • 配置当前仓库用户

      1
      2
      git config user.name <用户名>
      git config user.email <用户邮箱>
    • 配置全局用户

      1
      2
      git config --global user.name <用户名>
      git config --global user.email <用户邮箱>

      Tip: 当前仓库用户会覆盖全局用户。如果当前仓库没有配置用户,使用全局配置的用户。

推荐