webrepl_setup.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. import sys
  2. #import uos as os
  3. import os
  4. import machine
  5. RC = "./boot.py"
  6. CONFIG = "./webrepl_cfg.py"
  7. def input_choice(prompt, choices):
  8. while 1:
  9. resp = input(prompt)
  10. if resp in choices:
  11. return resp
  12. def getpass(prompt):
  13. return input(prompt)
  14. def input_pass():
  15. while 1:
  16. passwd1 = getpass("New password (4-9 chars): ")
  17. if len(passwd1) < 4 or len(passwd1) > 9:
  18. print("Invalid password length")
  19. continue
  20. passwd2 = getpass("Confirm password: ")
  21. if passwd1 == passwd2:
  22. return passwd1
  23. print("Passwords do not match")
  24. def exists(fname):
  25. try:
  26. with open(fname):
  27. pass
  28. return True
  29. except OSError:
  30. return False
  31. def get_daemon_status():
  32. with open(RC) as f:
  33. for l in f:
  34. if "webrepl" in l:
  35. if l.startswith("#"):
  36. return False
  37. return True
  38. return None
  39. def change_daemon(action):
  40. LINES = ("import webrepl", "webrepl.start()")
  41. with open(RC) as old_f, open(RC + ".tmp", "w") as new_f:
  42. found = False
  43. for l in old_f:
  44. for patt in LINES:
  45. if patt in l:
  46. found = True
  47. if action and l.startswith("#"):
  48. l = l[1:]
  49. elif not action and not l.startswith("#"):
  50. l = "#" + l
  51. new_f.write(l)
  52. if not found:
  53. new_f.write("import webrepl\nwebrepl.start()\n")
  54. # FatFs rename() is not POSIX compliant, will raise OSError if
  55. # dest file exists.
  56. os.remove(RC)
  57. os.rename(RC + ".tmp", RC)
  58. def main():
  59. status = get_daemon_status()
  60. print("WebREPL daemon auto-start status:", "enabled" if status else "disabled")
  61. print("\nWould you like to (E)nable or (D)isable it running on boot?")
  62. print("(Empty line to quit)")
  63. resp = input("> ").upper()
  64. if resp == "E":
  65. if exists(CONFIG):
  66. resp2 = input_choice("Would you like to change WebREPL password? (y/n) ", ("y", "n", ""))
  67. else:
  68. print("To enable WebREPL, you must set password for it")
  69. resp2 = "y"
  70. if resp2 == "y":
  71. passwd = input_pass()
  72. with open(CONFIG, "w") as f:
  73. f.write("PASS = %r\n" % passwd)
  74. if resp not in ("D", "E") or (resp == "D" and not status) or (resp == "E" and status):
  75. print("No further action required")
  76. sys.exit()
  77. change_daemon(resp == "E")
  78. print("Changes will be activated after reboot")
  79. resp = input_choice("Would you like to reboot now? (y/n) ", ("y", "n", ""))
  80. if resp == "y":
  81. machine.reset()
  82. main()