server.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. print(command)
  34. os.system(command)
  35. print('new report "{0}" from [{2}]:{3} stored as "{1}"'.format(report_id, filename, addr[0], addr[1]))
  36. pass
  37. if __name__ == '__main__':
  38. try:
  39. opts, args = getopt.getopt(sys.argv[1:], "dp:b:", ["do-not-daemonize", "port", "bind-to"])
  40. except:
  41. print ('Unrecognized option')
  42. sys.exit(2)
  43. daemonize = True
  44. port = 1337
  45. bindTo = '::'
  46. for opt, arg in opts:
  47. if opt in ("-d", "--do-not-daemonize"):
  48. daemonize = False
  49. elif opt in ("-p", "--port"):
  50. port = int(arg)
  51. elif opt in ("-b", "--bind-to"):
  52. try:
  53. socket.inet_aton(arg)
  54. bindTo = str(arg)
  55. except:
  56. print('Invalid IPAdress. Using default ::')
  57. else:
  58. assert False
  59. if daemonize == False:
  60. server(port, bindTo)
  61. else:
  62. daemonContext = daemon.DaemonContext(pidfile = daemon.pidlockfile.PIDLockFile("/var/run/ffpb-debugserver.pid"))
  63. with daemonContext:
  64. server(port, bindTo)