【问题标题】:Ssh conection with async value具有异步值的 SSH 连接
【发布时间】:2021-08-31 15:44:29
【问题描述】:

我需要获取 cat 值 txt 返回并将其传递给另一个函数,但当前在 try catch 和 Promise 挂起时出现错误,我该怎么做?

   var SSH2Shell = require("ssh2shell");

async function sshFunction() {
  let finalList = [];
  try {
    var host = {
      server: {
        host: "xxxxxxxxxxxx",
        userName: "xxxxxxxxxx",
        password: "xxxxxxx",
      },
      commands: [
        "sudo /usr/bin/rootsh -i -u root",
        "cd ..; cd u01/scripts/; cat saida.txt",
      ],
    };

    finalList.push(
      (result = await SSH2Shell(host)),
      (callback = function (sessionText) {
        let list = [];
        list.push(sessionText);
        return list; // Return this call back
      })
    );
  } catch {
    console.log("error");
  }
  let resultList = await Promise.all(finalList);
  return resultList;
}

var test = sshFunction();
console.log(test);

结果:

error
Promise { <pending> }

【问题讨论】:

  • "...但目前有一个错误" 请edit你的问题显示你得到的确切错误。

标签: node.js asynchronous ssh promise


【解决方案1】:
async function sshFunction() {
  return new Promise(async (resolve, reject) => {
    var host;
    host = {
      server: {
        host: "xxx.xxx.xx.xx",
        port: "xx",
        userName: "",
        password: "",
        passPhrase: "",
        privateKey: fs.readFileSync(`./xx.cer`),
      },
      commands: ["echo $(pwd)", "ls -l"],
    };

    SSH = new SSH2Shell(host);

    SSH.connect((sessionText) => {
      const data = sessionText;
      resolve(data);
    });
  });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-20
    • 1970-01-01
    • 2017-05-21
    • 2021-12-17
    • 1970-01-01
    • 2013-09-27
    相关资源
    最近更新 更多