wpaspy.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. try:
  29. self.detach()
  30. except Exception, e:
  31. # Need to ignore this allow the socket to be closed
  32. pass
  33. if self.started:
  34. self.s.close()
  35. os.unlink(self.local)
  36. self.started = False
  37. def request(self, cmd):
  38. self.s.send(cmd)
  39. [r, w, e] = select.select([self.s], [], [], 10)
  40. if r:
  41. return self.s.recv(4096)
  42. raise Exception("Timeout on waiting response")
  43. def attach(self):
  44. if self.attached:
  45. return None
  46. res = self.request("ATTACH")
  47. if "OK" in res:
  48. self.attached = True
  49. return None
  50. raise Exception("ATTACH failed")
  51. def detach(self):
  52. if not self.attached:
  53. return None
  54. res = self.request("DETACH")
  55. if "OK" in res:
  56. self.attached = False
  57. return None
  58. raise Exception("DETACH failed")
  59. def pending(self):
  60. [r, w, e] = select.select([self.s], [], [], 0)
  61. if r:
  62. return True
  63. return False
  64. def recv(self):
  65. res = self.s.recv(4096)
  66. return res