如何高效替换文件中同一MAC地址的不同格式并覆盖原文件?
Hey there, let's fix up that MAC address replacement script to be more efficient and reliable. Here's a polished solution that addresses your pain points with repeated file I/O and safe overwriting:
Optimized MAC Address Replacement Script (
mac_replacer.py) Key Improvements
- Single-pass file handling: Read the entire file into memory once, process it, then write back once—no repeated I/O operations
- Safe file overwriting: Use a temporary file to avoid corrupting the original if something goes wrong mid-write
- Dynamic MAC pattern matching: Use regex to catch all common MAC variants instead of enumerating every possible format manually
Complete Script Implementation
import argparse import re import os import shutil def normalize_mac(target_mac): # Strip all non-hex characters and convert to lowercase for consistent matching return re.sub(r'[^0-9a-fA-F]', '', target_mac).lower() def build_mac_regex(target_mac_normalized): # Generate regex patterns for all common MAC formats mac_segments_2char = [target_mac_normalized[i:i+2] for i in range(0, 12, 2)] mac_segments_4char = [target_mac_normalized[i:i+4] for i in range(0, 12, 4)] variant_patterns = [ # Raw 12-character MAC (no separators) re.escape(target_mac_normalized), # Hyphen-separated (XX-XX-XX-XX-XX-XX) '-'.join(mac_segments_2char), # Dot-separated (XX.XX.XX.XX.XX.XX) '.'.join(mac_segments_2char), # 4-character dot-separated (XXXX.XXXX.XXXX, e.g., Cisco format) '.'.join(mac_segments_4char) ] # Return case-insensitive regex to match all variants return re.compile('|'.join([re.escape(p) for p in variant_patterns]), re.IGNORECASE) def generate_replacement_mac(normalized_mac, output_format): # Generate the MAC in the user-specified output format two_char_parts = [normalized_mac[i:i+2] for i in range(0, 12, 2)] if output_format == 'colon': return ':'.join(two_char_parts) elif output_format == 'hyphen': return '-'.join(two_char_parts) elif output_format == 'dot': return '.'.join(two_char_parts) elif output_format == '4dot': four_char_parts = [normalized_mac[i:i+4] for i in range(0, 12, 4)] return '.'.join(four_char_parts) elif output_format == 'raw': return normalized_mac else: # Support custom formats (e.g., "{0}_{1}_{2}_{3}_{4}_{5}" for underscore-separated) return output_format.format(*two_char_parts) def process_file(file_path, target_mac, output_format): normalized_target = normalize_mac(target_mac) mac_regex = build_mac_regex(normalized_target) replacement_mac = generate_replacement_mac(normalized_target, output_format) # Read entire file into memory (single read operation) with open(file_path, 'r', encoding='utf-8') as f: content = f.read() # Replace all matching MAC variants updated_content = mac_regex.sub(replacement_mac, content) # Write to temp file first to avoid corrupting original temp_file = f"{file_path}.tmp" with open(temp_file, 'w', encoding='utf-8') as f: f.write(updated_content) # Verify temp file was written correctly (optional but safe) with open(temp_file, 'r', encoding='utf-8') as f: if f.read() != updated_content: os.remove(temp_file) raise IOError("Temporary file write failed—aborting to protect original file") # Replace original file with temp file shutil.move(temp_file, file_path) print(f"Success! All matching MAC variants replaced in {file_path}") def main(): parser = argparse.ArgumentParser( description="Replace all variants of a target MAC address in a file with a standardized format." ) parser.add_argument('-m', '--mac', required=True, help="Target MAC address (any format, e.g., 00:11:22:33:44:55 or 001122334455)") parser.add_argument('-f', '--file', required=True, help="Path to the file to process") parser.add_argument('-o', '--output-format', default='colon', help="Output format for MACs. Options: colon, hyphen, dot, 4dot, raw, or custom (e.g., \"{0}_{1}_{2}_{3}_{4}_{5}\")") args = parser.parse_args() try: process_file(args.file, args.mac, args.output_format) except Exception as e: print(f"Error occurred: {str(e)}") if __name__ == '__main__': main()
How to Use
Here are some common usage examples:
# Replace all variants of 001122334455 with colon-separated format (default) python mac_replacer.py -m 001122334455 -f network_config.txt # Replace all variants of 00-11-22-33-44-55 with Cisco-style 4dot format python mac_replacer.py -m 00-11-22-33-44-55 -f switch_config.txt -o 4dot # Use a custom underscore-separated format python mac_replacer.py -m 00.11.22.33.44.55 -f inventory.txt -o "{0}_{1}_{2}_{3}_{4}_{5}"
Why This Works Better
- No repeated I/O: The file is read once and written once, which is way faster than multiple read/write cycles
- Safe overwriting: Using a temporary file ensures your original file stays intact if the script crashes mid-write
- Flexible matching: The regex automatically catches all common MAC formats without needing to list every possible variant manually
内容的提问来源于stack exchange,提问作者Baksten
相关产品推荐
相关产品推荐

