【问题标题】:NodeJS ssh2-sftp-client | connecting to SFTP using public key and a passphraseNodeJS ssh2-sftp-client |使用公钥和密码连接到 SFTP
【发布时间】:2022-06-15 03:21:58
【问题描述】:

我在使用公钥和密码连接到 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】:

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

        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 client.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 client.end(); // don't forget to close connection
            }
        }
    

    【讨论】:

    • 您的答案可以通过添加有关代码的作用以及它如何帮助 OP 的更多信息来改进。
    猜你喜欢
    • 2013-09-05
    • 2016-11-23
    • 2015-03-31
    • 2021-09-28
    • 1970-01-01
    • 1970-01-01
    • 2019-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多