【发布时间】:2014-09-17 08:00:19
【问题描述】:
我在项目中编写 ssh2 模块时遇到了麻烦。我试图在一个终端上运行多个命令来统治远程 Linux 系统。例如“bc”命令为您提供了一个基本的计算器,您可以运行它进行基本操作。但是这种进程在你使用时需要保持清醒(它会接受两个或更多输入,并会给出响应)。
我需要创建一个类似 websocket 和 ssh 的系统。当 websocket 接收到命令时,ssh 节点需要执行这个消息,并且 Module 需要通过 websocket.send() 发送它的响应
我正在使用 Node.js websocket,ssh2 客户端。
这是我的代码:
#!/usr/bin/node
var Connection = require('ssh2');
var conn = new Connection();
var command="";
var http = require('http');
var WebSocketServer = require('websocket').server;
var firstcom=true;
conn.on('ready', function() {
console.log('Connection :: ready');
// conn.shell(onShell);
});
var onShell = function(err, stream) {
// stream.write(command+'\n');
stream.on('data', function(data) {
console.log('STDOUT: ' + data);
});
stream.stderr.on('data', function(data) {
console.log('STDERR: ' + data);
});
}
var webSocketsServerPort=5000;
var ssh2ConnectionControl=false;
var server = http.createServer(function (req, res) {
//blahbalh
}).listen(webSocketsServerPort, function() {
console.log((new Date()) + " Server is listening on port:: " + webSocketsServerPort);
});
//console.log((new Date()) + 'server created');
wsServer = new WebSocketServer({
httpServer: server,
// autoAcceptConnections: false
});
wsServer.on('request', function(request) {
console.log((new Date()) + ' Connection from origin ' + request.origin + '.');
var wsconnection = request.accept('echo-protocol', request.origin);
console.log((new Date()) + ' Connection accepted.');
if(!ssh2ConnectionControl){
conn.connect({
host: 'localhost',
port: 22,
username: 'attilaakinci',
password: '1'
});
ssh2ConnectionControl=true;
console.log('SSH Connected.');
}
wsconnection.on('message', function(message) {
if (message.type === 'utf8') {
console.log('Received Message: ' + message.utf8Data);
command=message.utf8Data;
//if(firstcom){
// conn.shell(onShell);
// firstcom=false;
//}else{
conn.exec(message.utf8Data,onShell);
//}
wsconnection.send(message.utf8Data);
}
else{
console.log('Invalid message');
}
});
wsconnection.on('close', function(reasonCode, description) {
console.log((new Date()) + ' Peer ' + wsconnection.remoteAddress + ' disconnected.');
});
});
【问题讨论】:
-
这段代码在不同的shell上执行命令我在检查终端进程ID时意识到了这种情况。所以我失去了 ssh 连接的使用。我需要在同一个终端上执行它们。请帮我解决这个问题。非常感谢..
标签: javascript node.js shell ssh websocket