DeaD_EyE

get status from wpa_ctl interface

Jul 26th, 2021 (edited)
313
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.30 KB | None | 0 0
  1. """
  2. Source: https://stackoverflow.com/questions/60422924/writing-an-external-program-to-interface-with-wpa-supplicant
  3.  
  4. Commands: https://w1.fi/wpa_supplicant/devel/ctrl_iface_page.html
  5. """
  6.  
  7. import json
  8. import os
  9. import time
  10. from contextlib import contextmanager
  11. from socket import AF_UNIX, SOCK_DGRAM, socket
  12.  
  13.  
  14. @contextmanager
  15. def connect():
  16.     req_sock = socket(AF_UNIX, SOCK_DGRAM)
  17.     rep_sock = socket(AF_UNIX, SOCK_DGRAM)
  18.  
  19.     req_sock_file = "/run/wpa_supplicant/wlan0"
  20.     rep_sock_file = "/run/wpa_supplicant/reply"
  21.  
  22.     if not os.path.exists(req_sock_file):
  23.         raise SystemExit("wpa_supplicant unix socket does not exist.")
  24.  
  25.     req_sock.connect(req_sock_file)
  26.     rep_sock.bind(rep_sock_file)
  27.     rep_sock.settimeout(1)
  28.  
  29.     yield rep_sock, req_sock_file
  30.  
  31.     req_sock.close()
  32.     rep_sock.close()
  33.  
  34.     os.unlink(rep_sock_file)
  35.  
  36.  
  37. def parse(raw_bytes):
  38.     text = raw_bytes.decode()
  39.     result = {}
  40.     for line in text.splitlines():
  41.         key, value = line.strip().split("=", maxsplit=1)
  42.         result[key] = value
  43.  
  44.     return result
  45.  
  46.  
  47. def main():
  48.     with connect() as (sock, file):
  49.         sock.sendto(b"STATUS", file)
  50.  
  51.         data = sock.recv(4096)
  52.         result = parse(data)
  53.         print(json.dumps(result))
  54.  
  55.  
  56. if __name__ == "__main__":
  57.     main()
  58.  
Add Comment
Please, Sign In to add comment