| 12345678910111213141516171819202122232425262728293031323334353637383940414243 |
- #!/usr/bin/env python3
- """云服务器上的TCP转发守护(替代socat): 25432 -> db.fmode.cn:5432"""
- import socket, threading, subprocess, sys
- def pipe(a, b):
- try:
- while True:
- d = a.recv(65536)
- if not d:
- break
- b.sendall(d)
- except Exception:
- pass
- finally:
- try:
- a.close()
- except Exception:
- pass
- try:
- b.close()
- except Exception:
- pass
- def handle(client):
- try:
- upstream = socket.create_connection(("db.fmode.cn", 5432), timeout=10)
- except Exception:
- client.close()
- return
- threading.Thread(target=pipe, args=(client, upstream), daemon=True).start()
- threading.Thread(target=pipe, args=(upstream, client), daemon=True).start()
- def serve():
- srv = socket.socket()
- srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
- srv.bind(("127.0.0.1", 25432))
- srv.listen(16)
- print("forwarder up", flush=True)
- while True:
- c, _ = srv.accept()
- threading.Thread(target=handle, args=(c,), daemon=True).start()
- serve()
|