实用脚本能批量更新吗?

wen 实用脚本 9

本文目录导读:

实用脚本能批量更新吗?

  1. 批量更新数据库记录(Python + MySQL)
  2. 批量重命名文件(Python)
  3. 批量处理图片(Python + Pillow)
  4. 批量更新配置文件(Bash脚本)
  5. 批量更新JSON数据(Python)
  6. 批量同步远程服务器(Ansible Playbook)
  7. 建议与最佳实践
  8. 实用工具推荐

是的,实用脚本完全可以实现批量更新功能!这取决于你具体要更新什么内容,我为你提供几种常见场景的批量更新脚本示例:

批量更新数据库记录(Python + MySQL)

# batch_update_db.py
import mysql.connector
from mysql.connector import Error
def batch_update_users():
    """批量更新用户状态"""
    try:
        conn = mysql.connector.connect(
            host='localhost',
            database='your_db',
            user='your_user',
            password='your_password'
        )
        cursor = conn.cursor()
        # 批量更新活跃用户
        update_query = """
        UPDATE users 
        SET status = 'active', 
            updated_at = NOW()
        WHERE last_login >= DATE_SUB(NOW(), INTERVAL 30 DAY)
        """
        cursor.execute(update_query)
        conn.commit()
        print(f"成功更新 {cursor.rowcount} 条记录")
    except Error as e:
        print(f"数据库错误: {e}")
    finally:
        if conn.is_connected():
            cursor.close()
            conn.close()
if __name__ == "__main__":
    batch_update_users()

批量重命名文件(Python)

# batch_rename_files.py
import os
import re
from pathlib import Path
def batch_rename_files(directory, pattern, replacement):
    """批量重命名文件"""
    path = Path(directory)
    for file in path.glob('*.*'):
        if file.is_file():
            # 使用正则替换文件名
            new_name = re.sub(pattern, replacement, file.name)
            if new_name != file.name:
                file.rename(path / new_name)
                print(f"重命名: {file.name} -> {new_name}")
# 示例:将所有 .jpg 文件名中的空格替换为下划线
batch_rename_files('./images', r'\s+', '_')

批量处理图片(Python + Pillow)

# batch_process_images.py
from PIL import Image
import os
from pathlib import Path
def batch_resize_images(input_dir, output_dir, size=(800, 600)):
    """批量调整图片大小"""
    Path(output_dir).mkdir(parents=True, exist_ok=True)
    for img_file in Path(input_dir).glob('*.jpg'):
        with Image.open(img_file) as img:
            img_resized = img.resize(size, Image.Resampling.LANCZOS)
            output_path = Path(output_dir) / img_file.name
            img_resized.save(output_path, quality=85, optimize=True)
            print(f"处理完成: {img_file.name}")
# 使用示例
batch_resize_images('./original', './resized', (1024, 768))

批量更新配置文件(Bash脚本)

#!/bin/bash
# batch_update_config.sh
# 批量修改配置文件中的某个参数
CONFIG_DIR="./config"
OLD_VALUE="version=1.0"
NEW_VALUE="version=2.0"
# 递归查找并替换
find "$CONFIG_DIR" -type f -name "*.conf" -exec sed -i "s/$OLD_VALUE/$NEW_VALUE/g" {} \;
echo "已完成批量配置更新"

批量更新JSON数据(Python)

# batch_update_json.py
import json
from pathlib import Path
def batch_update_json_files(directory, update_func):
    """批量更新JSON文件"""
    for json_file in Path(directory).glob('*.json'):
        with open(json_file, 'r', encoding='utf-8') as f:
            data = json.load(f)
        # 应用更新函数
        updated_data = update_func(data)
        with open(json_file, 'w', encoding='utf-8') as f:
            json.dump(updated_data, f, ensure_ascii=False, indent=2)
        print(f"已更新: {json_file.name}")
# 更新函数示例:添加时间戳
def add_timestamp(data):
    import datetime
    data['updated_at'] = datetime.datetime.now().isoformat()
    return data
# 使用
batch_update_json_files('./data', add_timestamp)

批量同步远程服务器(Ansible Playbook)

# batch_update_servers.yml
---
- name: 批量更新服务器配置
  hosts: web_servers
  become: yes
  tasks:
    - name: 更新Nginx配置
      template:
        src: nginx.conf.j2
        dest: /etc/nginx/nginx.conf
      notify: restart nginx
    - name: 更新应用版本
      git:
        repo: 'https://github.com/your/repo.git'
        dest: /var/www/app
        version: main
        force: yes
  handlers:
    - name: restart nginx
      systemd:
        name: nginx
        state: restarted

建议与最佳实践

  1. 测试先行:批量操作前先在测试环境验证
  2. 备份数据:重要的批量更新前做好备份
  3. 逐步执行:对于大量数据,可以分批处理
  4. 日志记录:记录每次更新的内容和结果
  5. 错误处理:添加异常处理机制,避免中断

实用工具推荐

  • Python: os, shutil, glob, pathlib
  • Bash: find, xargs, sed, awk
  • 数据库: SQL UPDATE语句(可带WHERE条件)
  • 配置管理: Ansible, SaltStack, Puppet

你需要具体更新什么类型的内容?我可以提供更针对性的脚本示例!

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