Python脚本检测新增vCenter Farm:解决文件覆盖问题的方法
Got it, let's break down how to fix this problem. The core issue you're hitting is that overwriting your stored farm list every run erases the baseline reference you need to spot new entries. Here are three practical, easy-to-implement solutions to avoid this:
1. Use a One-Time Initialized Baseline File
This approach creates a baseline file only once (on the first run) and uses that file as your reference point forever after—no overwriting unless you intentionally reset it.
import os # Define your baseline file and initial farm list BASELINE_FILE = "vcenter_farms_baseline.txt" INITIAL_FARMS = ["Farm01", "Farm02", "Farm03", "Farm04", "Farm05"] def get_real_time_farms(): # Replace this with actual vCenter API calls to fetch live farms # Example: Returns simulated live list with a new Farm06 return ["Farm01", "Farm02", "Farm03", "Farm04", "Farm05", "Farm06"] def initialize_baseline(): # Create baseline file only if it doesn't exist if not os.path.exists(BASELINE_FILE): with open(BASELINE_FILE, "w") as f: for farm in INITIAL_FARMS: f.write(f"{farm}\n") print("Baseline file created with initial farm list.") else: print("Using existing baseline file for comparison.") def detect_new_farms(): initialize_baseline() # Load baseline farms from file with open(BASELINE_FILE, "r") as f: baseline_farms = [line.strip() for line in f if line.strip()] # Get live farm data real_time_farms = get_real_time_farms() # Find farms that exist in live data but not in baseline new_farms = [farm for farm in real_time_farms if farm not in baseline_farms] if new_farms: print(f"✅ Detected new farms: {', '.join(new_farms)}") else: print("ℹ️ No new farms detected.") if __name__ == "__main__": detect_new_farms()
How it works:
- On first run: Creates the baseline file with your initial farm list.
- Subsequent runs: Reads the existing baseline file instead of overwriting it, so you always have a fixed reference to compare against.
- To reset the baseline: Delete the
vcenter_farms_baseline.txtfile and re-run the script.
2. Use a Structured Config File (JSON/YAML)
For more flexibility (like adding extra configs later), store your baseline in a structured format like JSON. This makes it easier to maintain and update the baseline when needed.
import json import os BASELINE_CONFIG = "vcenter_farms_config.json" INITIAL_FARMS = ["Farm01", "Farm02", "Farm03", "Farm04", "Farm05"] def get_real_time_farms(): return ["Farm01", "Farm02", "Farm03", "Farm04", "Farm05", "Farm06", "Farm07"] def initialize_config(): if not os.path.exists(BASELINE_CONFIG): config = {"baseline_farms": INITIAL_FARMS} with open(BASELINE_CONFIG, "w") as f: json.dump(config, f, indent=4) print("Config file initialized with baseline farms.") else: print("Using existing config file for comparison.") def detect_new_farms(): initialize_config() # Load baseline from JSON with open(BASELINE_CONFIG, "r") as f: config = json.load(f) baseline_farms = config["baseline_farms"] real_time_farms = get_real_time_farms() new_farms = list(set(real_time_farms) - set(baseline_farms)) if new_farms: print(f"✅ New farms found: {', '.join(new_farms)}") # Optional: Update baseline automatically after confirming new farms # config["baseline_farms"] = real_time_farms # with open(BASELINE_CONFIG, "w") as f: # json.dump(config, f, indent=4) # print("Baseline updated to include new farms.") else: print("ℹ️ No new farms detected.") if __name__ == "__main__": detect_new_farms()
Bonus:
- You can manually edit the JSON file to update the baseline if needed, or uncomment the auto-update code to refresh the baseline after detecting new farms.
3. Append Historical Records (For Audit Trails)
If you want to track changes over time (e.g., when farms were added), use an append-only history file. This keeps all past farm lists intact and lets you compare against the most recent baseline.
import os from datetime import datetime HISTORY_FILE = "vcenter_farms_history.txt" INITIAL_FARMS = ["Farm01", "Farm02", "Farm03", "Farm04", "Farm05"] def get_real_time_farms(): return ["Farm01", "Farm02", "Farm03", "Farm04", "Farm05", "Farm06"] def initialize_history(): if not os.path.exists(HISTORY_FILE): timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") with open(HISTORY_FILE, "a") as f: f.write(f"[{timestamp}] BASELINE: {', '.join(INITIAL_FARMS)}\n") print("History file initialized with baseline farms.") def get_latest_baseline(): # Pull the most recent baseline from the history file with open(HISTORY_FILE, "r") as f: lines = [line.strip() for line in f if line.strip()] # Find the last marked baseline entry for line in reversed(lines): if "BASELINE:" in line: baseline_str = line.split("BASELINE: ")[1] return baseline_str.split(", ") # Fallback to the last recorded farm list if no baseline exists last_line = lines[-1] farms_str = last_line.split("] ")[1] return farms_str.split(", ") def detect_new_farms(): initialize_history() baseline_farms = get_latest_baseline() real_time_farms = get_real_time_farms() new_farms = [farm for farm in real_time_farms if farm not in baseline_farms] # Append current farm list to history timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") with open(HISTORY_FILE, "a") as f: f.write(f"[{timestamp}] CURRENT: {', '.join(real_time_farms)}\n") if new_farms: print(f"✅ Detected new farms: {', '.join(new_farms)}") # Mark the updated list as the new baseline with open(HISTORY_FILE, "a") as f: f.write(f"[{timestamp}] BASELINE: {', '.join(real_time_farms)}\n") print("Updated baseline in history file.") else: print("ℹ️ No new farms detected.") if __name__ == "__main__": detect_new_farms()
Pro Tips:
- Replace the
get_real_time_farms()function with actual vCenter API calls using libraries likepyVmomiorvmware.vapito fetch live farm data. - Add error handling (e.g., permission checks, API connection failures) to make the script more robust.
- For sensitive environments, consider encrypting the baseline/config file to protect vCenter resource names.
内容的提问来源于stack exchange,提问作者askpython

