使用ssh连接github或gitee - 已创建密钥但依旧无法使用git命令无法连接, 显示git@github.com: Permission denied (publickey).
<h2 id="阅读须知">阅读须知</h2><blockquote>
<p>本文面向入门, 可能有出现错误的情况, 欢迎指出.<br>
本文主要引导解决与发现问题的方法, 解决方案可以翻到最下面</p>
</blockquote>
<p>代码块中<br>
<code>$</code> 开头表示输入内容<br>
<code>></code> 开头代表输出内容<br>
<code>#</code> 后面代表注释的内容<br>
示例如下</p>
<pre><code class="language-GITBASH">$ 我是输入内容
> 我是输出内容 # 我是注释,用于解释发生了什么
</code></pre>
<h2 id="场景">场景</h2>
<blockquote>
<p>在添加ssh的教程中,一般都会让我们使用<code>ssh git@github.com</code>验证是否连接成功</p>
</blockquote>
<p>首先按需求使用<code>ssh-keygen</code>创建密钥(<strong>请确保密钥在~/.ssh中</strong>)</p>
<pre><code class="language-GIT">> Enter file in which to save the key: mykey # 请记住这里, 是出现问题的主要原因
> Enter passphrase (empty for no passphrase): 114514 # 这一步和下一步都是设置密码, 不输入也可以. 实际输入的时候你是看不到内容的, 这是正常现象.
> Enter same passphrase again:114514
</code></pre>
<p>使用'ssh git@github.com'连接</p>
<blockquote>
<p>此时请确保已将<code>公钥(.pub)!!!</code>添加到<code>github/gitee</code></p>
</blockquote>
<pre><code class="language-GIT">$ ssh git@github.com
> git@github.com: Permission denied (publickey).
</code></pre>
<p>可以看到明明在<code>github/gitee</code>中 <strong>添加了公钥</strong>,<strong>私钥位置也没问题</strong>, 但是却依旧连接失败</p>
<h2 id="原因">原因</h2>
<p>这里可以用到 <code>-v</code> 参数, 这个参数可以显示连接时的日志.</p>
<blockquote>
<p>使用<code>-vvv</code>能看到更详细的信息, 但这里不需要, 对这些信息代表什么感兴趣的可以去看看<code>ssh连接调试</code>.</p>
</blockquote>
<pre><code>$ssh git@github -v
...
> debug1: Will attempt key: /c/Users/xxx/.ssh/id_rsa
> debug1: Will attempt key: /c/Users/xxx/.ssh/id_ecdsa
> debug1: Will attempt key: /c/Users/xxx/.ssh/id_ecdsa_sk
> debug1: Will attempt key: /c/Users/xxx/.ssh/id_ed25519
> debug1: Will attempt key: /c/Users/xxx/.ssh/id_ed25519_sk
> debug1: Will attempt key: /c/Users/xxx/.ssh/id_xmss
> debug1: Will attempt key: /c/Users/xxx/.ssh/id_dsa
...
</code></pre>
<p>可以看到, 连接日志并没有尝试我们的<code>/c/Users/xxx/.ssh/mykey</code>私钥</p>
<p>那么原因已经出来了: 因为我们命名了密钥, 但是ssh连接默认是会使用默认名称的, 并不是我们放在<code>~./ssh</code>目录下就自动读取</p>
<h2 id="解决方案">解决方案</h2>
<p>知道了原因, 解决方法就是告诉ssh去使用我们的密钥, 主要有以下两种方法</p>
<h3 id="1-使用-i参数指定私钥位置">1. 使用<code>-i</code>参数指定私钥位置</h3>
<blockquote>
<p>这种方法每次都要指定私钥位置, 不方便, 不太推荐</p>
</blockquote>
<pre><code class="language-GIT">$ ssh git@github -i ~/.ssh/mykey # 这里mykey是你命名的私钥名称
</code></pre>
<h3 id="2-使用config配置文件">2. 使用<code>config</code>配置文件</h3>
<p>在<code>~/.ssh/config</code>添加文件config<br>
在里面添加内容</p>
<pre><code class="language-CONFIG">Host github.com
User git
IdentityFile ~/.ssh/mykey # 这里mykey换成你命名的私钥名称
</code></pre>
<p>在配置文件中使用配置项<code>IdentityFile </code>指定了连接github使用的密钥.<br>
再次尝试, 已经可以正常连接了.</p>
<h3 id="3-拓展内容">3. 拓展内容</h3>
<p>关于ssh, config里还有许多方便的配置, 感兴趣也可以去了解一下.<br>
比如</p>
<pre><code>Host github
HostName github.com
User git
IdentityFile ~/.ssh/mykey
</code></pre>
<p>这样甚至可以直接使用<code>ssh github</code>连接</p>
<blockquote>
<p>只是用于示例, git没有必要这样使用</p>
</blockquote><br><br>
来源:https://www.cnblogs.com/faser/p/17838919.html
頁:
[1]