519 lines
16 KiB
Python
519 lines
16 KiB
Python
#!/usr/bin/env python3
|
||
# -*- coding: utf-8 -*-
|
||
"""
|
||
创建管理员用户的脚本
|
||
使用方法: python create_admin.py
|
||
"""
|
||
|
||
import sys
|
||
import os
|
||
from getpass import getpass
|
||
|
||
# 添加项目根目录到Python路径
|
||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||
|
||
from init_db import create_app
|
||
from app.models import db, User
|
||
from app.utils.database import safe_add_and_commit
|
||
|
||
|
||
def create_admin_user():
|
||
"""创建管理员用户"""
|
||
app = create_app()
|
||
|
||
with app.app_context():
|
||
print("=" * 50)
|
||
print("创建管理员用户")
|
||
print("=" * 50)
|
||
|
||
# 输入管理员信息
|
||
while True:
|
||
student_number = input("请输入管理员账号(学号格式): ").strip()
|
||
if not student_number:
|
||
print("账号不能为空,请重新输入!")
|
||
continue
|
||
|
||
# 检查账号是否已存在
|
||
existing_user = User.query.filter_by(student_number=student_number).first()
|
||
if existing_user:
|
||
print(f"账号 {student_number} 已存在!")
|
||
choice = input("是否要更新该用户为管理员?(y/n): ").lower()
|
||
if choice == 'y':
|
||
# 更新现有用户为管理员
|
||
existing_user.role = 'admin'
|
||
|
||
# 询问是否要重置密码
|
||
reset_pwd = input("是否要重置密码?(y/n): ").lower()
|
||
if reset_pwd == 'y':
|
||
while True:
|
||
password = getpass("请输入新密码: ")
|
||
if len(password) < 6:
|
||
print("密码长度至少6位,请重新输入!")
|
||
continue
|
||
|
||
confirm_password = getpass("请确认密码: ")
|
||
if password != confirm_password:
|
||
print("两次输入的密码不一致,请重新输入!")
|
||
continue
|
||
|
||
existing_user.set_password(password)
|
||
break
|
||
|
||
success, error = safe_add_and_commit(existing_user)
|
||
if success:
|
||
print(f"用户 {student_number} 已成功更新为管理员!")
|
||
else:
|
||
print(f"更新失败: {error}")
|
||
return
|
||
else:
|
||
continue
|
||
else:
|
||
break
|
||
|
||
# 输入密码
|
||
while True:
|
||
password = getpass("请输入管理员密码: ")
|
||
if len(password) < 6:
|
||
print("密码长度至少6位,请重新输入!")
|
||
continue
|
||
|
||
confirm_password = getpass("请确认密码: ")
|
||
if password != confirm_password:
|
||
print("两次输入的密码不一致,请重新输入!")
|
||
continue
|
||
break
|
||
|
||
# 创建管理员用户
|
||
admin_user = User(
|
||
student_number=student_number,
|
||
role='admin',
|
||
is_active=True
|
||
)
|
||
admin_user.set_password(password)
|
||
|
||
# 保存到数据库
|
||
success, error = safe_add_and_commit(admin_user)
|
||
|
||
if success:
|
||
print(f"\n✅ 管理员用户创建成功!")
|
||
print(f"账号: {student_number}")
|
||
print(f"角色: 管理员")
|
||
print(f"状态: 激活")
|
||
else:
|
||
print(f"\n❌ 创建失败: {error}")
|
||
|
||
|
||
def batch_create_admins():
|
||
"""批量创建管理员用户"""
|
||
app = create_app()
|
||
|
||
with app.app_context():
|
||
print("=" * 50)
|
||
print("批量创建管理员用户")
|
||
print("=" * 50)
|
||
print("输入格式: 账号,密码")
|
||
print("例如: admin001,123456")
|
||
print("输入 'done' 完成输入")
|
||
print("-" * 50)
|
||
|
||
admin_list = []
|
||
|
||
while True:
|
||
user_input = input("请输入管理员信息(账号,密码): ").strip()
|
||
|
||
if user_input.lower() == 'done':
|
||
break
|
||
|
||
if ',' not in user_input:
|
||
print("格式错误!请使用 '账号,密码' 格式")
|
||
continue
|
||
|
||
try:
|
||
student_number, password = user_input.split(',', 1)
|
||
student_number = student_number.strip()
|
||
password = password.strip()
|
||
|
||
if not student_number or not password:
|
||
print("账号和密码都不能为空!")
|
||
continue
|
||
|
||
if len(password) < 6:
|
||
print("密码长度至少6位!")
|
||
continue
|
||
|
||
# 检查是否已存在
|
||
existing_user = User.query.filter_by(student_number=student_number).first()
|
||
if existing_user:
|
||
print(f"账号 {student_number} 已存在,跳过...")
|
||
continue
|
||
|
||
admin_list.append((student_number, password))
|
||
print(f"✓ 已添加: {student_number}")
|
||
|
||
except ValueError:
|
||
print("格式错误!请使用 '账号,密码' 格式")
|
||
continue
|
||
|
||
if not admin_list:
|
||
print("没有有效的管理员信息,退出...")
|
||
return
|
||
|
||
# 确认创建
|
||
print(f"\n准备创建 {len(admin_list)} 个管理员用户:")
|
||
for student_number, _ in admin_list:
|
||
print(f"- {student_number}")
|
||
|
||
confirm = input("\n确认创建?(y/n): ").lower()
|
||
if confirm != 'y':
|
||
print("已取消创建")
|
||
return
|
||
|
||
# 批量创建
|
||
success_count = 0
|
||
fail_count = 0
|
||
|
||
for student_number, password in admin_list:
|
||
admin_user = User(
|
||
student_number=student_number,
|
||
role='admin',
|
||
is_active=True
|
||
)
|
||
admin_user.set_password(password)
|
||
|
||
success, error = safe_add_and_commit(admin_user)
|
||
|
||
if success:
|
||
print(f"✅ {student_number} 创建成功")
|
||
success_count += 1
|
||
else:
|
||
print(f"❌ {student_number} 创建失败: {error}")
|
||
fail_count += 1
|
||
|
||
print(f"\n批量创建完成:")
|
||
print(f"成功: {success_count}")
|
||
print(f"失败: {fail_count}")
|
||
|
||
|
||
def list_admins():
|
||
"""列出所有管理员用户"""
|
||
app = create_app()
|
||
|
||
with app.app_context():
|
||
print("=" * 50)
|
||
print("管理员用户列表")
|
||
print("=" * 50)
|
||
|
||
admins = User.query.filter_by(role='admin').all()
|
||
|
||
if not admins:
|
||
print("暂无管理员用户")
|
||
return
|
||
|
||
print(f"{'序号':<4} {'账号':<15} {'状态':<8} {'创建时间':<20} {'最后登录':<20}")
|
||
print("-" * 70)
|
||
|
||
for i, admin in enumerate(admins, 1):
|
||
status = "激活" if admin.is_active else "禁用"
|
||
created_at = admin.created_at.strftime('%Y-%m-%d %H:%M:%S') if admin.created_at else "未知"
|
||
last_login = admin.last_login.strftime('%Y-%m-%d %H:%M:%S') if admin.last_login else "从未登录"
|
||
|
||
print(f"{i:<4} {admin.student_number:<15} {status:<8} {created_at:<20} {last_login:<20}")
|
||
|
||
|
||
def main():
|
||
"""主函数"""
|
||
while True:
|
||
print("\n" + "=" * 50)
|
||
print("管理员用户管理")
|
||
print("=" * 50)
|
||
print("1. 创建单个管理员用户")
|
||
print("2. 批量创建管理员用户")
|
||
print("3. 查看管理员列表")
|
||
print("4. 退出")
|
||
print("-" * 50)
|
||
|
||
choice = input("请选择操作 (1-4): ").strip()
|
||
|
||
if choice == '1':
|
||
create_admin_user()
|
||
elif choice == '2':
|
||
batch_create_admins()
|
||
elif choice == '3':
|
||
list_admins()
|
||
elif choice == '4':
|
||
print("再见!")
|
||
break
|
||
else:
|
||
print("无效选择,请重新输入!")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
try:
|
||
main()
|
||
except KeyboardInterrupt:
|
||
print("\n\n程序被中断退出")
|
||
except Exception as e:
|
||
print(f"\n程序运行出错: {e}")
|
||
import traceback
|
||
|
||
traceback.print_exc()
|
||
# !/usr/bin/env python3
|
||
# -*- coding: utf-8 -*-
|
||
"""
|
||
创建管理员用户的脚本
|
||
使用方法: python create_admin.py
|
||
"""
|
||
|
||
import sys
|
||
import os
|
||
from getpass import getpass
|
||
|
||
# 添加项目根目录到Python路径
|
||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||
|
||
from init_db import create_app
|
||
from app.models import db, User
|
||
from app.utils.database import safe_add_and_commit
|
||
|
||
|
||
def create_admin_user():
|
||
"""创建管理员用户"""
|
||
app = create_app()
|
||
|
||
with app.app_context():
|
||
print("=" * 50)
|
||
print("创建管理员用户")
|
||
print("=" * 50)
|
||
|
||
# 输入管理员信息
|
||
while True:
|
||
student_number = input("请输入管理员账号(学号格式): ").strip()
|
||
if not student_number:
|
||
print("账号不能为空,请重新输入!")
|
||
continue
|
||
|
||
# 检查账号是否已存在
|
||
existing_user = User.query.filter_by(student_number=student_number).first()
|
||
if existing_user:
|
||
print(f"账号 {student_number} 已存在!")
|
||
choice = input("是否要更新该用户为管理员?(y/n): ").lower()
|
||
if choice == 'y':
|
||
# 更新现有用户为管理员
|
||
existing_user.role = 'admin'
|
||
|
||
# 询问是否要重置密码
|
||
reset_pwd = input("是否要重置密码?(y/n): ").lower()
|
||
if reset_pwd == 'y':
|
||
while True:
|
||
password = getpass("请输入新密码: ")
|
||
if len(password) < 6:
|
||
print("密码长度至少6位,请重新输入!")
|
||
continue
|
||
|
||
confirm_password = getpass("请确认密码: ")
|
||
if password != confirm_password:
|
||
print("两次输入的密码不一致,请重新输入!")
|
||
continue
|
||
|
||
existing_user.set_password(password)
|
||
break
|
||
|
||
success, error = safe_add_and_commit(existing_user)
|
||
if success:
|
||
print(f"用户 {student_number} 已成功更新为管理员!")
|
||
else:
|
||
print(f"更新失败: {error}")
|
||
return
|
||
else:
|
||
continue
|
||
else:
|
||
break
|
||
|
||
# 输入密码
|
||
while True:
|
||
password = getpass("请输入管理员密码: ")
|
||
if len(password) < 6:
|
||
print("密码长度至少6位,请重新输入!")
|
||
continue
|
||
|
||
confirm_password = getpass("请确认密码: ")
|
||
if password != confirm_password:
|
||
print("两次输入的密码不一致,请重新输入!")
|
||
continue
|
||
break
|
||
|
||
# 创建管理员用户
|
||
admin_user = User(
|
||
student_number=student_number,
|
||
role='admin',
|
||
is_active=True
|
||
)
|
||
admin_user.set_password(password)
|
||
|
||
# 保存到数据库
|
||
success, error = safe_add_and_commit(admin_user)
|
||
|
||
if success:
|
||
print(f"\n✅ 管理员用户创建成功!")
|
||
print(f"账号: {student_number}")
|
||
print(f"角色: 管理员")
|
||
print(f"状态: 激活")
|
||
else:
|
||
print(f"\n❌ 创建失败: {error}")
|
||
|
||
|
||
def batch_create_admins():
|
||
"""批量创建管理员用户"""
|
||
app = create_app()
|
||
|
||
with app.app_context():
|
||
print("=" * 50)
|
||
print("批量创建管理员用户")
|
||
print("=" * 50)
|
||
print("输入格式: 账号,密码")
|
||
print("例如: admin001,123456")
|
||
print("输入 'done' 完成输入")
|
||
print("-" * 50)
|
||
|
||
admin_list = []
|
||
|
||
while True:
|
||
user_input = input("请输入管理员信息(账号,密码): ").strip()
|
||
|
||
if user_input.lower() == 'done':
|
||
break
|
||
|
||
if ',' not in user_input:
|
||
print("格式错误!请使用 '账号,密码' 格式")
|
||
continue
|
||
|
||
try:
|
||
student_number, password = user_input.split(',', 1)
|
||
student_number = student_number.strip()
|
||
password = password.strip()
|
||
|
||
if not student_number or not password:
|
||
print("账号和密码都不能为空!")
|
||
continue
|
||
|
||
if len(password) < 6:
|
||
print("密码长度至少6位!")
|
||
continue
|
||
|
||
# 检查是否已存在
|
||
existing_user = User.query.filter_by(student_number=student_number).first()
|
||
if existing_user:
|
||
print(f"账号 {student_number} 已存在,跳过...")
|
||
continue
|
||
|
||
admin_list.append((student_number, password))
|
||
print(f"✓ 已添加: {student_number}")
|
||
|
||
except ValueError:
|
||
print("格式错误!请使用 '账号,密码' 格式")
|
||
continue
|
||
|
||
if not admin_list:
|
||
print("没有有效的管理员信息,退出...")
|
||
return
|
||
|
||
# 确认创建
|
||
print(f"\n准备创建 {len(admin_list)} 个管理员用户:")
|
||
for student_number, _ in admin_list:
|
||
print(f"- {student_number}")
|
||
|
||
confirm = input("\n确认创建?(y/n): ").lower()
|
||
if confirm != 'y':
|
||
print("已取消创建")
|
||
return
|
||
|
||
# 批量创建
|
||
success_count = 0
|
||
fail_count = 0
|
||
|
||
for student_number, password in admin_list:
|
||
admin_user = User(
|
||
student_number=student_number,
|
||
role='admin',
|
||
is_active=True
|
||
)
|
||
admin_user.set_password(password)
|
||
|
||
success, error = safe_add_and_commit(admin_user)
|
||
|
||
if success:
|
||
print(f"✅ {student_number} 创建成功")
|
||
success_count += 1
|
||
else:
|
||
print(f"❌ {student_number} 创建失败: {error}")
|
||
fail_count += 1
|
||
|
||
print(f"\n批量创建完成:")
|
||
print(f"成功: {success_count}")
|
||
print(f"失败: {fail_count}")
|
||
|
||
|
||
def list_admins():
|
||
"""列出所有管理员用户"""
|
||
app = create_app()
|
||
|
||
with app.app_context():
|
||
print("=" * 50)
|
||
print("管理员用户列表")
|
||
print("=" * 50)
|
||
|
||
admins = User.query.filter_by(role='admin').all()
|
||
|
||
if not admins:
|
||
print("暂无管理员用户")
|
||
return
|
||
|
||
print(f"{'序号':<4} {'账号':<15} {'状态':<8} {'创建时间':<20} {'最后登录':<20}")
|
||
print("-" * 70)
|
||
|
||
for i, admin in enumerate(admins, 1):
|
||
status = "激活" if admin.is_active else "禁用"
|
||
created_at = admin.created_at.strftime('%Y-%m-%d %H:%M:%S') if admin.created_at else "未知"
|
||
last_login = admin.last_login.strftime('%Y-%m-%d %H:%M:%S') if admin.last_login else "从未登录"
|
||
|
||
print(f"{i:<4} {admin.student_number:<15} {status:<8} {created_at:<20} {last_login:<20}")
|
||
|
||
|
||
def main():
|
||
"""主函数"""
|
||
while True:
|
||
print("\n" + "=" * 50)
|
||
print("管理员用户管理")
|
||
print("=" * 50)
|
||
print("1. 创建单个管理员用户")
|
||
print("2. 批量创建管理员用户")
|
||
print("3. 查看管理员列表")
|
||
print("4. 退出")
|
||
print("-" * 50)
|
||
|
||
choice = input("请选择操作 (1-4): ").strip()
|
||
|
||
if choice == '1':
|
||
create_admin_user()
|
||
elif choice == '2':
|
||
batch_create_admins()
|
||
elif choice == '3':
|
||
list_admins()
|
||
elif choice == '4':
|
||
print("再见!")
|
||
break
|
||
else:
|
||
print("无效选择,请重新输入!")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
try:
|
||
main()
|
||
except KeyboardInterrupt:
|
||
print("\n\n程序被中断退出")
|
||
except Exception as e:
|
||
print(f"\n程序运行出错: {e}")
|
||
import traceback
|
||
|
||
traceback.print_exc()
|