0

我有三台 Ubuntu 服务器,我们称它们为 A、B、C。在服务器 A 上,我安装了 node.js 和 socket.io。在服务器 B 上,我已经安装了 apache 和 php。我想通过php从服务器B向服务器A发送一个socket.io事件。当事件被触发时,服务器A将ssh到服务器C并运行'reboot'命令。

我已成功设置 node.js。

var Connection = require("ssh2");
var sys = require("sys");
var exec = require("child_process").exec;
var io = require("socket.io").listen(81);
var c = new Connection();

c.on("connect", function(){
    console.log("Connection :: connect");
});

c.on("ready", function(){
    console.log("Connection :: ready");
    c.exec("reboot", function(err, stream){
            if(err) throw err;
            stream.on("data", function(data, extended){
                    console.log((extended === "stderr" ? "STDERR: " : "STDOUT: ") + data);
            });
            stream.on("end", function(){
                    console.log("Stream :: EOF");
            });
            stream.on("close", function(){
                    console.log("Stream :: close");
            });
            stream.on("exit", function(code, signal){
                    console.log("Stream :: exit :: code: " + code + ", signal: " + signal);
                    c.end();
            });
    });
});

c.on("error", function(err){
    console.log("Connection :: error :: " + err);
});

c.on("end", function(){
    console.log("Connection :: end");
});

c.on("close", function(had_error){
    console.log("Console :: close");
});

io.sockets.on("connection", function (socket) {
    socket.on("my_event", function (data) {
        c.connect({
           host: data.ip,
           port: 22,
           username: "root",
           privateKey: require("fs").readFileSync("/root/.ssh/id")
        });
    });
});

我可以成功发送事件,服务器C重新启动,但我只能发送一次事件。在第二次尝试时,请求不会达到“就绪”状态。在日志中可以看到:

info  - socket.io started
debug - client authorized .......
Connection :: connect
debug - got disconnection packet ......
Connection :: ready
Stream :: exit :: code: 0, signal: undefined
Stream :: EOF
Stream :: close
Connection :: end
Console :: close

debug - client authorized .......
Connection :: connect
debug - got disconnection packet ......
Connection :: end
Console :: close

我该怎么办?

4

1 回答 1

0

根据乔的评论,我不得不重新分配c = new Connection(). 就是这样。

于 2014-01-29T14:42:41.620 回答