inz

webssh.javascript (raw)

  1. var process = require('process');
  2.  
  3. // Hacks to get ssh2 working in browser
  4. process.binding = function () { return {} };
  5. process.version = '1.0.0';
  6.  
  7. var Client = require('ssh2/lib/client');
  8. var ws = require('websocket-stream');
  9. var xterm = require('xterm');
  10. var fit = require('xterm/lib/addons/fit/fit');
  11.  
  12. var conn = new Client();
  13. var term = new xterm();
  14. var chan;
  15. var wndopts = { term: 'xterm' };
  16.  
  17. window.term = term;
  18.  
  19. // Store current size for initialization
  20. term.on('resize', function (rev) {
  21. wndopts.rows = rev.rows;
  22. wndopts.cols = rev.cols;
  23. });
  24.  
  25. term.on('title', function (title) {
  26. document.title = title;
  27. });
  28.  
  29. conn.on('ready', function() {
  30. console.log('Client :: ready');
  31. chan = conn.shell(wndopts, function(err, stream) {
  32. if (err) throw err;
  33. stream.on('close', function() {
  34. console.log('Stream :: close');
  35. conn.end();
  36. }).on('data', function(data) {
  37. term.write(data.toString());
  38. }).stderr.on('data', function(data) {
  39. term.write(data.toString());
  40. });
  41. term.on('key', function (key, kev) {
  42. stream.write(key);
  43. });
  44. term.on('resize', function (rev) {
  45. stream.setWindow(rev.rows, rev.cols, 480, 640);
  46. });
  47. });
  48. }).on('error', function (err) {
  49. term.write(err.toString());
  50. }).on('close', function () {
  51. term.write('\r\nConnection lost.\r\n');
  52. });
  53.  
  54. var user = '', pass = '';
  55.  
  56. function read_pass (key, kev) {
  57. for (var i in key) {
  58. var c = key[i];
  59. switch (c.charCodeAt(0)) {
  60. case 127:
  61. pass = user.substring(0, user.length - 1);
  62. break;
  63. case 13:
  64. term.off('key', read_pass);
  65. term.write('\r\n');
  66. conn.connect({
  67. sock: ws('ws://localhost:8022', ['binary']),
  68. username: user,
  69. password: pass
  70. });
  71. default:
  72. pass += c;
  73. }
  74. }
  75. }
  76.  
  77. function read_user(key, kev) {
  78. for (var i in key) {
  79. var c = key[i];
  80. switch (c.charCodeAt(0)) {
  81. case 127:
  82. user = user.substring(0, user.length - 1);
  83. term.write('\033[D \033[D');
  84. break;
  85. case 13:
  86. term.off('key', read_user);
  87. term.write('\r\nPassword: ');
  88. term.on('key', read_pass);
  89. break;
  90. default:
  91. user += c;
  92. term.write(c);
  93. }
  94. }
  95. }
  96.  
  97. term.write('Login as: ');
  98. term.on('key', read_user);
  99.  
  100. term.open(document.getElementById('#terminal'));
  101. term.fit();
  102. window.onresize = term.fit.bind(term);
  103.