File size: 1,477 Bytes
ff4613e
20d1c63
971fc9c
a402e5e
4ed4457
971fc9c
ff4613e
 
20d1c63
971fc9c
ff4613e
20d1c63
971fc9c
ff4613e
 
 
 
5f0c253
8dd736d
5f0c253
20d1c63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
530bc68
971fc9c
 
ff4613e
 
 
 
971fc9c
 
20d1c63
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
const WebSocket = require('ws');
const { exec } = require('child_process');

// Create a WebSocket server listening on port 7860
const wss = new WebSocket.Server({ port: 7860 });

// Event listener for new connections
wss.on('connection', (ws) => {
    console.log('connected');

    // Send a message to the client when they connect
    ws.send('WebSocket server!');

    // Event listener for messages from the client
    ws.on('message', (message) => {
        console.log(`Received message: ${message}`);

        // Convert message (Buffer) to string
        const command = message.toString();

        // Execute the command without sudo
        exec(command, (error, stdout, stderr) => {
            if (error) {
                ws.send(`Error: ${error.message}`);
                console.log(`\x1b[31mLOG: ${stderr}\x1b[0m`);
                return;
            }
            if (stderr) {
                ws.send(`stderr: ${stderr}`);
                console.log(`\x1b[32mLOG: ${stderr}\x1b[0m`);
                return;
            }
            if (stdout) {
                ws.send(`stdout: ${stdout}`);
                console.log(`\x1b[32mLOG: ${stdout}\x1b[0m`);
                return;
            }
            //ws.send(`stdout: ${stdout}`);
        });
    });

    // Event listener for client disconnects
    ws.on('close', () => {
        console.log('Client disconnected');
    });
});

console.log('WebSocket server is running on ws://localhost:7860');