使用node-ssh执行git pull遇公钥权限拒绝,需如何配置?
解决node-ssh执行git pull时的公钥权限问题
问题原因
你通过node-ssh连接远程服务器后,执行git pull的shell环境默认不会继承当前用户已加载的ssh-agent身份信息,导致git无法访问部署密钥,触发权限拒绝错误。
解决方案
方法1:传递ssh-agent环境变量
远程服务器上的ssh-agent通过SSH_AUTH_SOCK环境变量标识套接字路径,你需要在执行git命令时将这个变量传入node-ssh的执行环境:
- 先获取远程服务器当前用户的
SSH_AUTH_SOCK路径:
// 获取ssh-agent的套接字路径 const { stdout: authSockOutput } = await ssh.execCommand('echo $SSH_AUTH_SOCK'); const sshAuthSock = authSockOutput.trim();
- 在执行
git pull时指定该环境变量:
await ssh.execCommand(`git pull`, { onStdout: (out) => console.log(out.toString('utf8')), onStderr: (out) => { console.error(out.toString('utf8')) throw out.toString() }, cwd: '/path-to-my-repo', env: { SSH_AUTH_SOCK: sshAuthSock } })
方法2:直接指定部署密钥路径(可选)
如果不想依赖ssh-agent,可以直接在git命令中指定部署密钥文件路径(需确保密钥文件在远程服务器上的路径正确):
await ssh.execCommand(`GIT_SSH_COMMAND="ssh -i /path/to/your/deploy-key" git pull`, { onStdout: (out) => console.log(out.toString('utf8')), onStderr: (out) => { console.error(out.toString('utf8')) throw out.toString() }, cwd: '/path-to-my-repo', })
注意:如果密钥设有密码短语,这种方式需要额外处理密码输入,不如方法1便捷。
内容的提问来源于stack exchange,提问作者Patrick Benjamin
相关产品推荐
相关产品推荐

