-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdev.py
More file actions
398 lines (331 loc) · 15.4 KB
/
dev.py
File metadata and controls
398 lines (331 loc) · 15.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
#!/usr/bin/env python3
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
import subprocess, re, time, csv, webbrowser
from typing import List, Tuple, Optional
from dataclasses import dataclass
APP_VERSION = "v0.3.0"
SCAN_INTERVAL_MS = 6000
TIMESTAMP_UPDATE_MS = 1000
GITHUB_URL = "https://github.com/GoobyFRS/Goobs-WiFi-Scanner"
ISSUES_URL = "https://github.com/GoobyFRS/Goobs-WiFi-Scanner/issues"
WIKI_URL = "https://github.com/GoobyFRS/Goobs-WiFi-Scanner/wiki"
@dataclass
class WiFiNetwork: # Helper to define data classes.
ssid: str
mac_address: str
signal_strength: str
channel: str
def to_tuple(self) -> Tuple[str, str, str, str]: # Convert to tuple for treeview insertion
return (self.ssid, self.mac_address, self.signal_strength, self.channel)
@property # Extract signal percentage for sorting
def signal_percentage(self) -> int:
try:
return int(self.signal_strength.strip('%'))
except (ValueError, AttributeError):
return -1
class WiFiScanner:
""" Powershell command example output
SSID 2 : THE_NEIGHBORS_WIFI
Network type : Infrastructure
Authentication : WPA2-Personal
Encryption : CCMP
BSSID 1 : a0:b1:c2:d3:e4:cb
Signal : 24%
Radio type : 802.11ax
Channel : 44
Basic rates (Mbps) : 6 12 24
Other rates (Mbps) : 9 18 36 48 54
BSSID 2 : a0:b1:c2:d3:e4:ca
Signal : 38%
Radio type : 802.11ac
Channel : 1
Basic rates (Mbps) : 1 2 5.5 11
Other rates (Mbps) : 6 9 12 18 24 36 48 54
BSSID 3 : a0:b1:c2:d3:e4:3b
"""
@staticmethod
def scan() -> List[WiFiNetwork]: # Returns a List of networks.
try:
ps_command = "netsh wlan show networks mode=bssid"
ps_command_result = subprocess.run( ps_command, capture_output=True, text=True, shell=True, timeout=10, creationflags=subprocess.CREATE_NO_WINDOW if hasattr(subprocess, 'CREATE_NO_WINDOW') else 0)
if ps_command_result.returncode != 0:
# Show actual error output for debugging
error_msg = f"Application Failure with Return Code {ps_command_result.returncode}\n"
if ps_command_result.stderr:
error_msg += f"Error: {ps_command_result.stderr}\n"
if ps_command_result.stdout:
error_msg += f"Output: {ps_command_result.stdout[:200]}"
raise RuntimeError(error_msg)
return WiFiScanner._parse_output(ps_command_result.stdout)
except subprocess.TimeoutExpired:
messagebox.showerror("Driver Error", "Scanning for wireless networks took too long.")
return []
except FileNotFoundError:
messagebox.showerror("Windows Error", "Could not find netsh command. This tool requires Windows.")
return []
except Exception as e:
messagebox.showerror("Application Error", f"Failed to scan WiFi networks:\n{str(e)}")
return []
@staticmethod
def _parse_output(output: str) -> List[WiFiNetwork]: # Parse netsh command output into WiFiNetwork objects
networks = []
current_ssid = None
current_bssid = None
current_signal = "N/A"
current_channel = "N/A"
for line in output.split("\n"):
line = line.strip()
# Match SSID
ssid_match = re.match(r"SSID \d+ : (.+)", line)
if ssid_match:
current_ssid = ssid_match.group(1).strip() or "Hidden SSID"
continue
# Match BSSID (MAC address)
mac_match = re.match(r"BSSID \d+ *: ([0-9A-Fa-f:-]+)", line)
if mac_match and current_ssid:
# Save previous BSSID if exists
if current_bssid:
networks.append(WiFiNetwork(
ssid=current_ssid,
mac_address=current_bssid,
signal_strength=current_signal,
channel=current_channel
))
current_bssid = mac_match.group(1)
current_signal = "N/A"
current_channel = "N/A"
continue
# Match signal strength
signal_match = re.match(r"Signal\s*:\s*(\d+)%", line)
if signal_match and current_bssid:
current_signal = f"{signal_match.group(1)}%"
continue
# Match channel
channel_match = re.match(r"Channel\s*:\s*(\d+)", line)
if channel_match and current_bssid:
current_channel = channel_match.group(1)
continue
# Don't forget the last network
if current_bssid and current_ssid:
networks.append(WiFiNetwork(
ssid=current_ssid,
mac_address=current_bssid,
signal_strength=current_signal,
channel=current_channel))
return networks
class PlaceholderEntry(tk.Entry): # Entry widget with placeholder text support
def __init__(self, parent, placeholder: str = "", **kwargs):
super().__init__(parent, **kwargs)
self.placeholder = placeholder
self.placeholder_color = "gray"
self.default_color = self["fg"]
self._showing_placeholder = False
self._show_placeholder()
self.bind("<FocusIn>", self._on_focus_in)
self.bind("<FocusOut>", self._on_focus_out)
def _show_placeholder(self): # Display placeholder text
if not self.get():
self.insert(0, self.placeholder)
self.config(fg=self.placeholder_color)
self._showing_placeholder = True
def _on_focus_in(self, event): # Remove placeholder on focus
if self._showing_placeholder:
self.delete(0, tk.END)
self.config(fg=self.default_color)
self._showing_placeholder = False
def _on_focus_out(self, event): # Restore placeholder if empty
if not self.get():
self._show_placeholder()
def get_value(self) -> str:
"""Get actual value (empty string if showing placeholder)"""
return "" if self._showing_placeholder else self.get()
class WiFiScannerApp: # Main application class
def __init__(self, root: tk.Tk):
self.root = root
self.root.title(f"Goobs WiFi Scanner {APP_VERSION}")
self.root.geometry("800x500")
# Initialize variables
self.scan_job_id: Optional[str] = None
self.timestamp_job_id: Optional[str] = None
# Build UI
self._create_menu_bar()
self._create_main_table()
self._setup_signal_tags()
self._create_reference_fields()
self._create_control_buttons()
self._create_status_bar()
# Start operations
self.scan_wifi()
self._update_timestamp()
def _create_menu_bar(self): # Create application menu bar
menu_bar = tk.Menu(self.root)
# File menu
file_menu = tk.Menu(menu_bar, tearoff=0)
file_menu.add_command(label="Export CSV", command=self.export_csv)
file_menu.add_command(label="Check for Updates", command=self.check_updates)
file_menu.add_command(label="About", command=self.show_about)
file_menu.add_separator()
file_menu.add_command(label="Exit", command=self.exit_app)
menu_bar.add_cascade(label="File", menu=file_menu)
# Help menu
help_menu = tk.Menu(menu_bar, tearoff=0)
help_menu.add_command(label="Report Issue", command=self.github_report_issue)
help_menu.add_command(label="Go to Wiki", command=self.goto_wiki)
menu_bar.add_cascade(label="Help", menu=help_menu)
self.root.config(menu=menu_bar)
def _create_main_table(self): # Create the main network list table
# Frame for table and scrollbar
tree_frame = tk.Frame(self.root)
tree_frame.pack(expand=True, fill="both", padx=10, pady=(10, 0))
# Scrollbar
tree_scroll = ttk.Scrollbar(tree_frame, orient="vertical")
tree_scroll.pack(side="right", fill="y")
# Treeview
columns = ("SSID", "MAC Address", "Signal Strength", "Channel")
self.tree = ttk.Treeview(
tree_frame,
columns=columns,
show="headings",
yscrollcommand=tree_scroll.set)
tree_scroll.config(command=self.tree.yview)
# Configure columns
column_widths = {"SSID": 200, "MAC Address": 150, "Signal Strength": 120, "Channel": 80}
for col in columns:
self.tree.heading(col, text=col)
self.tree.column(col, width=column_widths.get(col, 100))
self.tree.pack(expand=True, fill="both")
def _setup_signal_tags(self): # Configure Treeview tags for signal highlighting
# Background colors chosen for readability
# Strong: Green, Good: Light Green, Fair: Yellow, Weak: Light Red
try:
self.tree.tag_configure("sig-strong", background="#2ecc71") # green
self.tree.tag_configure("sig-good", background="#a9dfbf") # light green
self.tree.tag_configure("sig-fair", background="#f9e79f") # yellow
self.tree.tag_configure("sig-weak", background="#f5b7b1") # light red
except Exception:
# Fail silently if theme/platform ignores tag backgrounds
pass
@staticmethod
def _signal_tag_for_percentage(pct: int) -> Optional[str]:
if pct >= 80:
return "sig-strong"
if 65 <= pct < 80:
return "sig-good"
if 50 <= pct < 65:
return "sig-fair"
if pct <= 49:
return "sig-weak"
return None
def _create_reference_fields(self): # Create reference data entry fields
entry_frame = tk.Frame(self.root)
entry_frame.pack(fill="x", padx=10, pady=10)
# Incident Reference
tk.Label(entry_frame, text="Customer:").grid(row=0, column=0, padx=(0, 5), sticky="w")
self.customer_entry = PlaceholderEntry(entry_frame, placeholder="Example", width=20)
self.customer_entry.grid(row=0, column=1, padx=(0, 20))
# Incident Reference
tk.Label(entry_frame, text="Reference:").grid(row=0, column=2, padx=(0, 5), sticky="w")
self.reference_entry = PlaceholderEntry(entry_frame, placeholder="INC000012345", width=20)
self.reference_entry.grid(row=0, column=3, padx=(0, 20))
# Department
tk.Label(entry_frame, text="Department:").grid(row=0, column=4, padx=(0, 5), sticky="w")
self.department_entry = PlaceholderEntry(entry_frame, placeholder="Men's Shoes", width=20)
self.department_entry.grid(row=0, column=5)
def _create_control_buttons(self): # Create control buttons
button_frame = tk.Frame(self.root)
button_frame.pack(fill="x", padx=10, pady=(0, 10))
self.scan_button = tk.Button(button_frame,
text="Scan WiFi",
command=self.scan_wifi,
width=15)
self.scan_button.pack()
def _create_status_bar(self): # Create status bar with timestamp
self.timestamp_label = tk.Label(self.root,
text="Ready",
anchor="w",
padx=10,
relief=tk.SUNKEN)
self.timestamp_label.pack(side="bottom", fill="x")
def scan_wifi(self): # Perform a wireless scan and update the display
# Cancel existing scheduled scan
if self.scan_job_id:
self.root.after_cancel(self.scan_job_id)
# Perform scan
networks = WiFiScanner.scan()
# Sort by signal strength (strongest first)
networks.sort(key=lambda n: n.signal_percentage, reverse=True)
# Update tree
self.tree.delete(*self.tree.get_children())
for network in networks:
tag = self._signal_tag_for_percentage(network.signal_percentage)
if tag:
self.tree.insert("", tk.END, values=network.to_tuple(), tags=(tag,))
else:
self.tree.insert("", tk.END, values=network.to_tuple())
# Schedule next scan
self.scan_job_id = self.root.after(SCAN_INTERVAL_MS, self.scan_wifi)
def _update_timestamp(self): # Update timestamp display
current_time = time.strftime("%H:%M:%S")
self.timestamp_label.config(text=f"Last Updated: {current_time}")
self.timestamp_job_id = self.root.after(TIMESTAMP_UPDATE_MS, self._update_timestamp)
def export_csv(self): # Export current scan results to CSV
timestamp = time.strftime("%Y%m%d_%H%M%S")
default_name = f"wireless_scan_{timestamp}.csv" # Generate default filename
# Get save location
filepath = filedialog.asksaveasfilename(
defaultextension=".csv",
initialfile=default_name, filetypes=[("CSV files", "*.csv"), ("All files", "*.*")])
if not filepath:
return
try:
# Collect data from treeview
rows = []
for iid in self.tree.get_children():
rows.append(self.tree.item(iid, "values"))
# Write CSV
with open(filepath, "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
# Write headers
writer.writerow(["SSID", "MAC Address", "Signal Strength", "Channel"])
# Write reference data if provided
ref = self.reference_entry.get_value()
dept = self.department_entry.get_value()
store = self.customer_entry.get_value()
if ref or dept or store:
writer.writerow([])
writer.writerow(["Reference:", ref])
writer.writerow(["Department:", dept])
writer.writerow(["Store:", store])
writer.writerow([])
# Write network data
for row in rows:
writer.writerow(row)
messagebox.showinfo("Export Successful", f"Data exported to:\n{filepath}")
except Exception as e:
messagebox.showerror("Export Error", f"Failed to export CSV:\n{str(e)}")
def check_updates(self): # Open GitHub Repo for updates.
webbrowser.open(GITHUB_URL)
def github_report_issue(self): # Launch GitHub Issues Page
webbrowser.open(ISSUES_URL)
def goto_wiki(self): # Launch GitHub Wiki Page
webbrowser.open(WIKI_URL)
def show_about(self): # About dialog
about_text = f"""Goobs WiFi Scanner {APP_VERSION}
Lightweight Windows-centric 802.11 (DOT11) Wireless Scanner.
Works best when disconnected from any WiFi network.
"""
messagebox.showinfo("About", about_text)
def exit_app(self): # Clean Exit
if self.scan_job_id: # Cancel scheduled jobs
self.root.after_cancel(self.scan_job_id)
if self.timestamp_job_id:
self.root.after_cancel(self.timestamp_job_id)
self.root.quit()
def main():
"""Application entry point"""
root = tk.Tk()
app = WiFiScannerApp(root)
root.mainloop()
if __name__ == "__main__":
main()