1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
|
""" Oracle 数据库日常巡检脚本 (Python 版本) 功能:多实例巡检、HTML报告、邮件发送、历史数据存储 作者:OCM DBA @ 4dba.top 日期:2026-06-10 """
import os import sys import json import logging import smtplib from datetime import datetime, timedelta from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email import encoders from dataclasses import dataclass, field from typing import List, Dict, Optional
try: import oracledb except ImportError: print("请先安装 oracledb: pip install oracledb") sys.exit(1)
DB_INSTANCES = [ { "name": "PROD1", "host": "192.168.1.100", "port": 1521, "service": "PRODDB", "user": "sys", "password": "your_password", "role": "SYSDBA", }, { "name": "PROD2", "host": "192.168.1.101", "port": 1521, "service": "PRODDB2", "user": "sys", "password": "your_password", "role": "SYSDBA", }, { "name": "TEST1", "host": "192.168.1.200", "port": 1521, "service": "TESTDB", "user": "sys", "password": "your_password", "role": "SYSDBA", }, ]
THRESHOLDS = { "tablespace_warn": 85, "tablespace_crit": 95, "asm_warn": 80, "session_warn": 80, "arch_count_warn": 200, "long_txn_hours": 1, }
MAIL_CONFIG = { "smtp_server": "smtp.4dba.top", "smtp_port": 465, "smtp_ssl": True, "username": "alert@4dba.top", "password": "smtp_password", "from_addr": "alert@4dba.top", "to_addrs": ["dba-team@4dba.top"], }
REPORT_DIR = "/home/oracle/dba/scripts/reports" HISTORY_DB = "/home/oracle/dba/scripts/data/history.db"
logging.basicConfig( level=logging.INFO, format="[%(asctime)s] [%(levelname)s] %(message)s", datefmt="%Y-%m-%d %H:%M:%S", ) logger = logging.getLogger(__name__)
@dataclass class CheckResult: """单项检查结果""" category: str item: str status: str message: str details: Optional[str] = None timestamp: str = field(default_factory=lambda: datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
@dataclass class InstanceReport: """单实例巡检报告""" instance_name: str host: str check_time: str results: List[CheckResult] = field(default_factory=list) connected: bool = False
@property def error_count(self) -> int: return sum(1 for r in self.results if r.status in ("ERROR", "CRITICAL"))
@property def warn_count(self) -> int: return sum(1 for r in self.results if r.status == "WARN")
@property def ok_count(self) -> int: return sum(1 for r in self.results if r.status == "OK")
class OracleChecker: """Oracle 巡检类"""
def __init__(self, instance_config: dict): self.config = instance_config self.name = instance_config["name"] self.conn = None self.report = InstanceReport( instance_name=self.name, host=instance_config["host"], check_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"), )
def connect(self) -> bool: """连接数据库""" try: dsn = oracledb.makedsn( self.config["host"], self.config["port"], service_name=self.config["service"], ) self.conn = oracledb.connect( user=self.config["user"], password=self.config["password"], dsn=dsn, mode=oracledb.SYSDBA if self.config.get("role") == "SYSDBA" else 0, ) self.report.connected = True logger.info(f"[{self.name}] 数据库连接成功") return True except Exception as e: logger.error(f"[{self.name}] 数据库连接失败: {e}") self.report.results.append(CheckResult( category="连接状态", item="数据库连接", status="CRITICAL", message=f"无法连接数据库: {str(e)}", )) return False
def disconnect(self): """断开数据库连接""" if self.conn: try: self.conn.close() except Exception: pass
def _query(self, sql: str, fetchall: bool = True): """执行查询并返回结果""" try: cursor = self.conn.cursor() cursor.execute(sql) if fetchall: columns = [desc[0] for desc in cursor.description] rows = cursor.fetchall() return columns, rows else: return cursor.fetchone() except Exception as e: logger.error(f"[{self.name}] SQL 执行失败: {e}") return None, None
def check_instance_status(self): """检查实例状态""" logger.info(f"[{self.name}] 检查实例状态...") cols, rows = self._query(""" SELECT INSTANCE_NAME, HOST_NAME, VERSION, STATUS, DATABASE_STATUS, TO_CHAR(STARTUP_TIME, 'YYYY-MM-DD HH24:MI:SS') AS STARTUP_TIME FROM V$INSTANCE """) if rows: row = rows[0] status = row[3] if status == "OPEN": self.report.results.append(CheckResult( category="实例状态", item="数据库实例", status="OK", message=f"实例 {row[0]} 状态正常 (OPEN)", details=f"版本: {row[2]}, 主机: {row[1]}, 启动时间: {row[5]}", )) else: self.report.results.append(CheckResult( category="实例状态", item="数据库实例", status="ERROR", message=f"实例状态异常: {status}", ))
def check_tablespace(self): """检查表空间使用率""" logger.info(f"[{self.name}] 检查表空间使用率...") cols, rows = self._query(""" SELECT a.tablespace_name, ROUND(a.total_mb, 2) AS total_mb, ROUND(a.total_mb - NVL(b.free_mb, 0), 2) AS used_mb, ROUND(NVL(b.free_mb, 0), 2) AS free_mb, ROUND((a.total_mb - NVL(b.free_mb, 0)) / a.total_mb * 100, 2) AS used_pct FROM ( SELECT tablespace_name, SUM(bytes) / 1024 / 1024 AS total_mb FROM dba_data_files GROUP BY tablespace_name ) a LEFT JOIN ( SELECT tablespace_name, SUM(bytes) / 1024 / 1024 AS free_mb FROM dba_free_space GROUP BY tablespace_name ) b ON a.tablespace_name = b.tablespace_name ORDER BY used_pct DESC """) if rows: for row in rows: ts_name, total, used, free, pct = row if pct >= THRESHOLDS["tablespace_crit"]: status = "CRITICAL" elif pct >= THRESHOLDS["tablespace_warn"]: status = "WARN" else: status = "OK" self.report.results.append(CheckResult( category="空间管理", item=f"表空间 {ts_name}", status=status, message=f"使用率 {pct}% (总 {total}MB, 已用 {used}MB)", ))
def check_asm_diskgroup(self): """检查 ASM 磁盘组""" logger.info(f"[{self.name}] 检查 ASM 磁盘组...") cols, rows = self._query(""" SELECT NAME, STATE, ROUND(TOTAL_MB/1024, 2) AS total_gb, ROUND(FREE_MB/1024, 2) AS free_gb, ROUND((TOTAL_MB - FREE_MB) / TOTAL_MB * 100, 2) AS used_pct FROM V$ASM_DISKGROUP """) if rows: for row in rows: dg_name, state, total, free, pct = row if pct >= THRESHOLDS["asm_warn"]: status = "WARN" else: status = "OK" self.report.results.append(CheckResult( category="空间管理", item=f"ASM 磁盘组 {dg_name}", status=status, message=f"状态: {state}, 使用率 {pct}% (总 {total}GB, 空闲 {free}GB)", )) else: logger.info(f"[{self.name}] 未检测到 ASM 磁盘组")
def check_backup_status(self): """检查 RMAN 备份状态""" logger.info(f"[{self.name}] 检查 RMAN 备份状态...") cols, rows = self._query(""" SELECT TO_CHAR(START_TIME, 'YYYY-MM-DD HH24:MI:SS') AS start_time, STATUS, INPUT_TYPE, INPUT_BYTES_DISPLAY, TIME_TAKEN_DISPLAY FROM V$RMAN_BACKUP_JOB_DETAILS WHERE START_TIME > SYSDATE - 2 ORDER BY START_TIME DESC """) if rows: latest = rows[0] if latest[1] == "COMPLETED": self.report.results.append(CheckResult( category="备份状态", item="RMAN 备份", status="OK", message=f"最近备份成功 ({latest[2]})", details=f"时间: {latest[0]}, 大小: {latest[3]}, 耗时: {latest[4]}", )) else: self.report.results.append(CheckResult( category="备份状态", item="RMAN 备份", status="ERROR", message=f"最近备份状态异常: {latest[1]}", details=f"时间: {latest[0]}, 类型: {latest[2]}", )) details = "\n".join([ f" {r[0]} | {r[1]} | {r[2]} | {r[3]} | {r[4]}" for r in rows ]) logger.info(f"[{self.name}] 备份历史:\n{details}") else: self.report.results.append(CheckResult( category="备份状态", item="RMAN 备份", status="WARN", message="最近 2 天无备份记录", ))
def check_archive_log(self): """检查归档日志生成速率""" logger.info(f"[{self.name}] 检查归档日志...") cols, rows = self._query(""" SELECT COUNT(*) AS cnt, ROUND(NVL(SUM(BLOCKS * BLOCK_SIZE) / 1024 / 1024, 0), 2) AS size_mb FROM V$ARCHIVED_LOG WHERE FIRST_TIME > SYSDATE - 1 AND DEST_ID = 1 """) if rows: cnt, size_mb = rows[0] if cnt > THRESHOLDS["arch_count_warn"]: status = "WARN" else: status = "OK" self.report.results.append(CheckResult( category="归档日志", item="归档生成速率", status=status, message=f"过去 24 小时: {cnt} 个, {size_mb} MB", ))
def check_alert_log(self): """检查告警日志中的 ORA- 错误""" logger.info(f"[{self.name}] 检查告警日志...") cols, rows = self._query(""" SELECT MESSAGE_TEXT FROM V$DIAG_ALERT_EXT WHERE ORIGINATING_TIMESTAMP > SYSTIMESTAMP - INTERVAL '1' DAY AND MESSAGE_TEXT LIKE '%ORA-%' AND MESSAGE_TEXT NOT LIKE '%ORA-00000%' ORDER BY ORIGINATING_TIMESTAMP DESC """) if rows: ora_errors = [r[0][:200] for r in rows[:20]] critical = [e for e in ora_errors if "ORA-600" in e or "ORA-7445" in e] if critical: self.report.results.append(CheckResult( category="告警日志", item="严重错误", status="CRITICAL", message=f"发现 {len(critical)} 个严重内部错误", details="\n".join(critical[:5]), )) self.report.results.append(CheckResult( category="告警日志", item="ORA- 错误", status="WARN" if len(rows) > 10 else "OK", message=f"过去 24 小时: {len(rows)} 条 ORA- 错误", details="\n".join(ora_errors[:5]), )) else: self.report.results.append(CheckResult( category="告警日志", item="ORA- 错误", status="OK", message="过去 24 小时无 ORA- 错误", ))
def check_sessions(self): """检查会话数""" logger.info(f"[{self.name}] 检查会话数...") cols, rows = self._query(""" SELECT (SELECT COUNT(*) FROM V$SESSION WHERE STATUS = 'ACTIVE' AND TYPE = 'USER') AS active, (SELECT COUNT(*) FROM V$SESSION WHERE STATUS = 'INACTIVE' AND TYPE = 'USER') AS inactive, (SELECT COUNT(*) FROM V$SESSION WHERE TYPE = 'USER') AS total, (SELECT TO_NUMBER(VALUE) FROM V$PARAMETER WHERE NAME = 'sessions') AS max_sessions FROM DUAL """) if rows: active, inactive, total, max_sessions = rows[0] pct = round(total / max_sessions * 100, 1) if max_sessions else 0 status = "WARN" if pct >= THRESHOLDS["session_warn"] else "OK" self.report.results.append(CheckResult( category="会话信息", item="会话统计", status=status, message=f"活跃: {active}, 空闲: {inactive}, 总计: {total}/{max_sessions} ({pct}%)", ))
def check_invalid_objects(self): """检查无效对象""" logger.info(f"[{self.name}] 检查无效对象...") cols, rows = self._query(""" SELECT COUNT(*) FROM DBA_OBJECTS WHERE STATUS = 'INVALID' """) if rows: cnt = rows[0][0] if cnt > 0: self.report.results.append(CheckResult( category="对象状态", item="无效对象", status="WARN", message=f"存在 {cnt} 个无效对象", )) else: self.report.results.append(CheckResult( category="对象状态", item="无效对象", status="OK", message="无无效对象", ))
def run_all_checks(self): """执行所有巡检项""" if not self.connect(): return self.report
checks = [ self.check_instance_status, self.check_tablespace, self.check_asm_diskgroup, self.check_backup_status, self.check_archive_log, self.check_alert_log, self.check_sessions, self.check_invalid_objects, ]
for check_func in checks: try: check_func() except Exception as e: logger.error(f"[{self.name}] {check_func.__name__} 执行失败: {e}") self.report.results.append(CheckResult( category="脚本错误", item=check_func.__name__, status="ERROR", message=f"检查执行异常: {str(e)}", ))
self.disconnect() return self.report
class ReportGenerator: """报告生成器"""
@staticmethod def generate_html(reports: List[InstanceReport]) -> str: """生成 HTML 格式报告""" now = datetime.now().strftime("%Y-%m-%d %H:%M:%S") total_errors = sum(r.error_count for r in reports) total_warns = sum(r.warn_count for r in reports)
html = f"""<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Oracle 日常巡检报告</title> <style> body {{ font-family: "Microsoft YaHei", Arial, sans-serif; margin: 20px; background: #f5f5f5; }} .container {{ max-width: 1200px; margin: 0 auto; }} .header {{ background: #2c3e50; color: white; padding: 20px; border-radius: 8px 8px 0 0; }} .header h1 {{ margin: 0; font-size: 24px; }} .header .time {{ color: #bdc3c7; margin-top: 8px; }} .summary {{ background: white; padding: 20px; border-bottom: 1px solid #ddd; display: flex; gap: 20px; }} .summary-item {{ flex: 1; text-align: center; padding: 15px; border-radius: 8px; }} .summary-item.ok {{ background: #d5f4e6; color: #27ae60; }} .summary-item.warn {{ background: #fef9e7; color: #f39c12; }} .summary-item.error {{ background: #fadbd8; color: #e74c3c; }} .summary-item h3 {{ margin: 0; font-size: 32px; }} .summary-item p {{ margin: 5px 0 0 0; font-size: 14px; }} .instance {{ background: white; margin: 20px 0; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }} .instance-header {{ background: #34495e; color: white; padding: 15px 20px; font-size: 18px; }} .instance-header .host {{ color: #bdc3c7; font-size: 14px; }} table {{ width: 100%; border-collapse: collapse; }} th {{ background: #ecf0f1; padding: 12px 15px; text-align: left; font-size: 14px; }} td {{ padding: 10px 15px; border-bottom: 1px solid #ecf0f1; font-size: 13px; }} tr:hover {{ background: #f8f9fa; }} .status-ok {{ color: #27ae60; font-weight: bold; }} .status-warn {{ color: #f39c12; font-weight: bold; }} .status-error {{ color: #e74c3c; font-weight: bold; }} .status-critical {{ color: #c0392b; font-weight: bold; background: #fadbd8; }} .details {{ color: #7f8c8d; font-size: 12px; margin-top: 4px; }} .footer {{ text-align: center; padding: 20px; color: #95a5a6; font-size: 12px; }} </style> </head> <body> <div class="container"> <div class="header"> <h1>Oracle 数据库日常巡检报告</h1> <div class="time">巡检时间: {now} | 实例数量: {len(reports)}</div> </div> <div class="summary"> <div class="summary-item {'error' if total_errors > 0 else 'ok'}"> <h3>{total_errors}</h3> <p>错误</p> </div> <div class="summary-item {'warn' if total_warns > 0 else 'ok'}"> <h3>{total_warns}</h3> <p>告警</p> </div> <div class="summary-item ok"> <h3>{len(reports)}</h3> <p>实例</p> </div> </div> """ for report in reports: status_color = "error" if report.error_count > 0 else ("warn" if report.warn_count > 0 else "ok") html += f""" <div class="instance"> <div class="instance-header"> {report.instance_name} <span class="host">({report.host})</span> <span style="float:right" class="status-{status_color}"> {'有告警' if status_color != 'ok' else '正常'} - 错误:{report.error_count} 告警:{report.warn_count} </span> </div> <table> <tr><th>分类</th><th>检查项</th><th>状态</th><th>结果</th></tr> """ for r in report.results: status_class = f"status-{r.status.lower()}" status_text = {"OK": "✅ 正常", "WARN": "⚠️ 告警", "ERROR": "❌ 错误", "CRITICAL": "🔥 严重"}.get(r.status, r.status) details_html = f'<div class="details">{r.details}</div>' if r.details else '' html += f""" <tr> <td>{r.category}</td> <td>{r.item}</td> <td class="{status_class}">{status_text}</td> <td>{r.message}{details_html}</td> </tr> """ html += " </table>\n</div>\n"
html += f""" <div class="footer"> Oracle 巡检报告 - 生成于 {now} - Powered by Python + oracledb </div> </div> </body> </html>""" return html
class MailSender: """邮件发送类"""
@staticmethod def send(subject: str, html_body: str, attachment_path: Optional[str] = None): """发送 HTML 邮件""" cfg = MAIL_CONFIG msg = MIMEMultipart() msg["From"] = cfg["from_addr"] msg["To"] = ", ".join(cfg["to_addrs"]) msg["Subject"] = subject
msg.attach(MIMEText(html_body, "html", "utf-8"))
if attachment_path and os.path.exists(attachment_path): with open(attachment_path, "rb") as f: part = MIMEBase("application", "octet-stream") part.set_payload(f.read()) encoders.encode_base64(part) part.add_header( "Content-Disposition", f"attachment; filename=os.path.basename(attachment_path)", ) msg.attach(part)
try: if cfg["smtp_ssl"]: server = smtplib.SMTP_SSL(cfg["smtp_server"], cfg["smtp_port"]) else: server = smtplib.SMTP(cfg["smtp_server"], cfg["smtp_port"]) server.starttls() server.login(cfg["username"], cfg["password"]) server.sendmail(cfg["from_addr"], cfg["to_addrs"], msg.as_string()) server.quit() logger.info(f"邮件发送成功: {subject}") except Exception as e: logger.error(f"邮件发送失败: {e}")
def main(): """主函数""" logger.info("=" * 60) logger.info("Oracle 日常巡检开始") logger.info("=" * 60)
os.makedirs(REPORT_DIR, exist_ok=True) reports = []
for instance_cfg in DB_INSTANCES: logger.info(f"--- 开始巡检: {instance_cfg['name']} ---") checker = OracleChecker(instance_cfg) report = checker.run_all_checks() reports.append(report)
html = ReportGenerator.generate_html(reports) report_file = os.path.join( REPORT_DIR, f"daily_check_{datetime.now().strftime('%Y%m%d_%H%M%S')}.html" ) with open(report_file, "w", encoding="utf-8") as f: f.write(html) logger.info(f"HTML 报告已生成: {report_file}")
history_file = os.path.join( REPORT_DIR, f"history_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json" ) history_data = [] for report in reports: instance_data = { "instance": report.instance_name, "host": report.host, "time": report.check_time, "errors": report.error_count, "warnings": report.warn_count, "checks": [ { "category": r.category, "item": r.item, "status": r.status, "message": r.message, } for r in report.results ], } history_data.append(instance_data) with open(history_file, "w", encoding="utf-8") as f: json.dump(history_data, f, ensure_ascii=False, indent=2) logger.info(f"历史数据已保存: {history_file}")
total_errors = sum(r.error_count for r in reports) total_warns = sum(r.warn_count for r in reports)
if total_errors > 0 or total_warns > 0: subject = f"[Oracle巡检-告警] ERR:{total_errors} WARN:{total_warns} - {datetime.now().strftime('%Y%m%d')}" else: subject = f"[Oracle巡检-正常] {datetime.now().strftime('%Y%m%d')}"
MailSender.send(subject, html, report_file)
cutoff = datetime.now() - timedelta(days=30) for f_name in os.listdir(REPORT_DIR): f_path = os.path.join(REPORT_DIR, f_name) if os.path.isfile(f_path): f_mtime = datetime.fromtimestamp(os.path.getmtime(f_path)) if f_mtime < cutoff: os.remove(f_path) logger.info(f"已清理过期文件: {f_name}")
logger.info("=" * 60) logger.info("Oracle 日常巡检完成") logger.info(f"总错误: {total_errors}, 总告警: {total_warns}") logger.info("=" * 60)
if __name__ == "__main__": main()
|