简体   繁体   English

Node.js 的 SSH2 问题

[英]SSH2 issues wiht Node.js

I got this code that it seems to be working but it does not.我得到了这段代码,它似乎正在工作,但它没有。

let REMOTE_SSH_HOST = '190.444.01.75:55554'
let REMOTE_SSH_USERNAME = 'olec'
let REMOTE_SSH_PASSWORD = 'm3uW4jkbaEwVChklFszpbm4'
const Client = require('ssh2-sftp-client');
const sshConfig = {
    host: process.env.REMOTE_SSH_HOST,
    //port: 22,
    username: process.env.REMOTE_SSH_USERNAME,
    password: process.env.REMOTE_SSH_PASSWORD,
    readyTimeout: 99999,
};
let sftp = new Client();

async function Read(directory) {
    console.log('Read(' + directory + ')');
    const result = await sftp.list(directory);
    for(const sub of result) {
      if (sub['type'] === 'd') {
          await Read(directory + '/ ' + sub['name']);
      }
    }
}

async function main(directory) {
  try{
    const myList = await sftp.list(directory);
    }catch(err){console.log(err)}//NEVER forget to catch
    finally {
        console.log('Closing session...');
        await sftp.end();
        console.log('Session closed.');
    }
}
console.log('Application started');
main('/home/user/path').then(r => {
    console.log('Application ended.');
});

I get the error message of:我收到以下错误消息:

(Use node --trace-warnings... to show where the warning was created) (node:16240) UnhandledPromiseRejectionWarning: Unhandled promise rejection. (使用node --trace-warnings...显示警告的创建位置)(节点:16240) UnhandledPromiseRejectionWarning:未处理的 promise 拒绝。 This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with.catch().此错误源于在没有 catch 块的情况下抛出异步 function 内部,或拒绝未使用.catch() 处理的 promise。 To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode ).要终止未处理的 promise 拒绝的节点进程,请使用 CLI 标志--unhandled-rejections=strict (请参阅https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode )。 (rejection id: 5) (node:16240) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. (拒绝 ID:5)(节点:16240)[DEP0018] DeprecationWarning:不推荐使用未处理的 promise 拒绝。 In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.将来,未处理的 promise 拒绝将使用非零退出代码终止 Node.js 进程。

I think you might need something like我想你可能需要类似的东西

const sftp = new Client();
await sftp.connect({
  host: hostAddress,
  username: '...',
  privateKey: ...,
});

The issue is you are using environment variables where you have set consts.问题是您正在使用设置了 consts 的环境变量。 (also you are setting consts as lets... don't ever use a let where something will never change. (您也将 consts 设置为让...永远不要使用让某些东西永远不会改变的地方。

const Client = require('ssh2-sftp-client');
const REMOTE_SSH_HOST = '190.444.01.75'
const REMOTE_SSH_PORT = '55554';
const REMOTE_SSH_USERNAME = 'olec'
const REMOTE_SSH_PASSWORD = 'm3uW4jkbaEwVChklFszpbm4'
const sshConfig = {
    host: REMOTE_SSH_HOST,
    port: REMOTE_SSH_PORT,
    username: REMOTE_SSH_USERNAME,
    password: REMOTE_SSH_PASSWORD,
    readyTimeout: 99999,
};

Thnx gonna try this and get back to you! Thnx 会试试这个并回复你!

There are a series of errors on your script that are causing the issue.您的脚本中存在一系列导致问题的错误。 The main one is that you are not handling errors in your async code.主要问题是您没有处理async代码中的错误。 You should add a catch chain function to your main call because, even though you are using a try/catch clause inside your main function, it doesn't consider the code that runs inside the finally block.您应该在main调用中添加一个catch链 function,因为即使您在main function 中使用try/catch子句,它也不会考虑在finally块中运行的代码。

On the other hand, your code seems to be failing because you are running sftp.list before running sftp.connect .另一方面,您的代码似乎失败了,因为您在运行sftp.list之前正在运行sftp.connect

There are a couple of minor errors that could potentially cause problems in your script:有几个小错误可能会导致脚本出现问题:

  1. The address 190.444.01.75 is not a valid IPv4 address.地址190.444.01.75不是有效的 IPv4 地址。
  2. You should provide default values when reading env variables where they make sense.在读取env的环境变量时,您应该提供默认值。
  3. You are not really using the Read function yet, but I would suggest you name functions in lower case.您还没有真正使用Read function,但我建议您以小写字母命名函数。
  4. You are declaring the variable of the for-of loop inside the Read function with const .您正在使用constRead function 中声明for-of循环的变量。 It would be best to use let instead since the engine will update it on each iteration.最好使用let代替,因为引擎会在每次迭代时更新它。

Here is a modified example of your script that works:这是一个修改后的脚本示例:

const Client = require('ssh2-sftp-client')

/**
 * Global variables
 */
const SSH_CONFIG = {
  host     : process.env.REMOTE_SSH_HOST     || '190.44.1.75:55554',
  port     : process.env.REMOTE_SSH_PORT     || 22,
  username : process.env.REMOTE_SSH_USERNAME || 'olec',
  password : process.env.REMOTE_SSH_PASSWORD,
  readyTimeout: 99999,
}
const ROOT = process.env.ROOT || '/home/user/path'

/**
 * Constructors
 */
const sftp = new Client()

/**
 * Main
 */
console.log("Application Started!")
main(ROOT)
  .then ((response) => console.log(response))
  .catch((err)      => console.error(err))

/**
 * Functions
 */
async function main(directory) {
  let myList
  try {
    await sftp.connect(SSH_CONFIG)
    return await sftp.list(directory)
  } catch(err) {
    console.error(err)
  } finally {
    console.log('Closing session...')
    await sftp.end()
    console.log('Session closed.')
  }
}

And here is how you would call it:这就是你如何称呼它:

env REMOTE_SSH_HOST=10.0.0.10 \
env REMOTE_SSH_USERNAME=conatel \
env REMOTE_SSH_PASSWORD=C0n4t3lC0n4t3l \
env REMOTE_SSH_PORT=22 \
env ROOT=/home/conatel \
node ssh.js

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM