如何用脚本加密文件名

wen 实用脚本 2

本文目录导读:

如何用脚本加密文件名

  1. Python 脚本(跨平台)
  2. Bash 脚本(Linux/Mac)
  3. Windows 批处理脚本(.bat)
  4. 高级功能(Python完整示例)
  5. 使用建议

这里为您提供几种常见的脚本加密文件名的方法,涵盖不同平台和需求:

Python 脚本(跨平台)

使用 Base64 编码(可逆)

import os
import base64
def encrypt_filename(filename):
    """将文件名进行Base64编码"""
    # 分离文件名和扩展名
    base_name, ext = os.path.splitext(filename)
    # 编码文件名主体
    encoded = base64.urlsafe_b64encode(base_name.encode()).decode()
    return f"{encoded}{ext}"
def decrypt_filename(encrypted_name):
    """解密文件名"""
    base_name, ext = os.path.splitext(encrypted_name)
    decoded = base64.urlsafe_b64decode(base_name.encode()).decode()
    return f"{decoded}{ext}"
# 使用示例
filename = "my_important_document.txt"
encrypted = encrypt_filename(filename)
print(f"加密: {encrypted}")
# 批量重命名文件夹中的文件
import os
def encrypt_folder(path):
    for file in os.listdir(path):
        full_path = os.path.join(path, file)
        if os.path.isfile(full_path):
            new_name = encrypt_filename(file)
            os.rename(full_path, os.path.join(path, new_name))
# 解密文件夹
def decrypt_folder(path):
    for file in os.listdir(path):
        full_path = os.path.join(path, file)
        if os.path.isfile(full_path):
            new_name = decrypt_filename(file)
            os.rename(full_path, os.path.join(path, new_name))

使用哈希函数(不可逆,安全)

import os
import hashlib
def hash_filename(filename):
    """使用SHA-256生成哈希文件名"""
    base_name, ext = os.path.splitext(filename)
    hash_value = hashlib.sha256(base_name.encode()).hexdigest()[:16]  # 前16位
    return f"{hash_value}{ext}"
# 使用示例
filename = "private_data.xlsx"
hashed = hash_filename(filename)
print(f"原始: {filename} -> 哈希: {hashed}")

使用 Fernet 对称加密(现代加密,可逆)

import os
from cryptography.fernet import Fernet
def generate_key():
    """生成加密密钥并保存"""
    key = Fernet.generate_key()
    with open('key.key', 'wb') as key_file:
        key_file.write(key)
    return key
def load_key():
    """加载已保存的密钥"""
    return open('key.key', 'rb').read()
def encrypt_filename(filename, key):
    """加密文件名"""
    base_name, ext = os.path.splitext(filename)
    cipher = Fernet(key)
    encrypted = cipher.encrypt(base_name.encode())
    # 将加密结果转为文件名友好的格式
    encrypted_str = encrypted.decode().replace('/', '_').replace('+', '-').strip('=')
    return f"{encrypted_str}{ext}"
def decrypt_filename(filename, key):
    """解密文件名"""
    base_name, ext = os.path.splitext(filename)
    # 恢复原始加密格式
    encrypted_str = base_name.replace('_', '/').replace('-', '+')
    encrypted_str += '=' * (4 - len(encrypted_str) % 4)
    cipher = Fernet(key)
    decrypted = cipher.decrypt(encrypted_str.encode()).decode()
    return f"{decrypted}{ext}"
# 使用示例
key = load_key()  # 或 generate_key()
encrypted = encrypt_filename("report_q3_2023.pdf", key)
print(f"加密后: {encrypted}")
decrypted = decrypt_filename(encrypted, key)
print(f"解密后: {decrypted}")

Bash 脚本(Linux/Mac)

#!/bin/bash
# 使用 MD5 加密文件名
encrypt_filename() {
    local file="$1"
    local dir=$(dirname "$file")
    local basename=$(basename "$file")
    # 提取扩展名
    local ext="${basename##*.}"
    # 提取纯文件名
    local name="${basename%.*}"
    # 生成MD5哈希
    local hash=$(echo -n "$name" | md5sum | cut -d' ' -f1)
    # 重命名
    mv "$file" "$dir/${hash}.${ext}"
}
# 批量加密当前目录下的所有文件
# for file in *; do
#     if [ -f "$file" ]; then
#         encrypt_filename "$file"
#     fi
# done

