bat_manage

This commit is contained in:
z66
2025-08-22 17:31:14 +08:00
commit 92afcbd14f
6 changed files with 548 additions and 0 deletions
+181
View File
@@ -0,0 +1,181 @@
from flask import Flask, render_template, request, jsonify
import os
import subprocess
import json
import threading
import time
from urllib.parse import unquote
app = Flask(__name__)
# 配置
TASKS_DIR = os.path.join(os.getcwd(), 'tasks')
CONFIG_FILE = 'config.json'
LOG_LINES = 200
# 全局变量
SCRIPT_CONFIGS = {}
running_processes = {}
script_outputs = {}
os.makedirs(TASKS_DIR, exist_ok=True)
def load_configs():
global SCRIPT_CONFIGS
try:
if os.path.exists(CONFIG_FILE):
with open(CONFIG_FILE, 'r', encoding='utf-8') as f:
SCRIPT_CONFIGS = json.load(f)
if not isinstance(SCRIPT_CONFIGS, dict):
SCRIPT_CONFIGS = {}
except:
SCRIPT_CONFIGS = {}
def save_configs():
with open(CONFIG_FILE, 'w', encoding='utf-8') as f:
json.dump(SCRIPT_CONFIGS, f, indent=2, ensure_ascii=False)
def get_script_path(script_name):
return os.path.join(TASKS_DIR, script_name)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/api/scripts')
def api_scripts():
if not os.path.exists(TASKS_DIR):
return jsonify([])
files = []
for f in os.listdir(TASKS_DIR):
path = os.path.join(TASKS_DIR, f)
if os.path.isfile(path) and f.endswith(('.bat', '.py')):
files.append(f)
return jsonify(sorted(files))
@app.route('/api/config')
def api_get_config():
return jsonify(SCRIPT_CONFIGS)
@app.route('/api/config', methods=['POST'])
def api_save_config():
try:
data = request.get_json()
if not isinstance(data, dict):
return jsonify({"error": "Invalid data format"}), 400
for script_name, config in data.items():
SCRIPT_CONFIGS[script_name] = config
save_configs()
return jsonify({"msg": "配置已保存"})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/api/start/<script_name>')
def api_start_script(script_name):
script_name = unquote(script_name)
if script_name not in SCRIPT_CONFIGS:
return jsonify({"error": "未找到配置"}), 404
if script_name in running_processes:
return jsonify({"error": "已在运行"}), 400
script_path = get_script_path(script_name)
if not os.path.exists(script_path):
return jsonify({"error": f"脚本不存在: {script_path}"}), 404
if script_name.endswith('.bat'):
cmd = ['cmd', '/c', script_path]
elif script_name.endswith('.py'):
cmd = ['python', script_path]
else:
return jsonify({"error": "不支持的类型"}), 400
def target():
try:
proc = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
stdin=subprocess.PIPE,
text=True,
encoding='utf-8',
cwd=TASKS_DIR
)
running_processes[script_name] = proc
script_outputs[script_name] = []
while True:
line = proc.stdout.readline()
if line:
line = f"[{time.strftime('%H:%M:%S')}] {line.strip()}"
script_outputs[script_name].append(line)
script_outputs[script_name] = script_outputs[script_name][-LOG_LINES:]
if proc.poll() is not None:
break
except Exception as e:
script_outputs.setdefault(script_name, []).append(f"❌ 执行错误: {e}")
finally:
running_processes.pop(script_name, None)
thread = threading.Thread(target=target, daemon=True)
thread.start()
return jsonify({"msg": f"✅ 开始执行: {script_name}"})
@app.route('/api/stop/<script_name>')
def api_stop_script(script_name):
script_name = unquote(script_name)
if script_name not in running_processes:
return jsonify({"msg": "未在运行"})
proc = running_processes[script_name]
proc.terminate()
try:
proc.wait(timeout=5)
except:
proc.kill()
running_processes.pop(script_name, None)
script_outputs.setdefault(script_name, []).append("⏹️ 已停止")
return jsonify({"msg": f"⏹️ 已停止: {script_name}"})
@app.route('/api/status/<script_name>')
def api_status(script_name):
script_name = unquote(script_name)
output = script_outputs.get(script_name, [])
is_running = script_name in running_processes
return jsonify({
"running": is_running,
"output": output
})
@app.route('/api/send-input/<script_name>', methods=['POST'])
def api_send_input(script_name):
script_name = unquote(script_name)
if script_name not in running_processes:
return jsonify({"error": "脚本未运行"}), 400
proc = running_processes[script_name]
try:
proc.stdin.write(request.data + "\n")
proc.stdin.flush()
return jsonify({"msg": "输入已发送"})
except Exception as e:
return jsonify({"error": str(e)}), 500
if __name__ == '__main__':
load_configs()
app.run(host='0.0.0.0', port=5000, debug=False)
+16
View File
@@ -0,0 +1,16 @@
{
"3.bat": {
"script": "3.bat",
"mode": "interval",
"interval": "1",
"unit": "hours"
},
"2.bat": {
"script": "2.bat",
"mode": "long-running"
},
"1.bat": {
"script": "1.bat",
"mode": "long-running"
}
}
+25
View File
@@ -0,0 +1,25 @@
@echo off
chcp 65001 > nul
:: 脚本1: 显示基本系统信息
title 系统信息报告
color 0a
echo.
echo =============================
echo 系统信息概览
echo =============================
echo.
echo 当前时间: %time%
echo 当前日期: %date%
echo 计算机名: %computername%
echo 用户名: %username%
echo 操作系统: %os%
echo.
echo 驱动器 C: 可用空间:
for /f "tokens=3" %%a in ('dir c:\ ^| find "可用字节"') do set "free=%%a"
echo %free%
echo.
echo =============================
echo 报告生成于 %date% %time%
echo =============================
pause
+5
View File
@@ -0,0 +1,5 @@
@echo off
:loop
set /p input=Enter something:
echo [%time%] User input: %input%
goto loop
+32
View File
@@ -0,0 +1,32 @@
@echo off
chcp 65001 > nul
:: 脚本4: 网络诊断测试
title 网络连接测试
color 0e
echo 网络连接诊断工具
echo =============================
echo 1. 测试本地回环 (127.0.0.1)...
ping -n 2 -w 100 127.0.0.1 > nul && echo [OK] 本地回环正常。 || echo [FAIL] 本地回环失败!
echo 2. 测试网关连接...
for /f "tokens=2 delims=[]" %%a in ('route print ^| find " 0.0.0.0" ^| find "0.0.0.0"') do set gateway=%%a
if defined gateway (
echo 网关地址: %gateway%
ping -n 2 -w 500 %gateway% > nul && echo [OK] 网关可达。 || echo [FAIL] 无法连接到网关!
) else (
echo [ERROR] 无法获取网关地址。
)
echo 3. 测试 DNS 解析 (Google DNS: 8.8.8.8)...
nslookup google.com 8.8.8.8 > nul && echo [OK] DNS 解析成功。 || echo [FAIL] DNS 解析失败!
echo 4. 测试外部连接 (www.baidu.com)...
ping -n 2 -w 1000 www.baidu.com > nul && echo [OK] 可访问外部网络。 || echo [FAIL] 无法访问外部网络!
echo.
echo =============================
echo 测试完成。
echo 诊断时间: %time%
echo =============================
pause
+289
View File
@@ -0,0 +1,289 @@
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>脚本管理平台</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
<style>
body {
font-family: 'Segoe UI', sans-serif;
background-color: #f8f9fa;
padding: 20px;
}
.main-container {
display: grid;
grid-template-columns: 250px 1fr;
gap: 15px;
height: calc(100vh - 40px);
}
#script-list-panel {
background: white;
border-radius: 8px;
padding: 15px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
overflow-y: auto;
}
#output-area {
background: #000;
color: #0f0;
font-family: 'Consolas', monospace;
padding: 15px;
border-radius: 8px;
overflow-y: auto;
height: calc(100% - 220px);
}
#config-panel {
background: white;
border-radius: 8px;
padding: 15px;
margin-top: 15px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.script-item {
padding: 10px;
margin-bottom: 10px;
border-left: 3px solid transparent;
border-radius: 4px;
background: #f8f9fa;
cursor: pointer;
}
.script-item:hover {
background: #e9ecef;
}
.script-item.active {
border-left-color: #0d6efd;
background: #e9ecef;
}
.status-indicator {
display: inline-block;
width: 10px;
height: 10px;
border-radius: 50%;
margin-right: 6px;
}
.status-running { background: #198754; }
.status-stopped { background: #dc3545; }
.form-control, .form-select {
margin-bottom: 10px;
}
</style>
</head>
<body>
<h4 class="mb-3">脚本管理平台</h4>
<div class="main-container">
<!-- 左侧脚本列表 -->
<div id="script-list-panel">
<div class="d-flex justify-content-between align-items-center mb-3">
<h5>脚本列表</h5>
<button class="btn btn-sm btn-outline-secondary" onclick="loadScripts()">
<i class="bi bi-arrow-clockwise"></i> 刷新
</button>
</div>
<div id="script-list"></div>
</div>
<!-- 右侧主区域 -->
<div>
<!-- 输出控制台 -->
<div id="output-area"></div>
<!-- 配置面板 -->
<div id="config-panel">
<h5>脚本配置</h5>
<form id="config-form">
<div class="mb-3">
<label class="form-label">选择脚本</label>
<select class="form-select" id="config-script" required>
<option value="">请选择脚本...</option>
</select>
</div>
<div class="mb-3">
<label class="form-label">运行模式</label>
<select class="form-select" id="config-mode">
<option value="long-running">长期运行</option>
<option value="interval">定时执行</option>
</select>
</div>
<div id="interval-config" style="display: none;">
<label class="form-label">执行周期</label>
<div class="input-group">
<input type="number" class="form-control" id="config-interval" value="1" min="1">
<select class="form-select" id="config-unit">
<option value="minutes">分钟</option>
<option value="hours">小时</option>
<option value="days"></option>
</select>
</div>
</div>
<button type="submit" class="btn btn-primary w-100">
<i class="bi bi-save"></i> 保存配置
</button>
</form>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
let currentScript = null;
let allScripts = [];
// 加载脚本列表
function loadScripts() {
$.get('/api/scripts', function(files) {
allScripts = files;
renderScriptList();
const select = $('#config-script');
select.empty().append('<option value="">请选择脚本...</option>');
files.forEach(f => select.append(`<option value="${f}">${f}</option>`));
if (currentScript) {
select.val(currentScript);
loadConfig(currentScript);
}
});
}
// 渲染脚本列表
function renderScriptList() {
const container = $('#script-list').empty();
allScripts.forEach(scriptName => {
$.get(`/api/status/${encodeURIComponent(scriptName)}`, function(status) {
const isRunning = status.running;
const isActive = currentScript === scriptName;
const item = $(`
<div class="script-item ${isActive ? 'active' : ''}" onclick="selectScript('${scriptName}')">
<div class="d-flex justify-content-between align-items-center">
<div>
<span class="status-indicator ${isRunning ? 'status-running' : 'status-stopped'}"></span>
<strong>${scriptName}</strong>
</div>
<button class="btn btn-sm ${isRunning ? 'btn-danger' : 'btn-success'}"
onclick="event.stopPropagation(); ${isRunning ? `stopScript('${scriptName}')` : `startScript('${scriptName}')`}">
${isRunning ? '<i class="bi bi-stop-fill"></i>' : '<i class="bi bi-play-fill"></i>'}
${isRunning ? '停止' : '启动'}
</button>
</div>
</div>
`);
container.append(item);
});
});
if (currentScript) updateOutput();
}
// 选择脚本
function selectScript(name) {
currentScript = name;
$('.script-item').removeClass('active');
$(`.script-item:contains('${name}')`).addClass('active');
$('#config-script').val(name);
loadConfig(name);
updateOutput();
}
// 加载配置
function loadConfig(scriptName) {
$.get('/api/config', function(configs) {
const config = configs[scriptName];
if (config) {
$('#config-mode').val(config.mode || 'long-running');
toggleInterval(config.mode);
if (config.mode === 'interval') {
$('#config-interval').val(config.interval || 1);
$('#config-unit').val(config.unit || 'hours');
}
}
});
}
// 切换间隔配置显示
function toggleInterval(mode) {
$('#interval-config').toggle(mode === 'interval');
}
// 启动脚本
function startScript(name) {
$.get(`/api/start/${encodeURIComponent(name)}`, function(res) {
renderScriptList();
}).fail(function(xhr) {
alert('启动失败: ' + (xhr.responseJSON?.error || xhr.statusText));
});
}
// 停止脚本
function stopScript(name) {
$.get(`/api/stop/${encodeURIComponent(name)}`, function() {
renderScriptList();
});
}
// 更新输出
function updateOutput() {
if (!currentScript) return;
$.get(`/api/status/${encodeURIComponent(currentScript)}`, function(res) {
const output = $('#output-area').empty();
res.output.forEach(line => {
output.append($('<div>').text(line).addClass('output-line'));
});
output.scrollTop(output[0].scrollHeight);
});
}
// 保存配置
$('#config-form').submit(function(e) {
e.preventDefault();
const scriptName = $('#config-script').val();
if (!scriptName) return alert('请选择脚本');
const config = {
script: scriptName,
mode: $('#config-mode').val()
};
if (config.mode === 'interval') {
config.interval = $('#config-interval').val();
config.unit = $('#config-unit').val();
}
$.ajax({
url: '/api/config',
method: 'POST',
contentType: 'application/json',
data: JSON.stringify({ [scriptName]: config })
}).done(function() {
alert('配置已保存');
renderScriptList();
}).fail(function(xhr) {
alert('保存失败: ' + (xhr.responseJSON?.error || xhr.statusText));
});
});
// 初始化
$(function() {
loadScripts();
$('#config-mode').change(function() {
toggleInterval($(this).val());
});
// 每2秒更新状态
setInterval(() => {
if (currentScript) updateOutput();
}, 2000);
});
</script>
</body>
</html>