verify_yml.py 2.4 KB

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