wirelessServer.py 3.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import asyncio
  2. import websockets
  3. import ssl
  4. import os
  5. import signal
  6. import linecache
  7. ssl._create_default_https_context = ssl._create_unverified_context
  8. ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
  9. ssl_context.load_cert_chain("/root/preset/server/ccrb.crt", "/root/preset/server/ccrb.key")
  10. p1 = None
  11. p2 = None
  12. p3 = None
  13. countn = 0
  14. async def send(websocket):
  15. global p2
  16. global p1
  17. global countn
  18. await asyncio.create_subprocess_shell("echo > /root/event.log &")
  19. #open("/root/event.log", 'w').close()
  20. while True:
  21. await asyncio.sleep(0.03)
  22. if True:
  23. try:
  24. proxy_recv_msg = ""
  25. linecache.clearcache()
  26. logarr = linecache.getlines("/root/event.log")[-20:]
  27. open("/root/event.log", 'w').close()
  28. #os.remove(r'/root/event.log')
  29. #await asyncio.create_subprocess_shell("echo '' > /root/event.log")
  30. #print(linecache.getlines("/root/event.log")[-10:])
  31. proxy_recv_msg = "".join(logarr).rstrip('\x00')
  32. #print(len(logarr))
  33. if proxy_recv_msg != "" and proxy_recv_msg != "\n":
  34. try:
  35. await websocket.send(proxy_recv_msg)
  36. except websockets.ConnectionClosed:
  37. try:
  38. if p1.returncode == None:
  39. os.killpg(p1.pid, signal.SIGUSR1)
  40. #open("/root/event.log", 'w').close()
  41. #await asyncio.create_subprocess_shell("echo "" > /root/event.log")
  42. finally:
  43. pass
  44. pass
  45. finally:
  46. pass
  47. async def receive(websocket):
  48. global p2
  49. global p3
  50. global p1
  51. # if p2 == None and p3 == None:
  52. # p2 = await asyncio.create_subprocess_shell("echo '' > /tmp/event.log && tail -f /tmp/event.log", stdout=asyncio.subprocess.PIPE, preexec_fn = os.setsid)
  53. # p3 = p2
  54. # else:
  55. # p2 = p3
  56. while True:
  57. await asyncio.sleep(0.5)
  58. recv_text = await websocket.recv()
  59. if p1 != None:
  60. try:
  61. if p1.returncode == None:
  62. p1.kill()
  63. os.killpg(p1.pid, signal.SIGUSR1)
  64. finally:
  65. pass
  66. p1 = await asyncio.create_subprocess_shell(recv_text, stdout=None, preexec_fn = os.setsid)
  67. print(p1.pid)
  68. async def main_logic(websocket, path):
  69. await runstart(websocket, path)
  70. asyncio.run(runstart(websocket, path))
  71. async def runstart(websocket, path):
  72. a = asyncio.create_task(send(websocket))
  73. b = asyncio.create_task(receive(websocket))
  74. await a
  75. await b
  76. start_server = websockets.serve(main_logic, '0.0.0.0', 5678, ssl=ssl_context)
  77. asyncio.get_event_loop().run_until_complete(start_server)
  78. asyncio.get_event_loop().run_forever()