Skip to content

Commit 065d0d8

Browse files
committed
feat(wifi): add wifi scan script
1 parent ce568cc commit 065d0d8

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

Diff for: scripts/wifi_scan.py

+75
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
import subprocess
2+
import re
3+
import os
4+
5+
def scan_wifi():
6+
"""Scans for available Wi-Fi networks and their details using system_profiler."""
7+
try:
8+
output = subprocess.check_output(["system_profiler", "SPAirPortDataType"], universal_newlines=True)
9+
return output
10+
except subprocess.CalledProcessError as e:
11+
print(f"Error scanning Wi-Fi: {e}")
12+
return None
13+
14+
def parse_wifi_scan(scan_output):
15+
"""Parses the output of the Wi-Fi scan to extract network names (SSIDs)."""
16+
if not scan_output:
17+
return []
18+
19+
ssids = []
20+
lines = scan_output.splitlines()
21+
22+
ssids = []
23+
start_parsing = False
24+
for line in lines:
25+
if "Other Local Wi-Fi Networks:" in line:
26+
start_parsing = True
27+
continue
28+
if start_parsing and ":" in line:
29+
ssid = line.split(":")[1].strip()
30+
ssids.append(ssid)
31+
32+
return ssids
33+
34+
def attempt_connect(ssid, password=""):
35+
"""Attempts to connect to a Wi-Fi network with a given SSID and password."""
36+
try:
37+
if password:
38+
command = ["networksetup", "-setairportnetwork", "en0", ssid, password]
39+
else:
40+
command = ["networksetup", "-setairportnetwork", "en0", ssid]
41+
42+
subprocess.check_call(command, timeout=10) # Added timeout
43+
print(f"Successfully connected to {ssid}")
44+
return True
45+
except subprocess.CalledProcessError as e:
46+
print(f"Failed to connect to {ssid}: {e}")
47+
return False
48+
except subprocess.TimeoutExpired:
49+
print(f"Connection to {ssid} timed out.")
50+
return False
51+
52+
if __name__ == "__main__":
53+
print("Scanning for Wi-Fi networks...")
54+
scan_result = scan_wifi()
55+
56+
if scan_result:
57+
ssids = parse_wifi_scan(scan_result)
58+
print("\nAvailable Wi-Fi Networks:")
59+
for ssid in ssids:
60+
print(f"- {ssid}")
61+
62+
print("\nAttempting to connect to available networks (no password)...")
63+
if not ssids:
64+
print("No networks found to connect to.")
65+
66+
else:
67+
for ssid in ssids:
68+
print(f"Attempting to connect to {ssid}...") # Added feedback
69+
if attempt_connect(ssid):
70+
print(f"Connected to {ssid} successfully!")
71+
break # Stop after the first successful connection
72+
else:
73+
print(f"Could not connect to {ssid}.")
74+
else:
75+
print("Wi-Fi scan failed.")

0 commit comments

Comments
 (0)