wpaspy.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #!/usr/bin/python
  2. #
  3. # wpa_supplicant/hostapd control interface using Python
  4. # Copyright (c) 2013, Jouni Malinen <j@w1.fi>
  5. #
  6. # This software may be distributed under the terms of the BSD license.
  7. # See README for more details.
  8. import os
  9. import socket
  10. import select
  11. counter = 0
  12. class Ctrl:
  13. def __init__(self, path):
  14. global counter
  15. self.started = False
  16. self.attached = False
  17. self.s = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
  18. self.dest = path
  19. self.local = "/tmp/wpa_ctrl_" + str(os.getpid()) + '-' + str(counter)
  20. counter += 1
  21. self.s.bind(self.local)
  22. self.s.connect(self.dest)
  23. self.started = True
  24. def __del__(self):
  25. self.close()
  26. def close(self):
  27. if self.attached:
  28. self.detach()
  29. if self.started:
  30. self.s.close()
  31. os.unlink(self.local)
  32. self.started = False
  33. def request(self, cmd):
  34. self.s.send(cmd)
  35. [r, w, e] = select.select([self.s], [], [], 10)
  36. if r:
  37. return self.s.recv(4096)
  38. raise Exception("Timeout on waiting response")
  39. def attach(self):
  40. if self.attached:
  41. return None
  42. res = self.request("ATTACH")
  43. if "OK" in res:
  44. return None
  45. raise Exception("ATTACH failed")
  46. def detach(self):
  47. if not self.attached:
  48. return None
  49. res = self.request("DETACH")
  50. if "OK" in res:
  51. return None
  52. raise Exception("DETACH failed")
  53. def pending(self):
  54. [r, w, e] = select.select([self.s], [], [], 0)
  55. if r:
  56. return True
  57. return False
  58. def recv(self):
  59. res = self.s.recv(4096)
  60. return res