I have three Ubuntu servers, let's call them A, B, C. On server A, I have installed node.js and socket.io. On server B, I have installed apache and php. I would like to send a socket.io event through php from server B to server A. When the event is fired, server A would ssh to server C and run the 'reboot' command.
I have successfully set node.js up.
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")
});
});
});
I can send the event successfully, and server C restarts, but I can only send the event once. On the second attempt the request won't reach the 'ready' state. It can be seen in the log:
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
What shall I do?
According to Joe's comment I had to reassign c = new Connection().
And that's it.