myutil.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import platform
  2. from subprocess import check_output, Popen
  3. INVALID = "INVALID"
  4. WAKE = "WAKE"
  5. SLEEP = "SLEEP"
  6. OTHERS = "OTHERS"
  7. def parse_magic_packet(packet):
  8. frame = packet[0:6].hex()
  9. macs = set()
  10. for _ in range(0, 16):
  11. packet = packet[6:]
  12. mac = packet[:6].hex()
  13. macs.add(mac)
  14. if frame != "ff"*6 or len(macs) != 1:
  15. return INVALID
  16. mac = list(macs)[0].lower()
  17. macs = get_macs()
  18. if mac in macs:
  19. return WAKE
  20. if mac[::-1] in macs:
  21. return SLEEP
  22. return OTHERS
  23. def get_windows_macs():
  24. import re
  25. out = check_output(["ipconfig", "/all"]).decode("ascii").split("\n")
  26. match_mac = r"\s(?P<mac>[0-9a-f-]{17})\s"
  27. ret = []
  28. for line in out:
  29. matches = re.search(match_mac, line, flags=re.IGNORECASE)
  30. if matches:
  31. ret.append(matches.group("mac").replace("-", "").lower())
  32. return ret
  33. def get_linux_macs():
  34. import netifaces
  35. ret = []
  36. ifaces = netifaces.interfaces()
  37. ifaces.remove('lo')
  38. for i in ifaces:
  39. addresses = netifaces.ifaddresses(i)[netifaces.AF_LINK]
  40. addr = addresses[0]['addr']
  41. ret.append(addr.replace(":", "").lower())
  42. return ret
  43. def get_macs():
  44. if platform.system() == 'Windows':
  45. return get_windows_macs()
  46. else:
  47. return get_linux_macs()
  48. def suspend():
  49. if platform.system() == 'Windows':
  50. Popen(["rundll32.exe", "powrprof.dll,SetSuspendState", "0,1,0"])
  51. else:
  52. Popen(["systemctl", "suspend"])