def get_mysql_status(conn):
cursor = conn.cursor()
try:
1、连接数
cursor.execute(SHOW STATUS LIKE 'Connections';)
connections = cursor.fetchall()
total_connections = connections[0][1] if connections else 0
2、慢查询
cursor.execute(SHOW ENGINE INNODB STATUS LIKE 'Slow_queries';)
slow_queries = cursor.fetchone()
slow_query_count = slow_queries[1] if slow_queries else 0
3、锁
cursor.execute(SHOW ENGINE INNODB STATUS LIKE 'Locks';)
locks = cursor.fetchone()
lock_type = locks[1] if locks else None
4、表空间使用
cursor.execute(SHOW TABLE STATUS WHERE Engine = 'InnoDB';)
tables = cursor.fetchall()
table_space_usage = sum(t[10] for t in tables) / (1024 * 1024 * 1024) GB
5、错误日志
cursor.execute(SHOW GLOBAL STATUS LIKE 'Error_log_count';)
error_count = cursor.fetchone()[1] if cursor else 0
try:
with smtplib.SMTP(smtp.65.hk, 587) as server:
server.starttls()
server.login(ALERT_EMAIL, your-email-password)
server.sendmail(ALERT_EMAIL, ALERT_EMAIL, msg.as_string())
print(邮件发送成功)
except Exception as e:
print(f发送邮件失败: {e})
elif alert_type == sms:
示例:使用Twilio发送短信
需要替换为实际的短信服务API
print(短信发送中...) 实际需替换为真实API调用
else:
print(未识别的告警类型)
def check_alerts(status):
alerts = []
if status[total_connections] 100:
alerts.append(连接数过高)
if status[slow_queries] 100:
alerts.append(慢查询过多)
if status[table_space_usage] 0.8:
alerts.append(表空间使用过高)
if status[error_count] 5:
alerts.append(错误日志较多)
if alerts:
send_alert(email, ALERT_MSG.format(reason=, .join(alerts)))
print(告警已发送)
else:
print(一切正常)
def main():
while True:
conn = connect_db()
if conn:
status = get_mysql_status(conn)
check_alerts(status)
conn.close()
time.sleep(MONITOR_INTERVAL)