2014-05-20 41 views
2

我試圖ping一個遠程服務器來檢查它是否在線。流動是這樣的:在流星中讀取shell命令的輸出

1)用戶插入目標主機名

2)流星執行命令「NMAP -p 22的主機名」

3)流星讀取和解析的輸出,以檢查的狀態目標。

我已經能夠異步執行一個命令,例如mkdir,它允許我稍後驗證它的工作。

不幸的是,我似乎無法等待答覆。我的代碼在/server/poller.coffee裏面是:

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的任何其他方法都會因爲流星節點安裝後拒絕啓動而失敗。看來我只能通過流星添加(mrt)來安裝。

我的客戶端代碼,位於/client/views/home/home.coffee是:

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 

結果總是空。結果應該是一個子進程對象,並且具有一個stdout屬性,但該屬性爲null。

我在做什麼錯?我如何讀取輸出?我不得不異步執行它?

回答

2

你需要使用某種異步包裝,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 
+0

我想我是在做點什麼。我試圖將緩衝區轉換爲字符串,然後我可以驗證您的答案。 – Mascarpone

+0

它可以工作,但格式不正確。我使用toString(),你有更好的建議嗎? – Mascarpone

+0

這可能值得開一個不同的問題。非常感謝你的幫助 !!! – Mascarpone