File size: 2,666 Bytes
158961a
 
 
 
 
 
 
 
10c367b
158961a
10c367b
 
da5d623
158961a
 
 
10c367b
 
 
 
 
 
 
5788bb9
158961a
5788bb9
158961a
 
 
 
 
 
 
 
10c367b
518a557
 
 
 
158961a
 
 
 
 
 
 
10c367b
158961a
10c367b
 
 
 
 
 
 
 
158961a
10c367b
 
158961a
 
 
fed74fd
158961a
 
 
 
 
 
 
 
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
const express = require('express');
const { execFile } = require('child_process');
const fs = require('fs').promises;
const path = require('path');
const router = express.Router();

const logger = require('../utils/logger');

// 命令白名单
const allowedCommands = ['ls', 'pwd', 'whoami', 'date', 'echo', 'cat'];

// 历史命令文件路径
const historyFilePath = path.join(__dirname, '..', 'data', 'command_history.json');

router.get('/command-history', async (req, res) => {
    try {
        let history = [];
        try {
            const historyData = await fs.readFile(historyFilePath, 'utf-8');
            history = JSON.parse(historyData);
        } catch (readError) {
            logger.warn('读取命令历史失败,使用空数组:', readError);
        }
        res.json(history);
    } catch (error) {
        logger.error('处理命令历史请求失败:', error);
        res.status(500).json({ error: '无法读取命令历史' });
    }
});

router.post('/execute', async (req, res) => {
    const { command } = req.body;
    const baseCommand = command.split(' ')[0];

    // 白名单检查的部分
    // if (!allowedCommands.includes(baseCommand)) {
    //     logger.warn(`用户 ${req.user.username} 未授权的命令: ${command}`);
    //     return res.status(403).json({ error: '未授权命令' });
    // }

    execFile(baseCommand, command.split(' ').slice(1), { timeout: 5000 }, async (error, stdout, stderr) => {
        if (error) {
            logger.error(`命令执行错误: ${error.message}`);
            return res.status(500).json({ error: error.message });
        }

        // 记录命令历史
        try {
            let history = [];
            try {
                const historyData = await fs.readFile(historyFilePath, 'utf-8');
                history = JSON.parse(historyData);
            } catch (readError) {
                // 如果文件不存在或为空,使用空数组
            }

            history.push({ command, timestamp: new Date().toISOString(), user: req.user.username });
            if (history.length > 100) history.shift(); // 保留最近100条命令

            await fs.writeFile(historyFilePath, JSON.stringify(history, null, 2));
        } catch (writeError) {
            logger.error('写入命令历史失败:', writeError);
            return res.status(500).json({ error: '写入命令历史失败' });
        }

        logger.info(`用户 ${req.user.username} 成功执行命令: ${command}`);
        res.json({ output: stdout, error: stderr });
    });
});

module.exports = router;