server.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #!/usr/bin/python
  2. from __future__ import print_function
  3. import datetime
  4. import socket
  5. import random, string
  6. import daemon, getopt, sys
  7. import daemon.pidlockfile
  8. import os
  9. def myrandom(length):
  10. return ''.join(random.choice(string.lowercase) for i in range(length))
  11. def server(port, bindTo):
  12. BUFFER_SIZE = 1024
  13. s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
  14. s.bind((bindTo, port))
  15. s.listen(1)
  16. print('DebugReport server listening on [{0}]:{1}'.format(bindTo, port))
  17. while 1:
  18. conn, addr = s.accept()
  19. report_id = myrandom(10)
  20. filename = 'reports/' + datetime.date.today().strftime('%Y-%m-%d_') + report_id + '.gz'
  21. f = open(filename, 'w')
  22. while 1:
  23. data = conn.recv(BUFFER_SIZE)
  24. if not data: break
  25. f.write(data) # python will convert \n to os.linesep
  26. f.flush()
  27. f.close()
  28. # send reply to reportee
  29. conn.send(report_id)
  30. conn.close()
  31. command = 'echo "'+'new report \\\"{0}\\\" from [{2}]:{3} stored as \\\"{1}\\\""'.format(report_id, filename, addr[0], addr[1])
  32. command = command + ' | /usr/local/bin/ff_log_to_bot'
  33. os.system(command)
  34. print('new report "{0}" from [{2}]:{3} stored as "{1}"'.format(report_id, filename, addr[0], addr[1]))
  35. pass
  36. if __name__ == '__main__':
  37. try:
  38. opts, args = getopt.getopt(sys.argv[1:], "dp:b:", ["do-not-daemonize", "port", "bind-to"])
  39. except:
  40. print ('Unrecognized option')
  41. sys.exit(2)
  42. daemonize = True
  43. port = 1337
  44. bindTo = '::'
  45. for opt, arg in opts:
  46. if opt in ("-d", "--do-not-daemonize"):
  47. daemonize = False
  48. elif opt in ("-p", "--port"):
  49. port = int(arg)
  50. elif opt in ("-b", "--bind-to"):
  51. try:
  52. socket.inet_aton(arg)
  53. bindTo = str(arg)
  54. except:
  55. print('Invalid IPAdress. Using default ::')
  56. else:
  57. assert False
  58. if daemonize == False:
  59. server(port, bindTo)
  60. else:
  61. daemonContext = daemon.DaemonContext(pidfile = daemon.pidlockfile.PIDLockFile("/var/run/ffpb-debugserver.pid"))
  62. with daemonContext:
  63. server(port, bindTo)