wpaspy.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. pass
  38. if self.started:
  39. self.s.close()
  40. os.unlink(self.local)
  41. self.started = False
  42. def request(self, cmd, timeout=10):
  43. self.s.send(cmd)
  44. [r, w, e] = select.select([self.s], [], [], timeout)
  45. if r:
  46. return self.s.recv(4096)
  47. raise Exception("Timeout on waiting response")
  48. def attach(self):
  49. if self.attached:
  50. return None
  51. res = self.request("ATTACH")
  52. if "OK" in res:
  53. self.attached = True
  54. return None
  55. raise Exception("ATTACH failed")
  56. def detach(self):
  57. if not self.attached:
  58. return None
  59. res = self.request("DETACH")
  60. if "OK" in res:
  61. self.attached = False
  62. return None
  63. raise Exception("DETACH failed")
  64. def pending(self, timeout=0):
  65. [r, w, e] = select.select([self.s], [], [], timeout)
  66. if r:
  67. return True
  68. return False
  69. def recv(self):
  70. res = self.s.recv(4096)
  71. return res