cron-section-replace.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #!/usr/bin/python3
  2. import os
  3. import errno
  4. import re
  5. from commands.CmdExit import CmdExit
  6. from commands.CmdUpdate import CmdUpdate
  7. DIR = os.path.dirname(os.path.realpath(__file__))
  8. CONFIG = {
  9. "PipePath": os.path.join(DIR, "../data/cmd-pipe"),
  10. "CronFragment": os.path.join(DIR, "../data/cron-fragment.txt"),
  11. "Running": True,
  12. }
  13. # try:
  14. # os.mkfifo(PIPE)
  15. # except OSError as oe:
  16. # if oe.errno != errno.EEXIST:
  17. # raise
  18. def execute(command):
  19. if command == "EXIT":
  20. global running
  21. running = False
  22. elif command == "UPDATE":
  23. print("Updating...")
  24. stream = os.popen('crontab -l')
  25. crontab = stream.read()
  26. result = crontab
  27. begin = re.search("\s*#\s*BEGIN\(ALERTS\).*", crontab)
  28. if begin:
  29. result = crontab[:begin.span()[1]] + "\n"
  30. end = re.search("\s*#\s*END\(ALERTS\).*", crontab)
  31. if end:
  32. result += "muahahah\ntest"
  33. result += crontab[end.span()[0]:]
  34. print(result)
  35. else:
  36. print("UNKNOWN COMMAND: {0}".format(command))
  37. def main(config):
  38. # commandPipe = ''
  39. # cronFragment = ''
  40. # try:
  41. # opts, args = getopt.getopt(argv,"h",["help","pipe=","cron="])
  42. # except getopt.GetoptError:
  43. # print 'cron-section-replace --pipe <command-pipe> --cron <cron-fragment>'
  44. # sys.exit(2)
  45. # for opt, arg in opts:
  46. # if opt in ("-h", "--help"):
  47. # print 'cron-section-replace --pipe <command-pipe> --cron <cron-fragment>'
  48. # sys.exit()
  49. # elif opt in ("--pipe"):
  50. # commandPipe = arg
  51. # elif opt in ("--cron):
  52. # cronFragment = arg
  53. # print(commandPipe)
  54. # print(cronFragment)
  55. # sys.exit()
  56. commands = {
  57. "EXIT": CmdExit(config),
  58. "UPDATE": CmdUpdate(config)
  59. }
  60. while config["Running"]:
  61. print("Waiting for connection...")
  62. with open(config["PipePath"]) as pipe:
  63. print("Connection established")
  64. while True:
  65. cmd = pipe.read().strip()
  66. if len(cmd) == 0:
  67. break
  68. if cmd in commands:
  69. commands[cmd].execute()
  70. else:
  71. print("UNKNOWN COMMAND: {0}".format(cmd))
  72. #execute(data.strip())
  73. if __name__ == "__main__":
  74. main(CONFIG)