实用脚本能批量初始化吗?

wen 实用脚本 12

本文目录导读:

实用脚本能批量初始化吗?

  1. 批量创建用户脚本 (Linux)
  2. 批量初始化项目模板 (Node.js)
  3. 批量初始化数据库表 (Python)
  4. 批量初始化Docker容器
  5. 通用批量初始化框架
  6. 使用建议

可以的!实用脚本完全可以批量初始化,这里给你几种常见的批量初始化方案:

批量创建用户脚本 (Linux)

#!/bin/bash
# batch_init_users.sh - 批量初始化用户
# 从文件读取用户列表
USERS_FILE="users.txt"
# 检查文件是否存在
if [ ! -f "$USERS_FILE" ]; then
    echo "用户列表文件 $USERS_FILE 不存在!"
    exit 1
fi
# 批量创建用户
while IFS=: read -r username password home_dir
do
    # 检查用户是否存在
    if id "$username" &>/dev/null; then
        echo "用户 $username 已存在,跳过..."
        continue
    fi
    # 创建用户
    useradd -m -d "${home_dir:-/home/$username}" -s /bin/bash "$username"
    # 设置密码
    echo "$username:$password" | chpasswd
    # 设置权限
    chown -R "$username:$username" "${home_dir:-/home/$username}"
    echo "已创建用户: $username"
done < "$USERS_FILE"
echo "批量用户初始化完成!"

users.txt 格式示例:

zhangsan:Pass123:/home/zhangsan
lisi:Pass456:/home/lisi
wangwu:Pass789:/home/wangwu

批量初始化项目模板 (Node.js)

// batch-init.js
const fs = require('fs-extra');
const path = require('path');
const { execSync } = require('child_process');
// 项目配置
const projects = [
    { name: 'frontend-app', type: 'vue' },
    { name: 'backend-api', type: 'express' },
    { name: 'mobile-app', type: 'react-native' }
];
// 项目模板配置
const templates = {
    vue: 'https://github.com/vuejs/vue-cli.git',
    express: 'https://github.com/expressjs/express.git',
    'react-native': 'https://github.com/facebook/react-native.git'
};
async function batchInitProjects() {
    for (const project of projects) {
        const projectPath = path.join(process.cwd(), project.name);
        console.log(`正在初始化项目: ${project.name} (${project.type})`);
        try {
            // 创建项目目录
            await fs.ensureDir(projectPath);
            // 根据类型执行不同初始化命令
            switch(project.type) {
                case 'vue':
                    execSync(`vue create ${project.name}`, { stdio: 'inherit' });
                    break;
                case 'express':
                    execSync(`npx express-generator ${project.name} --view=ejs`, { stdio: 'inherit' });
                    break;
                case 'react-native':
                    execSync(`npx react-native init ${project.name}`, { stdio: 'inherit' });
                    break;
            }
            // 初始化Git仓库
            execSync('git init', { cwd: projectPath });
            console.log(`✓ 项目 ${project.name} 初始化完成`);
        } catch (error) {
            console.error(`✗ 项目 ${project.name} 初始化失败: ${error.message}`);
        }
    }
    console.log('所有项目初始化完成!');
}
batchInitProjects();

批量初始化数据库表 (Python)

#!/usr/bin/env python3
# batch_init_db.py
import mysql.connector
from mysql.connector import Error
import yaml
# 数据库配置
DB_CONFIG = {
    'host': 'localhost',
    'user': 'root',
    'password': 'password'
}
# 从YAML文件读取表结构
TABLES_CONFIG = '''
tables:
  - name: users
    columns:
      - name: id
        type: INT AUTO_INCREMENT PRIMARY KEY
      - name: username
        type: VARCHAR(50) NOT NULL
      - name: email
        type: VARCHAR(100)
      - name: created_at
        type: TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  - name: products
    columns:
      - name: id
        type: INT AUTO_INCREMENT PRIMARY KEY
      - name: name
        type: VARCHAR(200) NOT NULL
      - name: price
        type: DECIMAL(10,2)
      - name: stock
        type: INT DEFAULT 0
  - name: orders
    columns:
      - name: id
        type: INT AUTO_INCREMENT PRIMARY KEY
      - name: user_id
        type: INT
      - name: total_amount
        type: DECIMAL(10,2)
      - name: status
        type: VARCHAR(20) DEFAULT 'pending'
'''
def batch_init_tables(database_name):
    try:
        connection = mysql.connector.connect(**DB_CONFIG)
        cursor = connection.cursor()
        # 创建数据库
        cursor.execute(f"CREATE DATABASE IF NOT EXISTS {database_name}")
        cursor.execute(f"USE {database_name}")
        # 解析表结构
        config = yaml.safe_load(TABLES_CONFIG)
        # 批量创建表
        for table in config['tables']:
            table_name = table['name']
            columns = table['columns']
            # 构建CREATE TABLE语句
            columns_sql = ', '.join(
                f"{col['name']} {col['type']}" 
                for col in columns
            )
            create_sql = f"CREATE TABLE IF NOT EXISTS {table_name} ({columns_sql})"
            try:
                cursor.execute(create_sql)
                print(f"✓ 表 {table_name} 创建成功")
            except Error as e:
                print(f"✗ 表 {table_name} 创建失败: {e}")
        connection.commit()
        print(f"数据库 {database_name} 初始化完成!")
    except Error as e:
        print(f"数据库连接失败: {e}")
    finally:
        if connection.is_connected():
            cursor.close()
            connection.close()