Windows 批处理脚本(.bat)

@echo off
setlocal EnableDelayedExpansion
:: 简单的字符替换加密(示例)
set /p filename="请输入文件名: "
:: 创建加密映射
set "mapping=a=@&b=#&c=!&d=$&e=%%&f=^&g=&"
set "mapping=%mapping%h=&i=&j=&k=&l=&m=&n=&o=&p=&q=&r=&s=&t=&u=&v=&w=&x=&y=&z="
:: 遍历字符进行替换(示例仅替换a)
set "encrypted=%filename: a=@%"
echo 加密后的文件名: %encrypted%

高级功能(Python完整示例)

#!/usr/bin/env python3
"""
完整版文件加密工具
- 支持批量处理
- 多种加密算法
- 日志记录
"""
import os
import sys
import logging
from datetime import datetime
from typing import Optional
import argparse
# 配置日志
logging.basicConfig(filename='file_encryptor.log', 
                    level=logging.INFO,
                    format='%(asctime)s - %(message)s')
class FileEncryptor:
    def __init__(self):
        self.mapping = self._create_mapping()
    def _create_mapping(self):
        """创建字符映射表"""
        import random
        chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
        chars_list = list(chars)
        random.shuffle(chars_list)
        return dict(zip(chars, chars_list))
    def simple_encrypt(self, filename: str) -> str:
        """使用字符映射加密"""
        base, ext = os.path.splitext(filename)
        encrypted = ''.join(self.mapping.get(c, c) for c in base)
        return f"{encrypted}{ext}"
    def simple_decrypt(self, filename: str) -> str:
        """解密使用字符映射加密的文件名"""
        base, ext = os.path.splitext(filename)
        reverse_mapping = {v: k for k, v in self.mapping.items()}
        decrypted = ''.join(reverse_mapping.get(c, c) for c in base)
        return f"{decrypted}{ext}"
    def batch_encrypt(self, folder_path: str) -> int:
        """批量加密文件夹中的文件"""
        count = 0
        for file in os.listdir(folder_path):
            full_path = os.path.join(folder_path, file)
            if os.path.isfile(full_path):
                new_name = self.simple_encrypt(file)
                os.rename(full_path, os.path.join(folder_path, new_name))
                logging.info(f"Encrypted: {file} -> {new_name}")
                count += 1
        return count
def main():
    parser = argparse.ArgumentParser(description='文件加密工具')
    parser.add_argument('action', choices=['encrypt', 'decrypt', 'test'])
    parser.add_argument('path', nargs='?', help='文件或文件夹路径')
    parser.add_argument('--algo', choices=['mapping', 'base64', 'hash'], 
                       default='mapping', help='加密算法')
    args = parser.parse_args()
    encryptor = FileEncryptor()
    if args.action == 'test':
        # 测试功能
        test_file = "测试文档_v1.0.docx"
        encrypted = encryptor.simple_encrypt(test_file)
        decrypted = encryptor.simple_decrypt(encrypted)
        print(f"原始: {test_file}")
        print(f"加密: {encrypted}")
        print(f"解密: {decrypted}")
    elif args.path:
        if os.path.isfile(args.path):
            # 单文件处理
            if args.action == 'encrypt':
                new_name = encryptor.simple_encrypt(args.path)
                os.rename(args.path, new_name)
                print(f"已加密: {args.path} -> {new_name}")
            else:
                new_name = encryptor.simple_decrypt(args.path)
                os.rename(args.path, new_name)
                print(f"已解密: {args.path} -> {new_name}")
        else:
            # 文件夹批量处理
            count = encryptor.batch_encrypt(args.path)
            print(f"处理了 {count} 个文件")
if __name__ == "__main__":
    main()

使用建议

  1. 简单需求:使用 Base64 或字符映射
  2. 安全需求:使用 AES 加密(Fernet)
  3. 不可逆需求:使用哈希函数
  4. 批量处理:调用脚本遍历文件夹
  5. 记得备份:加密前备份密钥或原文件名
  6. 测试先行:先在测试环境验证,再对重要文件操作

如需更多特定功能的脚本,请提供具体需求(如加密算法、平台、批量操作等)。

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