verify_yml.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. # -*- coding: utf-8 -*-
  2. """读取 application.yml 验证 MySQL/Redis 连通性(不打印任何密码)"""
  3. import re
  4. import socket
  5. import pymysql
  6. import urllib.parse
  7. from _root import ROOT
  8. YML = str(ROOT / "yoshop-java/src/main/resources/application.yml")
  9. text = open(YML, encoding="utf-8").read()
  10. def get(pattern, default=""):
  11. m = re.search(pattern, text, re.M)
  12. return m.group(1).strip().strip('"\'') if m else default
  13. url = get(r"url:\s*(\S+)")
  14. user = get(r"username:\s*(\S+)")
  15. # redis 段:从 "redis:" 行开始截取,避免误读 server.port
  16. redis_section = text[text.index("redis:"):]
  17. rhost = re.search(r"host:\s*(\S+)", redis_section).group(1).strip("\"'")
  18. rport = int(re.search(r"port:\s*(\d+)", redis_section).group(1))
  19. # datasource 段的 password 是第一个,redis 段的是最后一个
  20. pwds = re.findall(r"password:\s*(.+)", text)
  21. pwd = pwds[0].strip().strip('"\'') if pwds else ""
  22. rpwd = pwds[-1].strip().strip('"\'') if pwds else ""
  23. m = re.match(r"jdbc:mysql://([^:/]+):(\d+)/([^?]+)", url)
  24. db_host, db_port, db_name = m.group(1), int(m.group(2)), m.group(3)
  25. print(f"MySQL 目标: {db_host}:{db_port}/{db_name} 用户: {user} 密码: {'<已读取,共%d位>' % len(pwd)}")
  26. try:
  27. conn = pymysql.connect(host=db_host, port=db_port, user=user, password=pwd,
  28. database=db_name, connect_timeout=5)
  29. with conn.cursor() as c:
  30. c.execute("SELECT VERSION()")
  31. ver = c.fetchone()[0]
  32. c.execute("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=%s", (db_name,))
  33. tables = c.fetchone()[0]
  34. conn.close()
  35. print(f"[MYSQL OK] 版本 {ver},{db_name} 库共 {tables} 张表")
  36. except Exception as e:
  37. print(f"[MYSQL FAIL] {e}")
  38. print(f"Redis 目标: {rhost}:{rport} 密码: {'<无>' if not rpwd else '<已读取,共%d位>' % len(rpwd)}")
  39. try:
  40. s = socket.create_connection((rhost, rport), timeout=5)
  41. def cmd(*a):
  42. l = f"*{len(a)}\r\n".encode()
  43. for x in a:
  44. b = x.encode()
  45. l += f"${len(b)}\r\n".encode() + b + b"\r\n"
  46. s.sendall(l)
  47. return s.recv(200)
  48. if rpwd:
  49. r = cmd("AUTH", rpwd)
  50. if not r.startswith(b"+OK"):
  51. print(f"[REDIS FAIL] AUTH 失败")
  52. raise SystemExit
  53. r = cmd("PING")
  54. print("[REDIS OK] PING ->", r.decode().strip())
  55. s.close()
  56. except Exception as e:
  57. print(f"[REDIS FAIL] {e}")