TheJason
TheJason

Reputation: 504

NodeJS SSH2 not authenticating, with known host defined

I am trying to transfer files from one server to another using SSH2 in NodeJS. However, our network admins have setup the private keys for the authorized user and basically just made it possible to connect to the other server via command line like so... $ ssh user@server2 and I can connect without entering a password. I know the authentication is pre-defined in known_hosts, but I'm trying to get this working in nodejs.

It appears that either privateKey or password is required in the SSH2 config. Anyone know of a workaround for something like this? Or am I just doing something wrong? The only key I can find is in the known_hosts file, but it doesn't seem to be in the right format.

Here's what I'm working with...

var Client = require('ssh2').Client;
 
var conn = new Client();
conn.on('ready', function() {
  console.log('Client :: ready');
  conn.exec('uptime', function(err, stream) {
    if (err) throw err;
    stream.on('close', function(code, signal) {
      console.log('Stream :: close :: code: ' + code + ', signal: ' + signal);
      conn.end();
    }).on('data', function(data) {
      console.log('STDOUT: ' + data);
    }).stderr.on('data', function(data) {
      console.log('STDERR: ' + data);
    });
  });
}).connect({
  host: '192.168.100.100',
  port: 22,
  username: 'frylock',
  privateKey: require('fs').readFileSync('/here/is/my/key')
});

//// Another Option I've tried  /////////////////////////////////////////

let Client = require('ssh2-sftp-client');
let sftp = new Client();

sftp.connect({
  host: 'server2',
  port: '22',
  username: 'username',
}).then(() => {
  return sftp.list('/pathname');
}).then(data => {
  console.log(data, 'the data info');
}).catch(err => {
  console.log(err, 'catch error');
});

/////////  

Upvotes: 1

Views: 5198

Answers (1)

Tim X
Tim X

Reputation: 4235

With ssh key based authentication, you need to have access to the PRIVATE key. What is in known_hosts is the public key. Both SSH2 and ssh2-sftp-client will work with a private key file, but you need to have access to that key file in order to pass it in. There is an example of how to do this in the ssh2-sftp-client repository. (ssh2-sftp-client is just a wrapper around ssh2 and uses the same underlying connection method).

Speak to your network admins and find out how you can get access to the key or create a new key pair and ask them to install the public key on the sftp server. Once you have it, you should be able to do something like

let sftp = new Client();
sftp.connect({
  host: 'YOUR-HOST',
  port: 'YOUR-PORT',
  username: 'YOUR-USERNAME',
  privateKey: fs.readFileSync('/path/to/ssh/ke')
}).then(() => {
  sftp.fastPut(.....)
}

Upvotes: 1

Related Questions