Node.js ssh不会再运行

时间:2013-06-20 11:47:33

标签: node.js ssh socket.io

我有三个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

我该怎么办?

1 个答案:

答案 0 :(得分:0)

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