我正在尝试创建一个连接到远程主机的Web终端,并允许运行正常的终端命令。我能够连接到远程服务器并且我理解stream.write(data)应该是触发命令在远程服务器上运行并返回输出的内容,但是我将输入返回到前端。 / p>
term.html
<!doctype html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="/socket.io/socket.io.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">
var socket = io.connect('http://localhost:8080', {query: 'host=IP_Address&port=22&username=user&password=password'});
// Display the resonse from the server
function add_content(str){
console.log(str);
$('div').append('<p>' + $('<div/>').text(str).html() + '</p>');
$(window).scrollTop($('body').height() - $(window).height() + 80);
}
// Backend -> Browser
socket.on('server_data', function(data) {
add_content(data);
});
// Disconnect message
socket.on('disconnect', function() {
add_content('\r\n*** Disconnected from backend***\r\n');
});
// Browser -> Backend
$(function(){
$('form').submit(function(e){
e.preventDefault();
var input = $('input');
socket.emit('client_data', input.val());
input.val('');
return false;
});
$('input').focus();
});
</script>
<style type="text/css">
body, p, input {
font-family: fixed;
font-size: 13px;
border: none;
}
p { white-space: pre; }
p, form, input { margin:0; padding:0; }
input:focus { outline: none; border: none; }
</style>
</head>
<body>
<div></div>
<form>
> <input>
</form>
</body>
</html>
server.js
var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs');
var SSHClient = require('ssh2').Client;
var listener = app.listen(8080);
var current_directory = null;
function handler (req, res) {
fs.readFile(__dirname + '/term.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading term.html');
}
res.writeHead(200);
res.end(data);
});
}
io.on('connection', function(socket) {
var conn = new SSHClient();
conn.on('ready', function() {
socket.emit('server_data', '\r\n*** SSH CONNECTION ESTABLISHED ***\r\n');
conn.shell(function(err, stream) {
if (err)
return socket.emit('server_data', '\r\n*** SSH SHELL ERROR: ' + err.message + ' ***\r\n');
socket.on('client_data', function(data) {
stream.write(data);
});
stream.on('data', function(data) {
socket.emit('server_data', data.toString('binary'));
//console.log('STDOUT: ' + data);
}).stderr.on('data', function(data){
//console.log('STDERR: ' + data);
socket.emit('server_data', data.toString('binary'));
}).on('close', function() {
conn.end();
});
});
}).on('close', function() {
socket.emit('server_data', '\r\n*** SSH CONNECTION CLOSED ***\r\n');
}).on('error', function(err) {
socket.emit('server_data', '\r\n*** SSH CONNECTION ERROR: ' + err.message + ' ***\r\n');
}).connect({
host: socket.handshake.query.host,
port: socket.handshake.query.port,
username: socket.handshake.query.username,
password: socket.handshake.query.password
});
});