Home > Software engineering >  Establish connection to remote SSH server with private key for exec, Node.js
Establish connection to remote SSH server with private key for exec, Node.js

Time:12-30

Trying to connect to a remote SSH server, Linux Ubuntu virtual machine, and execute commands.

I feel dumb having to ask this, but I've gone through dozens of node modules and cannot find a solution.

I believe it's something wrong on my end, as I'm a novice in coding, but I'm looking to connect to a virtual machine (which runs on Linux, Ubuntu) via SSH in order to execute some commands automatically. As of now, I connect to the server through PuTTY. I use the default port (22), fill in the IP address, and username, and upload my key. After going through a ton of SSH modules, each one gives me nothing: no error, no response, nothing - apart from, sometimes, "All configured authentication methods failed." This makes me assume I'm somehow linking my key incorrectly. I fill out the private key path like so: key: - or whatever the option name is - require('fs').readFileSync('./keys/key.key') or just readFileSync('./keys/key.key') if fs has already been acquired. I've filled in the path if the option only required the path, and I've attempted to use Buffer.from() as well, although I'm not too familiar with it. The key is defaultly in RSA format, but I've also converted it to OpenSSH using ssh-keygen to no avail. I've tried using keyboard-interactive, but, the host does not require this, and no keyboard-interactive prompts come up at all. I've tried adding a passphrase to the key, and nothing. I don't know what to do, and I cannot find an answer anywhere online.

Thank you!

CodePudding user response:

I was finally able to find an answer after days of searching. Turns out, there is a prompt regarding host authenticity which must be resolved. I didn't notice this at all considering I had already accepted it on my preferred SSH client and it never prompted me again - the prompt also had its own grandiose UI, so I didn't know it was intrinsic, but I rather assumed it was of the client itself. I wasn't able to fix this using keyboard-interactive, but I was able to modify the options of the ssh command in the child process method exec. Here's the code:

const { exec } = require('child_process');

const command = 'ssh -tt -i ./keys/key.key -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no user@host command';
/* replace user, host, and command with desired options */
exec(command, (err, stdout, stderr) => {
  if (err) throw err;
  process.stdout.write(stdout);
});

This bypassed the authenticity prompt as it tricks the system into believing it is already a known host.

  • Related