Node.JS exec git command error: Permission denied

2019-05-18 21:14发布

问题:

Question: How can I run git push from node.js with passphrase.

I'm trying to build a small module where I need to run git push from node.js to a remote repo, but I'm getting an error when I with from node.js exec but not from the terminal.

My code.

./command.ts

import * as util from 'util';

const exec = util.promisify(require('child_process').exec);

export default function command(command: string): Promise<string> {
  return exec(command, {cwd: process.cwd()}).then((resp) => {
    const data = resp.stdout.toString().replace(/[\n\r]/g, '');
    return Promise.resolve(data);
  });
}

./index.ts

import command from './command';

async function init() {
 try {
  await command('git add .');
  await command('git commit -m "my commit" ');
  conat result = await command('git push');
 } catch (e) {
  console.log(e);
 }
}

init();

and when I run ts-node ./index.ts I get the following error.

Error: Command failed: git push                                                                                                         
git@hostname.org: Permission denied (publickey).                                                                                       
fatal: Could not read from remote repository.                                                                                           

Please make sure you have the correct access rights                                                                                     
and the repository exists.

But when I run git push from the terminal I get prompt with the passphrase and it works.

Any idea on how to solve this issue, is there a way to run git push with passphrase using node.js?

bear in mind that I will love to fix this without any external libs.

Thanks in advance.

回答1:

As described here, check if the same program works when:

  • ssh-agent is launched
  • your key is ssh-add'ed

Not only the prompt should no longer query for your passphrase (now cached by the agent), but your script might benefit from that cache as well.



回答2:

You may need to add env: process.env to your exec() options if your key is loaded into an ssh-agent process. There are some environment variables ssh-agent exports that other processes use to find ssh-agent to access its keys.