本文目录导读:

我来介绍几种实现插件批量管理脚本的方法,涵盖不同场景和编程语言。
Python 实现(通用方案)
基础版 - 插件管理器
#!/usr/bin/env python3
"""
插件批量管理脚本
功能:启用/禁用/安装/卸载/更新 插件
"""
import os
import json
import shutil
import argparse
from pathlib import Path
from typing import List, Dict
class PluginManager:
def __init__(self, plugin_dir: str, config_file: str = "plugins.json"):
self.plugin_dir = Path(plugin_dir)
self.config_file = self.plugin_dir / config_file
self.plugins = self._load_config()
def _load_config(self) -> Dict:
"""加载插件配置"""
if self.config_file.exists():
with open(self.config_file, 'r') as f:
return json.load(f)
return {"plugins": []}
def _save_config(self):
"""保存插件配置"""
self.plugin_dir.mkdir(exist_ok=True)
with open(self.config_file, 'w') as f:
json.dump(self.plugins, f, indent=2)
def list_plugins(self) -> List[Dict]:
"""列出所有插件"""
return self.plugins.get("plugins", [])
def enable_plugins(self, plugin_names: List[str]):
"""启用插件"""
for plugin in self.plugins["plugins"]:
if plugin["name"] in plugin_names:
plugin["enabled"] = True
print(f"已启用: {plugin['name']}")
self._save_config()
def disable_plugins(self, plugin_names: List[str]):
"""禁用插件"""
for plugin in self.plugins["plugins"]:
if plugin["name"] in plugin_names:
plugin["enabled"] = False
print(f"已禁用: {plugin['name']}")
self._save_config()
def install_plugin(self, plugin_name: str, plugin_source: str):
"""安装插件"""
new_plugin = {
"name": plugin_name,
"source": plugin_source,
"enabled": True,
"version": "1.0.0"
}
self.plugins["plugins"].append(new_plugin)
self._save_config()
print(f"已安装: {plugin_name}")
def uninstall_plugins(self, plugin_names: List[str]):
"""卸载插件"""
self.plugins["plugins"] = [
p for p in self.plugins["plugins"]
if p["name"] not in plugin_names
]
self._save_config()
print(f"已卸载: {', '.join(plugin_names)}")
def batch_operation(self, operation: str, plugins: List[str]):
"""批量操作"""
operations = {
"enable": self.enable_plugins,
"disable": self.disable_plugins,
"uninstall": self.uninstall_plugins
}
if operation in operations:
operations[operation](plugins)
# CLI 接口
def main():
parser = argparse.ArgumentParser(description="插件批量管理工具")
parser.add_argument("--dir", default="./plugins", help="插件目录")
subparsers = parser.add_subparsers(dest="command", help="可用命令")
# list 命令
subparsers.add_parser("list", help="列出所有插件")
# enable 命令
enable_parser = subparsers.add_parser("enable", help="启用插件")
enable_parser.add_argument("plugins", nargs="+", help="插件名称")
# disable 命令
disable_parser = subparsers.add_parser("disable", help="禁用插件")
disable_parser.add_argument("plugins", nargs="+", help="插件名称")
# install 命令
install_parser = subparsers.add_parser("install", help="安装插件")
install_parser.add_argument("name", help="插件名称")
install_parser.add_argument("source", help="插件来源")
# uninstall 命令
uninstall_parser = subparsers.add_parser("uninstall", help="卸载插件")
uninstall_parser.add_argument("plugins", nargs="+", help="插件名称")
# batch 命令
batch_parser = subparsers.add_parser("batch", help="批量操作")
batch_parser.add_argument("operation", choices=["enable", "disable", "uninstall"])
batch_parser.add_argument("plugins", nargs="+", help="插件名称列表")
args = parser.parse_args()
manager = PluginManager(args.dir)
if args.command == "list":
plugins = manager.list_plugins()
for p in plugins:
status = "✓" if p.get("enabled", False) else "✗"
print(f"[{status}] {p['name']} v{p.get('version', 'N/A')}")
elif args.command == "enable":
manager.enable_plugins(args.plugins)
elif args.command == "disable":
manager.disable_plugins(args.plugins)
elif args.command == "install":
manager.install_plugin(args.name, args.source)
elif args.command == "uninstall":
manager.uninstall_plugins(args.plugins)
elif args.command == "batch":
manager.batch_operation(args.operation, args.plugins)
if __name__ == "__main__":
main()
Shell 脚本方案(Linux/Unix)
#!/bin/bash
# ============================================
# 插件批量管理 Shell 脚本
# 适用于 Wordpress、Drupal 等 CMS 系统
# ============================================
# 配置
PLUGIN_DIR="/var/www/html/wp-content/plugins"
BACKUP_DIR="./plugin_backups"
# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
# 显示帮助信息
show_help() {
echo "用法: $0 [选项]"
echo "选项:"
echo " list 列出所有插件"
echo " enable <plugin>... 启用插件"
echo " disable <plugin>... 禁用插件"
echo " install <plugin_url> 安装插件"
echo " uninstall <plugin>... 卸载插件"
echo " backup <plugin>... 备份插件"
echo " restore <plugin>... 恢复插件"
echo " status 检查插件状态"
echo " update 更新所有插件"
}
# 列出所有插件
list_plugins() {
echo -e "${GREEN}已安装的插件:${NC}"
for dir in "$PLUGIN_DIR"/*/; do
if [ -d "$dir" ]; then
plugin_name=$(basename "$dir")
if [ -f "$dir/disabled" ]; then
echo -e " [${RED}禁用${NC}] $plugin_name"
else
echo -e " [${GREEN}启用${NC}] $plugin_name"
fi
fi
done
}
# 启用插件
enable_plugins() {
for plugin in "$@"; do
if [ -d "$PLUGIN_DIR/$plugin" ]; then
if [ -f "$PLUGIN_DIR/$plugin/disabled" ]; then
rm "$PLUGIN_DIR/$plugin/disabled"
echo -e "${GREEN}已启用: $plugin${NC}"
else
echo -e "${YELLOW}插件已启用: $plugin${NC}"
fi
else
echo -e "${RED}插件不存在: $plugin${NC}"
fi
done
}
# 禁用插件
disable_plugins() {
for plugin in "$@"; do
if [ -d "$PLUGIN_DIR/$plugin" ]; then
if [ ! -f "$PLUGIN_DIR/$plugin/disabled" ]; then
touch "$PLUGIN_DIR/$plugin/disabled"
echo -e "${YELLOW}已禁用: $plugin${NC}"
else
echo -e "${YELLOW}插件已禁用: $plugin${NC}"
fi
else
echo -e "${RED}插件不存在: $plugin${NC}"
fi
done
}
# 安装插件
install_plugin() {
local url="$1"
local tmp_file="/tmp/plugin.zip"
echo -e "${GREEN}正在下载插件...${NC}"
wget -O "$tmp_file" "$url"
if [ $? -eq 0 ]; then
unzip -o "$tmp_file" -d "$PLUGIN_DIR/"
rm "$tmp_file"
echo -e "${GREEN}插件安装完成${NC}"
else
echo -e "${RED}插件下载失败${NC}"
fi
}
# 卸载插件
uninstall_plugins() {
for plugin in "$@"; do
if [ -d "$PLUGIN_DIR/$plugin" ]; then
read -p "确认删除 $plugin? (y/n): " confirm
if [ "$confirm" = "y" ]; then
rm -rf "$PLUGIN_DIR/$plugin"
echo -e "${GREEN}已卸载: $plugin${NC}"
fi
else
echo -e "${RED}插件不存在: $plugin${NC}"
fi
done
}
# 备份插件
backup_plugins() {
mkdir -p "$BACKUP_DIR"
for plugin in "$@"; do
if [ -d "$PLUGIN_DIR/$plugin" ]; then
tar -czf "$BACKUP_DIR/${plugin}_$(date +%Y%m%d).tar.gz" \
-C "$PLUGIN_DIR" "$plugin"
echo -e "${GREEN}已备份: $plugin${NC}"
fi
done
}
# 恢复插件
restore_plugins() {
for backup in "$@"; do
if [ -f "$BACKUP_DIR/$backup" ]; then
tar -xzf "$BACKUP_DIR/$backup" -C "$PLUGIN_DIR/"
echo -e "${GREEN}已恢复: $backup${NC}"
else
echo -e "${RED}备份文件不存在: $backup${NC}"
fi
done
}
# 更新所有插件
update_plugins() {
echo -e "${YELLOW}正在检查插件更新...${NC}"
for dir in "$PLUGIN_DIR"/*/; do
if [ -d "$dir" ]; then
plugin_name=$(basename "$dir")
# 这里可以集成具体的更新逻辑
echo -e "${GREEN}已更新: $plugin_name${NC}"
fi
done
}
# 主程序
main() {
if [ $# -lt 1 ]; then
show_help
exit 1
fi
case "$1" in
list)
list_plugins
;;
enable)
shift
enable_plugins "$@"
;;
disable)
shift
disable_plugins "$@"
;;
install)
install_plugin "$2"
;;
uninstall)
shift
uninstall_plugins "$@"
;;
backup)
shift
backup_plugins "$@"
;;
restore)
shift
restore_plugins "$@"
;;
status)
list_plugins
;;
update)
update_plugins
;;
*)
echo -e "${RED}未知命令: $1${NC}"
show_help
exit 1
;;
esac
}
# 执行主程序
main "$@"
Node.js 方案(适用于前端项目)
#!/usr/bin/env node
const fs = require('fs-extra');
const path = require('path');
const { program } = require('commander');
const chalk = require('chalk');
class PluginManager {
constructor(pluginDir) {
this.pluginDir = pluginDir;
this.configFile = path.join(pluginDir, 'plugins.config.json');
this.plugins = this.loadConfig();
}
loadConfig() {
try {
if (fs.existsSync(this.configFile)) {
return JSON.parse(fs.readFileSync(this.configFile, 'utf8'));
}
} catch (error) {
console.error(chalk.yellow('加载配置文件失败,使用默认配置'));
}
return { plugins: [] };
}
saveConfig() {
fs.ensureDirSync(this.pluginDir);
fs.writeFileSync(this.configFile, JSON.stringify(this.plugins, null, 2));
}
listPlugins() {
const { plugins } = this.plugins;
if (plugins.length === 0) {
console.log(chalk.yellow('没有安装任何插件'));
return;
}
console.log(chalk.green('\n已安装的插件:'));
plugins.forEach(plugin => {
const status = plugin.enabled ? chalk.green('✓') : chalk.red('✗');
console.log(` [${status}] ${chalk.cyan(plugin.name)} v${plugin.version || '1.0.0'}`);
});
}
enablePlugins(pluginNames) {
this.plugins.plugins.forEach(plugin => {
if (pluginNames.includes(plugin.name)) {
plugin.enabled = true;
console.log(chalk.green(`已启用: ${plugin.name}`));
}
});
this.saveConfig();
}
disablePlugins(pluginNames) {
this.plugins.plugins.forEach(plugin => {
if (pluginNames.includes(plugin.name)) {
plugin.enabled = false;
console.log(chalk.yellow(`已禁用: ${plugin.name}`));
}
});
this.saveConfig();
}
async installPlugin(name, source) {
const newPlugin = {
name,
source,
enabled: true,
version: '1.0.0',
installedAt: new Date().toISOString()
};
this.plugins.plugins.push(newPlugin);
this.saveConfig();
console.log(chalk.green(`已安装: ${name}`));
// 如果提供了 source,可以执行安装逻辑
if (source) {
await this.downloadPlugin(name, source);
}
}
uninstallPlugins(pluginNames) {
this.plugins.plugins = this.plugins.plugins.filter(
plugin => !pluginNames.includes(plugin.name)
);
this.saveConfig();
// 删除插件文件
pluginNames.forEach(name => {
const pluginPath = path.join(this.pluginDir, name);
if (fs.existsSync(pluginPath)) {
fs.removeSync(pluginPath);
}
});
console.log(chalk.green(`已卸载: ${pluginNames.join(', ')}`));
}
async downloadPlugin(name, source) {
// 实现具体的下载逻辑
console.log(chalk.cyan(`正在下载: ${name}`));
}
batchOperation(operation, pluginNames) {
switch(operation) {
case 'enable':
this.enablePlugins(pluginNames);
break;
case 'disable':
this.disablePlugins(pluginNames);
break;
case 'uninstall':
this.uninstallPlugins(pluginNames);
break;
default:
console.log(chalk.red(`未知操作: ${operation}`));
}
}
}
// CLI 配置
program
.version('1.0.0')
.description('插件批量管理工具');
program
.command('list')
.description('列出所有插件')
.action(() => {
const manager = new PluginManager('./plugins');
manager.listPlugins();
});
program
.command('enable <plugins...>')
.description('启用插件')
.action((plugins) => {
const manager = new PluginManager('./plugins');
manager.enablePlugins(plugins);
});
program
.command('disable <plugins...>')
.description('禁用插件')
.action((plugins) => {
const manager = new PluginManager('./plugins');
manager.disablePlugins(plugins);
});
program
.command('install <name> [source]')
.description('安装插件')
.action((name, source) => {
const manager = new PluginManager('./plugins');
manager.installPlugin(name, source);
});
program
.command('uninstall <plugins...>')
.description('卸载插件')
.action((plugins) => {
const manager = new PluginManager('./plugins');
manager.uninstallPlugins(plugins);
});
program
.command('batch <operation> <plugins...>')
.description('批量操作')
.action((operation, plugins) => {
const manager = new PluginManager('./plugins');
manager.batchOperation(operation, plugins);
});
program.parse(process.argv);
使用示例
Python 版本
# 列出插件 python plugin_manager.py --dir ./plugins list # 批量启用插件 python plugin_manager.py --dir ./plugins batch enable plugin1 plugin2 plugin3 # 批量禁用插件 python plugin_manager.py --dir ./plugins batch disable plugin1 plugin2 # 安装插件 python plugin_manager.py --dir ./plugins install my-plugin https://example.com/plugin.zip
Shell 版本
# 列出插件 ./plugin_manager.sh list # 批量启用 ./plugin_manager.sh enable plugin1 plugin2 plugin3 # 批量禁用 ./plugin_manager.sh disable plugin1 plugin2 # 备份多个插件 ./plugin_manager.sh backup plugin1 plugin2
Node.js 版本
# 先安装依赖 npm install commander chalk fs-extra # 运行脚本 node plugin-manager.js list node plugin-manager.js enable plugin1 plugin2 node plugin-manager.js batch disable plugin1 plugin2 plugin3
高级功能扩展
添加配置文件支持
{
"plugins": [
{
"name": "plugin1",
"enabled": true,
"version": "1.0.0",
"dependencies": ["plugin2"],
"compatibleVersions": ["2.0", "3.0"]
}
],
"settings": {
"autoUpdate": false,
"backupBeforeUpdate": true,
"logLevel": "info"
}
}
添加钩子系统
class PluginHook:
def before_enable(self, plugin_name):
"""启用前检查"""
pass
def after_disable(self, plugin_name):
"""禁用后清理"""
pass
def on_error(self, plugin_name, error):
"""错误处理"""
pass
这些脚本提供了灵活的插件批量管理功能,可以根据具体需求进行扩展和自定义。
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播