pg_forward.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. #!/usr/bin/env python3
  2. """云服务器上的TCP转发守护(替代socat): 25432 -> db.fmode.cn:5432"""
  3. import socket, threading, subprocess, sys
  4. def pipe(a, b):
  5. try:
  6. while True:
  7. d = a.recv(65536)
  8. if not d:
  9. break
  10. b.sendall(d)
  11. except Exception:
  12. pass
  13. finally:
  14. try:
  15. a.close()
  16. except Exception:
  17. pass
  18. try:
  19. b.close()
  20. except Exception:
  21. pass
  22. def handle(client):
  23. try:
  24. upstream = socket.create_connection(("db.fmode.cn", 5432), timeout=10)
  25. except Exception:
  26. client.close()
  27. return
  28. threading.Thread(target=pipe, args=(client, upstream), daemon=True).start()
  29. threading.Thread(target=pipe, args=(upstream, client), daemon=True).start()
  30. def serve():
  31. srv = socket.socket()
  32. srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  33. srv.bind(("127.0.0.1", 25432))
  34. srv.listen(16)
  35. print("forwarder up", flush=True)
  36. while True:
  37. c, _ = srv.accept()
  38. threading.Thread(target=handle, args=(c,), daemon=True).start()
  39. serve()