You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js telnet-client执行命令后如何将结果返回至主函数

Node.js telnet-client 命令响应返回主函数的解决方法

你的核心问题是telnet-client的事件回调是异步执行的,直接在exec回调里return response无法把值传递到主函数的返回值中——主函数会在事件触发前就执行完return逻辑,甚至你原代码里的return response还存在未定义变量的问题。

解决思路是把整个telnet连接、命令执行的逻辑包装成Promise,利用async/await的特性捕获异步操作的结果,具体修改如下:

const testTelnet = async (host, dns) => {
  process.on('unhandledRejection', error => {
    console.log("**TELNET CONNECTION ERROR ***", error);
  });

  const params = {
    host: host,
    port: 23,
    shellPrompt: '#',
    negotiationMandatory: false,
    loginPrompt: dns + ' login:',
    username: user, // 确保user变量已提前定义
    password: password, // 确保password变量已提前定义
    failedLoginMatch: '/error en autenticacion/',
    timeout: 5000,
  };

  // 将telnet操作包装为Promise,实现异步结果的传递
  return new Promise((resolve, reject) => {
    // 连接就绪后执行命令
    connection.on('ready', prompt => {
      connection.exec(cmd, (err, response) => {
        if (err) {
          reject(err); // 命令执行出错时抛出错误
          connection.end();
          return;
        }
        console.log("prompt", prompt);
        console.log(response);
        resolve(response); // 将命令响应作为Promise结果返回
        connection.end(); // 执行完成后主动关闭连接
      });
    });

    // 超时处理
    connection.on('timeout', () => {
      console.log('socket timeout!');
      reject(new Error('Telnet connection timeout'));
      connection.end();
    });

    // 连接意外关闭处理
    connection.on('close', () => {
      console.log('connection closed');
      reject(new Error('Telnet connection closed unexpectedly'));
    });

    // 连接错误处理
    connection.on('error', (err) => {
      console.log('Connection error:', err);
      reject(err);
    });

    // 发起telnet连接
    connection.connect(params);
  });
};

// 调用示例
// testTelnet('目标主机地址', 'DNS标识')
//   .then(finalResponse => console.log('最终响应:', finalResponse))
//   .catch(err => console.error('操作失败:', err));

关键修改说明

  • 用Promise包裹整个telnet流程,通过resolve传递成功的命令响应,reject传递各类错误(超时、连接失败、命令执行出错等)
  • 所有异常场景都做了错误抛出处理,确保主函数能捕获到问题
  • 命令执行完成后主动关闭连接,避免资源占用
  • 主函数直接返回这个Promise,外部可以通过await或.then()获取最终结果

内容的提问来源于stack exchange,提问作者Gabriel Mata

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 11:10:24