NodeJS ssh2-sftp-客户端 |使用公钥和密码连接到 SFTP

问题描述 投票:0回答:1

我在使用公钥和密码连接到 SFTP 服务器时遇到问题。 我尝试了以下代码,但它无限调用回调函数。

我感谢任何意见。谢谢。


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()
});

javascript node.js public-key ssh2-sftp-client
1个回答
1
投票

这是我的工作解决方案。你可以在你的服务器上试试

    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
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.