Zydecx's Site

Debug code, debug life, debug today!

使用SSH密钥连接Git仓库

Time: , by zydecx

检查SSH密钥是否存在

打开Git Bash,执行下面的命令,显示.ssh目录下的所有文件:

ls -al ~/.ssh

如果该目录下已经存在密钥对(比如,id_rsa.pub/id_rsa是一对公/私钥),可跳过下一步直接添加密钥到ssh-agent。

生成新的SSH密钥

  1. 打开Git Bash,执行下面的命令,其中,邮箱是Git仓库中使用的账号所对应的邮箱

    ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
  2. 弹出下面的提示信息,如果需要修改密钥文件位置或名称,可以输入新的路径;直接回车使用默认路径

    Enter file in which to save the key (/c/Users/you/.ssh/id_rsa): [Press enter or new path here]
  3. 接下来提示输入密码,直接回车不需要密码。仍然建议输入密码,否则,任何有电脑操作权限的用户均可以直接用你的账号向仓库提交代码,而不需要任何验证

    Enter passphrase (empty for no passphrase): [Press Enter or Type a passphrase here]
    Enter same passphrase again: [Press Enter or Type a passphrase again here]
  4. 密码输入完成后,提示生成成功,并显示密钥指纹信息;此时在前面指定的目录下会看到有两个新的文件:id_rsa.pub/id_rsa

    Your identification has been saved in id_rsa.
    Your public key has been saved in id_rsa.pub.
    The key fingerprint is:
    b1:6b:d3:21:e2:cf:45:4a:37:80:a4:e4:d5:76:69:21 your_email@example.com
    The key's randomart image is:
    +--[ RSA 4096]----+
    |    . o.E .o     |
    |   o + .o.+      |
    |    o ..oo       |
    |         +       |
    |      . S =      |
    |     . o B o     |
    |      . = o      |
    |       + o       |
    |        o        |
    +-----------------+

添加密钥到ssh-agent

  1. 启动ssh-agent

    打开Git Bash,执行以下命令启动ssh-agent

    ssh-agent -s

    Note:

    使用msysgit Bash on Windows时,需要执行下面的命令才能成功启动。否则接下来使用ssh-add时会出现Could not open a connection to your authentication agent的错误。引用

    eval `ssh-agent -s`或eval $(ssh-agent -s)
  2. 将密钥添加到ssh-agent

    ssh-add ~/.ssh/id_rsa

添加密钥到Git仓库使用的账号(以GitHub为例)

  1. 将生成的公钥id_rsa.pub中的内容复制到剪贴板中(或者打开Git Bash,执行以下命令:)

    clip < ~/.ssh/id_rsa.pub
  2. 登陆GitHub,点击右上角头像,依次进入Settings->SSH keys,点击Add SSH key,在Title中输入密钥描述信息,如“个人笔记本密钥”,在Key中输入刚才复制的公钥,点击Add key,添加公钥

验证连接

正式使用SSH密钥访问Git仓库前,最好验证密钥是否能成功连接到Git服务器。

  1. 打开Git Bash,执行下面的命令(将your-git-server-domain替换成实际的Git服务器地址)

    ssh -T git@your-git-server-domain
  2. 命令执行后,显示下面的警告,确认密钥的指纹信息后,输入yes

    The authenticity of host 'github.com (207.97.227.239)' can't be established.
    # RSA key fingerprint is 16:27:ac:a5:76:28:2d:36:63:1b:56:4d:eb:df:a6:48.
    # Are you sure you want to continue connecting (yes/no)?
  3. 显示下面的信息,确认用户名(username)为自己的,则表示已成功配置SSH密钥

    # Hi username! You've successfully authenticated, but GitHub does not
    # provide shell access.

其他

修改密钥密码

    ssh-keygen -p

切换现有Git仓库地址

    git remote -v
    git remote set-url origin your-git-repository-address

参考

Generating SSH keys
Working with SSH key passphrases
Changing a remote's URL


This is a magic phrase. You CANNOT see it(I'll really FULE you if you do that), but it does work. Why? You may feel confused. OK, at least it doesn't afftect your experience and it works. That is what we call MAGICE!