在meteor中读取shell命令的输出

Read output of shell command in meteor

本文关键字:命令 输出 shell 读取 meteor      更新时间:2023-09-26

我正在尝试ping远程服务器以检查它是否在线。流程如下:

1) User insert target Hostname

2)流星执行命令'nmap -p 22 hostname'

3)流星读取并解析输出,以检查目标的状态。

我已经能够异步执行命令,例如mkdir,这允许我稍后验证它是否工作。

不幸的是,我似乎无法等待回复。我的代码,内部/服务器/轮询器。咖啡是:

Meteor.methods
 check_if_open: (target_server) ->
     result = ''
     exec = Npm.require('child_process').exec
     result = exec 'nmap -p ' + target_server.port + ' ' + target_server.host
     return result

应该同步执行exec,不是吗?任何其他使用Futures、ShellJS、AsyncWrap的方法都会失败,因为一旦安装了节点包,meteor就会拒绝启动。似乎我只能通过流星添加(mrt)安装。

客户端代码,位于/client/views/home/home。咖啡,是:

Template.home.events 
    'submit form': (e) ->
        e.preventDefault()
        console.log "Calling the connect button"
        server_target =
           host: $(e.target).find("[name=hostname]").val()
           port: $(e.target).find("[name=port]").val()
           password: $(e.target).find("[name=password]").val()

        result = ''
        result = Meteor.call('check_if_open', server_target)
        console.log "You pressed the connect button" 
        console.log ' ' + result

结果总是null。Result应该是子进程对象,并具有stdout属性,但该属性为空。

我做错了什么?我如何读取输出?我被迫以异步方式完成?

您需要使用某种异步包装,child_process.exec是严格异步的。以下是如何使用期货:

# In top-level code:
# I didn't need to install anything with npm,
# this just worked.
Future = Npm.require("fibers/future")
# in the method:
fut = new Future()
# Warning: if you do this, you're probably vulnerable to "shell injection"
# e.g. the user might set target_server.host to something like "blah.com; rm -rf /"
exec "nmap -p #{target_server.port} #{target_server.host}", (err, stdout, stderr) ->
  fut.return [err, stdout, stderr]
[err, stdout, stderr] = fut.wait()
if err?
  throw new Meteor.Error(...)
# do stuff with stdout and stderr
# note that these are Buffer objects, you might need to manually
# convert them to strings if you want to send them to the client

当你在客户端调用方法时,你必须使用异步回调。客户端没有光纤

console.log "You pressed the connect button"
Meteor.call "check_if_open", server_target, (err, result) ->
  if err?
    # handle the error
  else
    console.log result