# 执行批量初始化
batch_init_tables('ecommerce_db')

批量初始化Docker容器

#!/bin/bash
# batch_init_docker.sh - 批量初始化Docker环境
# 定义服务配置
SERVICES=(
    "nginx:latest:8080:80"
    "redis:alpine:6379:6379"
    "postgres:13:5432:5432"
    "mongo:4.4:27017:27017"
)
# 批量初始化容器
for service in "${SERVICES[@]}"
do
    IFS=':' read -r name image host_port container_port <<< "$service"
    echo "正在初始化 $name..."
    # 检查容器是否已存在
    if docker ps -a --format '{{.Names}}' | grep -q "^${name}$"; then
        echo "容器 $name 已存在,跳过..."
        continue
    fi
    # 创建并启动容器
    docker run -d \
        --name "$name" \
        -p "$host_port:$container_port" \
        --restart unless-stopped \
        "$image"
    if [ $? -eq 0 ]; then
        echo "✓ $name 初始化成功 (端口: $host_port)"
    else
        echo "✗ $name 初始化失败"
    fi
done
echo "Docker环境初始化完成!"
docker ps

通用批量初始化框架

#!/usr/bin/env python3
# universal_batch_init.py
import json
import subprocess
import os
from pathlib import Path
class BatchInitializer:
    def __init__(self, config_file):
        with open(config_file, 'r') as f:
            self.config = json.load(f)
    def init_all(self):
        """批量执行所有初始化任务"""
        results = []
        for task in self.config['tasks']:
            result = self._execute_task(task)
            results.append(result)
        self._generate_report(results)
    def _execute_task(self, task):
        """执行单个初始化任务"""
        task_type = task['type']
        task_name = task['name']
        print(f"执行任务: {task_name} ({task_type})")
        try:
            if task_type == 'command':
                return self._run_command(task)
            elif task_type == 'script':
                return self._run_script(task)
            elif task_type == 'file':
                return self._create_files(task)
            elif task_type == 'template':
                return self._use_template(task)
            else:
                return {'name': task_name, 'status': 'error', 'message': f'未知任务类型: {task_type}'}
        except Exception as e:
            return {'name': task_name, 'status': 'error', 'message': str(e)}
    def _run_command(self, task):
        """执行系统命令"""
        result = subprocess.run(
            task['command'],
            shell=True,
            capture_output=True,
            text=True
        )
        if result.returncode == 0:
            return {'name': task['name'], 'status': 'success'}
        else:
            return {'name': task['name'], 'status': 'error', 'message': result.stderr}
    def _generate_report(self, results):
        """生成初始化报告"""
        success = sum(1 for r in results if r['status'] == 'success')
        errors = [r for r in results if r['status'] == 'error']
        print(f"\n初始化完成!")
        print(f"成功: {success}/{len(results)}")
        if errors:
            print(f"失败: {len(errors)}")
            for err in errors:
                print(f"  - {err['name']}: {err.get('message', '未知错误')}")
# 使用示例
if __name__ == "__main__":
    # 创建配置文件
    config = {
        "tasks": [
            {
                "name": "初始化项目目录",
                "type": "command",
                "command": "mkdir -p ./{src,dist,test,docs}"
            },
            {
                "name": "创建配置文件",
                "type": "file",
                "files": [
                    {"path": ".env", "content": "APP_ENV=development\nDEBUG=true"},
                    {"path": ".gitignore", "content": "node_modules/\ndist/\n.env.local"}
                ]
            },
            {
                "name": "初始化Git仓库",
                "type": "command",
                "command": "git init && git add . && git commit -m 'Initial commit'"
            }
        ]
    }
    # 保存配置文件
    with open('init_config.json', 'w') as f:
        json.dump(config, f, indent=2)
    # 执行批量初始化
    initializer = BatchInitializer('init_config.json')
    initializer.init_all()

使用建议

  1. 配置文件化:将初始化参数放在配置文件(JSON/YAML)中
  2. 错误处理:每个任务执行失败不应影响其他任务
  3. 日志记录:记录详细的初始化日志便于排查问题
  4. 幂等性:相同操作多次执行结果应一致
  5. 模板化:使用模板引擎(Jinja2/Handlebars)生成动态配置

你需要哪种类型的批量初始化?我可以给你更具体的脚本示例!

抱歉,评论功能暂时关闭!