node.js - 无法通过在 Node.js 中添加 ssh-key 来进行 git clone

标签 node.js command-line ssh-keys

  # Write the SSH-KEY to the disk
  fs.writeFile "/cgrepos/.ssh/#{repo.id}.pub", repo.public_key, (err) ->
    throw err if err

    fs.writeFile "/cgrepos/.ssh/#{repo.id}", repo.private_key, (err) ->
      throw err if err

      exec "chmod 400 /cgrepos/.ssh/#{repo.id} && eval `ssh-agent -s` && ssh-add /cgrepos/.ssh/#{repo.id}", (error) ->
        throw error if error
        # First, delete the git repo on the hard drive, if it exists
        exec "rm -rf #{git_location}", options, (error) ->
          throw error if error
          # Second, clone the repo into the location
          console.log "Cloning repo #{repo.id}: #{repo.repo_name} into #{git_location}. This could take a minute"
          exec "git clone #{repo.url} #{git_location}", options, (error) ->
            throw error if error

我正在 node 中尝试(使用 coffee 那些很棒的)。但出于某种原因,当它运行时,它给了我一个错误:错误:命令失败:conq:存储库访问被拒绝。部署 key 未与请求的存储库相关联。

不确定我做错了什么。如果我直接从命令行运行这些命令,一切似乎都正常。有什么想法吗?

最佳答案

当您尝试从 node.js 执行 git clone 进程时,它会在不同的环境中运行。

当您在 protected (基于 ssh 协议(protocol))存储库上使用 git clone 时,ssh-agent 首先尝试使用提供的公钥对您进行身份验证。由于 exec 为每个调用使用不同的运行时环境,即使您显式添加私钥,它也不会因为不同的运行时环境而工作。

在 ssh 中进行身份验证时,git clone 会查找 SSH_AUTH_SOCK。通常这个环境变量有你的密码 key 环服务的路径,比如(gnome-keyring 或 kde-wallet)。

先试试这个检查一下。

env | grep -i ssh

它应该列出 SSH_AGENT_PID 和 SSH_AUTH_SOCK。问题是在运行 git clone 时,这些环境变量没有设置。因此,您可以将它们设置为 exec 函数调用中的选项(仅 SSH_AUTH_SOCK 就足够了)。看here关于如何将 env key 对传递给 exec。

var exec = require('child_process').exec,
    child;

child = exec('git clone cloneurl', {
  cwd: cwdhere,      // working dir path for git clone
  env: {
           envVar1: envVarValue1,
           SSH_AUTH_SOCK: socketPathHere
       } 
}, callback);

如果这不起作用,请尝试在 exec 函数中执行 ssh -vvv user@git-repo-host。查看此过程的输出,您会发现错误。

如果错误提示 debug1: No more authentication methods to try。权限被拒绝(公钥)。,然后像这样将主机别名添加到 $HOME/.ssh/config 文件。

Host hostalias
 Hostname git-repo-host
 IdentityFile ~/.ssh/your_private_key_path

这将使用提供的私钥对指定主机的所有身份验证请求。在此选项中,您还可以更改您的 origin's url 以使用上面文件中配置的 hostalias。 reporoot/.git/config 文件将如下所示。

[remote "origin"]
    url = user@hostalias:repo.git

关于node.js - 无法通过在 Node.js 中添加 ssh-key 来进行 git clone,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15537822/

相关文章:

node.js - 如何在 restify 上扩展 socket.io?

node.js - 为什么 `node` 将 `npm` 的版本固定到每个版本?

javascript - 为什么我不能设置 Jquery 的属性并在 Electron 中得到未定义的答案

json - mongoexport JSON 断言 : 10340 Failure parsing JSON string

ssh - 如何在windows机器中生成known_host文件

node.js - 502 Bad Gateway - Ubuntu 16.04.2 LTS 上的 Meteor 和 nginx

azure - 如何在Azure池启动任务中运行多个命令行

Windows cygwin 相当于 Mac OS X 打开命令

google-cloud-platform - Google Cloud - 通过私钥访问Linux VM