M.K.
M.K.

Reputation: 23

NodeJS ssh2-sftp-client | connecting to SFTP using public key and a passphrase

I'm having a problem connecting to SFTP server using public key and a passphrase. I've tried the following code but it is infinitely calling the callback function.

I appreciate any input. Thank you.


let sftpClient = require('ssh2-sftp-client');

let sftp = new sftpClient();

let conf = {
    host: 'host',
    port: 'port',
    username: 'username',
    keepaliveInterval: 1000
};

conf.authHandler = function (methodsLeft, partialSuccess, callback) {
    console.log('authhandler invoked')
    callback({
        type: 'publickey',
        username: 'username',
        passphrase: 'password',
        key: fs.readFileSync('./id_rsa.pub', 'utf8')
    });
}

sftp.connect(conf).then(() => {
    console.log('connected')
    // upload process here

}).then(data => {

    sftp.end()
}).catch(err => {
    console.log(err, 'catch error');
    sftp.end()
});

Upvotes: 0

Views: 7923

Answers (1)

Roksolana M
Roksolana M

Reputation: 26

This is my working solution. You can try on your server

    const sftpClient = require('ssh2-sftp-client');

    async upload(file) {
      const sftp = new sftpClient();
      const sftpSSHKey = fs.readFileSync(keyPath);

      try {
          await sftp.connect({
            host: 'somehost',
            port: 'port',
            username: 'username',
            privateKey: sftpSSHKey,
            passphrase: 'passphrase for an encrypted private key',
          });
          console.log('Successfully connected to sftp');
        } catch (error: any) {
          console.log(error);
        }

        try {
          const res = await sftp.put(Buffer.from(file), '/folder/fileName', {
            writeStreamOptions: {
              flags: 'w',
              encoding: null, // use null for binary files
            },
          });
           console.log('File uploaded successfully');
        } catch (error) {
          console.log(error);
        } finally {
          await sftp.end(); // don't forget to close connection
        }
    }

Upvotes: 1

Related Questions