Advertisement
Guest User

Untitled

a guest
Dec 6th, 2024
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const WebSocket = require('ws');
  2. const ssh2 = require('ssh2');
  3. const http = require('http');
  4.  
  5. // Create an HTTP server to serve WebSocket connections
  6. const server = http.createServer((req, res) => {
  7.     res.writeHead(200, { 'Content-Type': 'text/plain' });
  8.     res.end('WebSocket server is running\n');
  9. });
  10.  
  11. // Create a WebSocket server attached to the HTTP server
  12. const wss = new WebSocket.Server({ server });
  13.  
  14. // WebSocket connection handling
  15. wss.on('connection', (ws) => {
  16.     console.log('WebSocket connection established');
  17.  
  18.     let conn = null; // Declare SSH client outside to manage lifecycle
  19.  
  20.     ws.on('message', (message) => {
  21.         try {
  22.             const data = JSON.parse(message); // Try parsing the incoming message as JSON
  23.  
  24.             // Check if message contains SSH connection details
  25.             if (data.host && data.username && data.password) {
  26.                 if (conn) {
  27.                     conn.end(); // Close any previous connection before starting a new one
  28.                 }
  29.  
  30.                 conn = new ssh2.Client(); // Create a new SSH connection instance
  31.  
  32.                 // When the SSH connection is ready
  33.                 conn.on('ready', () => {
  34.                     console.log('SSH Connection established');
  35.  
  36.                     // Start an interactive shell session
  37.                     conn.shell((err, stream) => {
  38.                         if (err) {
  39.                             console.log(`SSH Error: ${err}`);
  40.                             ws.send(`Error: ${err}`);
  41.                             return;
  42.                         }
  43.  
  44.                         // Handle data from SSH session
  45.                         stream.on('data', (data) => {
  46.                             console.log(`SSH Output: ${data}`);
  47.                             ws.send(data.toString()); // Send the SSH output back to WebSocket client
  48.                         });
  49.  
  50.                         // Handle stream close event
  51.                         stream.on('close', () => {
  52.                             console.log('SSH stream closed');
  53.                             conn.end();
  54.                         });
  55.  
  56.                         // When the WebSocket client sends a message (from terminal input), forward it to the SSH stream
  57.                         ws.on('message', (message) => {
  58.                             console.log(`Received message from WebSocket: ${message}`);
  59.                             stream.write(message); // Write the message (input) to the SSH shell
  60.                         });
  61.                     });
  62.                 }).on('error', (err) => {
  63.                     console.log('SSH Connection Error: ', err);
  64.                     ws.send(`SSH Error: ${err}`);
  65.                 }).connect({
  66.                     host: data.host,       // Host provided from the client
  67.                     port: 22,              // Default SSH port
  68.                     username: data.username,  // Username provided from the client
  69.                     password: data.password,  // Password provided from the client
  70.                     keepaliveInterval: 10000,  // Send a heartbeat every 10 seconds
  71.                     keepaliveCountMax: 5,      // Allow three missed heartbeats before considering the connection dead
  72.                 });
  73.             }
  74.         } catch (error) {
  75.             // If message is not valid JSON (i.e., terminal input), treat it as raw text and send it to SSH
  76.             console.log('Received non-JSON message, sending to SSH session:', message);
  77.             if (conn) {
  78.                 const stream = conn._stream; // Access the SSH stream directly
  79.                 if (stream && stream.writable) {
  80.                     stream.write(message); // Write raw input message to SSH stream
  81.                 }
  82.             } else {
  83.                 console.error('SSH connection is not established yet.');
  84.             }
  85.         }
  86.     });
  87.  
  88.     // Handle WebSocket close event
  89.     ws.on('close', () => {
  90.         console.log('WebSocket closed');
  91.         if (conn) {
  92.             conn.end(); // Close SSH connection when WebSocket client disconnects
  93.         }
  94.     });
  95. });
  96.  
  97. // Start the WebSocket server on port 8081
  98. server.listen(8081, () => {
  99.     console.log('WebSocket server is listening on ws://localhost:8081');
  100. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement