好的,我们来整理一下脚本,新增把枚举结果导出到 Excel 的功能。这里使用 openpyxl 库来生成 Excel 文件。
安装依赖
如果还没安装 pymysql 和 openpyxl,可以运行:
pip install pymysql openpyxl
优化后的脚本(导出 Excel)
import pymysql
from openpyxl import Workbook
from openpyxl.styles import Font
# 数据库配置
DB_CONFIG = {
'host': 'localhost',
'user': 'root',
'password': 'yourpassword',
'database': 'your_database',
'port': 3306,
'charset': 'utf8mb4'
}
# 常见敏感字段(中文和拼音)
SENSITIVE_KEYWORDS = [
'name', 'xingming', 'username', 'zhanghao', 'account',
'phone', 'shouji', 'mobile', 'tel', 'email', 'dizhi', 'address',
'id', 'sfz', 'sfzh', 'shenfenzheng', 'card', 'bank', 'yinhangka',
'password', 'mima', 'pwd', 'token', 'secret'
]
def connect_db():
"""建立数据库连接"""
try:
conn = pymysql.connect(**DB_CONFIG)
print("✅ 数据库连接成功")
return conn
except Exception as e:
print(f"❌ 数据库连接失败: {e}")
return None
def enumerate_server_info(conn, wb):
"""枚举服务器信息"""
sheet = wb.create_sheet(title="服务器信息")
with conn.cursor() as cursor:
# 标题
sheet.append(["项目", "值"])
sheet["A1"].font = sheet["B1"].font = Font(bold=True)
# 数据库版本
cursor.execute("SELECT VERSION()")
version = cursor.fetchone()[0]
sheet.append(["数据库版本", version])
# 获取关键配置
cursor.execute("""
SHOW VARIABLES
WHERE Variable_name IN ('port', 'datadir', 'version_compile_os', 'character_set_server')
""")
for var, value in cursor.fetchall():
sheet.append([var, value])
# 枚举用户信息
sheet.append([])
sheet.append(["数据库用户", "认证方式"])
sheet["A6"].font = sheet["B6"].font = Font(bold=True)
cursor.execute("SELECT user, host, authentication_string FROM mysql.user")
for user, host, auth in cursor.fetchall():
sheet.append([f"{user}@{host}", auth[:20] + "..." if auth else "N/A"])
def search_sensitive_data(conn, wb):
"""查找可能的敏感数据"""
sheet = wb.create_sheet(title="敏感数据检测")
sheet.append(["表名", "可能的敏感字段", "数据样本"])
sheet["A1"].font = sheet["B1"].font = sheet["C1"].font = Font(bold=True)
with conn.cursor() as cursor:
# 枚举所有表
cursor.execute("SHOW TABLES")
tables = [table[0] for table in cursor.fetchall()]
print(f"🔍 发现 {len(tables)} 张表,开始分析...")
for table in tables:
# 获取表字段
cursor.execute(f"DESCRIBE
columns = [col[0] for col in cursor.fetchall()]
# 查找可能的敏感字段
sensitive_cols = [col for col in columns if any(kw in col.lower() for kw in SENSITIVE_KEYWORDS)]
if sensitive_cols:
# 查询样本数据
cursor.execute(f"SELECT {', '.join(sensitive_cols)} FROM
samples = cursor.fetchall()
# 写入 Excel
for row in samples:
sheet.append([table, ", ".join(sensitive_cols), str(row)])
print(f"⚠️ 表 '{table}' 可能存在敏感字段: {sensitive_cols}")
def main():
# 连接数据库
conn = connect_db()
if not conn:
return
# 创建 Excel 工作簿
wb = Workbook()
wb.remove(wb.active) # 删除默认工作表
# 执行枚举操作
enumerate_server_info(conn, wb)
search_sensitive_data(conn, wb)
# 导出 Excel
output_file = "mysql_sensitive_data_enum.xlsx"
wb.save(output_file)
conn.close()
print(f"✅ 枚举完成,结果已导出到 '{output_file}'")
if name == "main":
main()
输出示例:
1. 生成名为 mysql_sensitive_data_enum.xlsx 的 Excel 文件。
2. Excel 内包含两个工作表:
服务器信息:列出数据库版本、关键配置、用户信息等。
敏感数据检测:显示可能存在敏感信息的表、字段和数据样本。
Excel 内容示例:
服务器信息
敏感数据检测
总结:
1. 自动导出 Excel,方便数据分析和归档。
2. 结构清晰:分工作表展示服务器信息和敏感字段检测结果。
3. 易扩展:可以添加更多检测逻辑,如正则匹配、字段类型判断等。
你希望再加点什么功能?比如:
导出 JSON 格式?
检测空密码或弱密码?
增加字段类型分析?
随时告诉我,我们继续优化!
安装依赖
如果还没安装 pymysql 和 openpyxl,可以运行:
pip install pymysql openpyxl
优化后的脚本(导出 Excel)
import pymysql
from openpyxl import Workbook
from openpyxl.styles import Font
# 数据库配置
DB_CONFIG = {
'host': 'localhost',
'user': 'root',
'password': 'yourpassword',
'database': 'your_database',
'port': 3306,
'charset': 'utf8mb4'
}
# 常见敏感字段(中文和拼音)
SENSITIVE_KEYWORDS = [
'name', 'xingming', 'username', 'zhanghao', 'account',
'phone', 'shouji', 'mobile', 'tel', 'email', 'dizhi', 'address',
'id', 'sfz', 'sfzh', 'shenfenzheng', 'card', 'bank', 'yinhangka',
'password', 'mima', 'pwd', 'token', 'secret'
]
def connect_db():
"""建立数据库连接"""
try:
conn = pymysql.connect(**DB_CONFIG)
print("✅ 数据库连接成功")
return conn
except Exception as e:
print(f"❌ 数据库连接失败: {e}")
return None
def enumerate_server_info(conn, wb):
"""枚举服务器信息"""
sheet = wb.create_sheet(title="服务器信息")
with conn.cursor() as cursor:
# 标题
sheet.append(["项目", "值"])
sheet["A1"].font = sheet["B1"].font = Font(bold=True)
# 数据库版本
cursor.execute("SELECT VERSION()")
version = cursor.fetchone()[0]
sheet.append(["数据库版本", version])
# 获取关键配置
cursor.execute("""
SHOW VARIABLES
WHERE Variable_name IN ('port', 'datadir', 'version_compile_os', 'character_set_server')
""")
for var, value in cursor.fetchall():
sheet.append([var, value])
# 枚举用户信息
sheet.append([])
sheet.append(["数据库用户", "认证方式"])
sheet["A6"].font = sheet["B6"].font = Font(bold=True)
cursor.execute("SELECT user, host, authentication_string FROM mysql.user")
for user, host, auth in cursor.fetchall():
sheet.append([f"{user}@{host}", auth[:20] + "..." if auth else "N/A"])
def search_sensitive_data(conn, wb):
"""查找可能的敏感数据"""
sheet = wb.create_sheet(title="敏感数据检测")
sheet.append(["表名", "可能的敏感字段", "数据样本"])
sheet["A1"].font = sheet["B1"].font = sheet["C1"].font = Font(bold=True)
with conn.cursor() as cursor:
# 枚举所有表
cursor.execute("SHOW TABLES")
tables = [table[0] for table in cursor.fetchall()]
print(f"🔍 发现 {len(tables)} 张表,开始分析...")
for table in tables:
# 获取表字段
cursor.execute(f"DESCRIBE
{table}")columns = [col[0] for col in cursor.fetchall()]
# 查找可能的敏感字段
sensitive_cols = [col for col in columns if any(kw in col.lower() for kw in SENSITIVE_KEYWORDS)]
if sensitive_cols:
# 查询样本数据
cursor.execute(f"SELECT {', '.join(sensitive_cols)} FROM
{table} LIMIT 5")samples = cursor.fetchall()
# 写入 Excel
for row in samples:
sheet.append([table, ", ".join(sensitive_cols), str(row)])
print(f"⚠️ 表 '{table}' 可能存在敏感字段: {sensitive_cols}")
def main():
# 连接数据库
conn = connect_db()
if not conn:
return
# 创建 Excel 工作簿
wb = Workbook()
wb.remove(wb.active) # 删除默认工作表
# 执行枚举操作
enumerate_server_info(conn, wb)
search_sensitive_data(conn, wb)
# 导出 Excel
output_file = "mysql_sensitive_data_enum.xlsx"
wb.save(output_file)
conn.close()
print(f"✅ 枚举完成,结果已导出到 '{output_file}'")
if name == "main":
main()
输出示例:
1. 生成名为 mysql_sensitive_data_enum.xlsx 的 Excel 文件。
2. Excel 内包含两个工作表:
服务器信息:列出数据库版本、关键配置、用户信息等。
敏感数据检测:显示可能存在敏感信息的表、字段和数据样本。
Excel 内容示例:
服务器信息
敏感数据检测
总结:
1. 自动导出 Excel,方便数据分析和归档。
2. 结构清晰:分工作表展示服务器信息和敏感字段检测结果。
3. 易扩展:可以添加更多检测逻辑,如正则匹配、字段类型判断等。
你希望再加点什么功能?比如:
导出 JSON 格式?
检测空密码或弱密码?
增加字段类型分析?
随时告诉我,我们继续优化!