本文目录导读:

我来帮你写一个安全的账号密码存储脚本,出于安全考虑,我会使用加密方式存储密码。
使用对称加密(Python示例)
安装依赖
pip install cryptography
密码管理器脚本
import json
import os
from cryptography.fernet import Fernet
from getpass import getpass
import base64
import hashlib
class PasswordManager:
def __init__(self, master_password):
# 使用主密码生成加密密钥
key = hashlib.sha256(master_password.encode()).digest()
self.key = base64.urlsafe_b64encode(key)
self.cipher = Fernet(self.key)
self.data_file = "passwords.enc"
self.load_data()
def load_data(self):
"""加载已保存的密码数据"""
if os.path.exists(self.data_file):
with open(self.data_file, 'rb') as f:
encrypted_data = f.read()
try:
decrypted_data = self.cipher.decrypt(encrypted_data)
self.data = json.loads(decrypted_data)
except:
print("密码错误或数据损坏!")
self.data = {}
else:
self.data = {}
def save_data(self):
"""保存加密的密码数据"""
json_data = json.dumps(self.data)
encrypted_data = self.cipher.encrypt(json_data.encode())
with open(self.data_file, 'wb') as f:
f.write(encrypted_data)
def add_password(self, site, username, password):
"""添加新密码"""
if site not in self.data:
self.data[site] = {}
self.data[site][username] = password
self.save_data()
print(f"已保存 {site} 的登录信息")
def get_password(self, site, username=None):
"""获取密码"""
if site in self.data:
if username:
if username in self.data[site]:
print(f"网站: {site}")
print(f"用户名: {username}")
print(f"密码: {self.data[site][username]}")
else:
print(f"未找到用户 {username} 在 {site} 的密码")
else:
print(f"网站: {site}")
for user, pwd in self.data[site].items():
print(f"用户名: {user} -> 密码: {pwd}")
else:
print(f"未找到 {site} 的密码")
def list_sites(self):
"""列出所有保存的网站"""
if self.data:
print("已保存密码的网站:")
for site in self.data:
print(f"- {site} ({len(self.data[site])} 个账号)")
else:
print("暂无保存的密码")
def delete_password(self, site, username=None):
"""删除密码"""
if site in self.data:
if username:
if username in self.data[site]:
del self.data[site][username]
if not self.data[site]:
del self.data[site]
self.save_data()
print(f"已删除 {site} 的 {username} 登录信息")
else:
print(f"未找到用户 {username}")
else:
del self.data[site]
self.save_data()
print(f"已删除 {site} 的所有登录信息")
else:
print(f"未找到 {site}")
def main():
print("=== 密码管理器 ===")
# 设置/输入主密码
if not os.path.exists("passwords.enc"):
master_password = getpass("设置主密码: ")
confirm_password = getpass("确认主密码: ")
if master_password != confirm_password:
print("两次密码不一致!")
return
else:
master_password = getpass("请输入主密码: ")
pm = PasswordManager(master_password)
while True:
print("\n请选择操作:")
print("1. 添加密码")
print("2. 查看密码")
print("3. 列出所有网站")
print("4. 删除密码")
print("5. 退出")
choice = input("请输入选择 (1-5): ")
if choice == '1':
site = input("网站名称: ")
username = input("用户名: ")
password = getpass("密码: ")
pm.add_password(site, username, password)
elif choice == '2':
site = input("网站名称: ")
username = input("用户名 (留空显示所有): ")
pm.get_password(site, username if username else None)
elif choice == '3':
pm.list_sites()
elif choice == '4':
site = input("网站名称: ")
username = input("用户名 (留空删除整个网站): ")
pm.delete_password(site, username if username else None)
elif choice == '5':
print("再见!")
break
if __name__ == "__main__":
main()
简单的明文存储(仅供学习参考)
import json
import os
def save_password(site, username, password):
"""保存密码到JSON文件"""
data = {}
if os.path.exists("passwords.json"):
with open("passwords.json", "r", encoding="utf-8") as f:
data = json.load(f)
if site not in data:
data[site] = {}
data[site][username] = password
with open("passwords.json", "w", encoding="utf-8") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
print(f"已保存 {site} 的密码")
def get_password(site, username=None):
"""读取密码"""
if not os.path.exists("passwords.json"):
print("没有保存的密码")
return
with open("passwords.json", "r", encoding="utf-8") as f:
data = json.load(f)
if site in data:
if username:
print(f"密码: {data[site].get(username, '未找到')}")
else:
for user, pwd in data[site].items():
print(f"{user}: {pwd}")
安全建议
- 使用强主密码:至少12位,包含大小写字母、数字和特殊字符
- 定期更改主密码:每3-6个月更换一次
- 备份加密文件:定期备份
passwords.enc文件 - 不要在公共电脑使用:避免在不受信任的设备上使用
- 考虑使用专业工具:如KeePass、Bitwarden等成熟密码管理器
扩展功能建议
你可以添加这些功能增强脚本:
- 密码强度检查器
- 密码生成器
- 导出/导入功能
- 搜索功能
- 密码过期提醒
需要我帮你实现某个特定功能吗?