wpaspy.py 2.2 KB

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