redis_probe.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. # -*- coding: utf-8 -*-
  2. """最小 RESP 客户端,用于验证 Redis 连通性与键值(不依赖 redis-py)。"""
  3. import socket
  4. import sys
  5. def cmd(sock, *args):
  6. data = b"*%d\r\n" % len(args)
  7. for a in args:
  8. b = a.encode() if isinstance(a, str) else a
  9. data += b"$%d\r\n%s\r\n" % (len(b), b)
  10. sock.sendall(data)
  11. return read_reply(sock)
  12. def read_reply(sock):
  13. line = readline(sock)
  14. if not line:
  15. return None
  16. t, rest = line[:1], line[1:]
  17. if t == b"+":
  18. return rest.decode()
  19. if t == b"-":
  20. return Exception(rest.decode())
  21. if t == b":":
  22. return int(rest)
  23. if t == b"$":
  24. n = int(rest)
  25. if n == -1:
  26. return None
  27. buf = b""
  28. while len(buf) < n + 2:
  29. buf += sock.recv(n + 2 - len(buf))
  30. return buf[:n].decode()
  31. if t == b"*":
  32. n = int(rest)
  33. if n == -1:
  34. return None
  35. return [read_reply(sock) for _ in range(n)]
  36. return line
  37. def readline(sock):
  38. buf = b""
  39. while not buf.endswith(b"\r\n"):
  40. c = sock.recv(1)
  41. if not c:
  42. return buf
  43. buf += c
  44. return buf[:-2]
  45. def main():
  46. host, port, pwd = "192.168.1.177", 6379, "@@Qinys12346.."
  47. s = socket.create_connection((host, port), timeout=5)
  48. print("AUTH:", cmd(s, "AUTH", pwd))
  49. print("PING:", cmd(s, "PING"))
  50. print("DBSIZE:", cmd(s, "DBSIZE"))
  51. s.close()
  52. if __name__ == "__main__":
  53. main()