|
|
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];
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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();
|
|
|
|
|
|
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; |