import sys import os # .env文件路径:固定在api-key-vault根目录 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ENV_FILE = os.path.join(BASE_DIR, ".env") def load_keys(): """读取.env文件,返回dict""" keys = {} if not os.path.exists(ENV_FILE): return keys with open(ENV_FILE, "r", encoding="utf-8") as f: for line in f: line = line.strip() if not line or line.startswith("#"): continue if "=" in line: name, _, value = line.partition("=") keys[name.strip()] = value.strip() return keys def save_keys(keys): """把dict写回.env文件""" with open(ENV_FILE, "w", encoding="utf-8") as f: f.write("# API Key Vault - 自动生成,请勿手动乱改\n") for name, value in keys.items(): f.write(f"{name}={value}\n") def cmd_get(name): keys = load_keys() if name not in keys: print("ERROR:KEY_NOT_FOUND") else: print(keys[name]) def cmd_set(name, value): keys = load_keys() keys[name] = value save_keys(keys) print(f"✅ 已保存:{name}") def cmd_list(): keys = load_keys() if not keys: print("暂无已存储的Key") return print("已存储的Key列表:") for name in keys: value = keys[name] # 只显示前4位和后4位,中间用*遮挡 masked = value[:4] + "****" + value[-4:] if len(value) > 8 else "****" print(f" · {name} = {masked}") def cmd_delete(name): keys = load_keys() if name not in keys: print(f"❌ 未找到:{name}") else: del keys[name] save_keys(keys) print(f"🗑 已删除:{name}") if __name__ == "__main__": if len(sys.argv) < 2: print("用法:") print(" python vault.py get ") print(" python vault.py set ") print(" python vault.py list") print(" python vault.py delete ") sys.exit(1) command = sys.argv[1].lower() if command == "get": if len(sys.argv) < 3: print("错误:get命令需要提供key名") sys.exit(1) cmd_get(sys.argv[2]) elif command == "set": if len(sys.argv) < 4: print("错误:set命令需要提供key名和key值") sys.exit(1) cmd_set(sys.argv[2], sys.argv[3]) elif command == "list": cmd_list() elif command == "delete": if len(sys.argv) < 3: print("错误:delete命令需要提供key名") sys.exit(1) cmd_delete(sys.argv[2]) else: print(f"错误:未知命令 {command}") sys.exit(1)