Python Wi-Fi Diagnostics on Windows: A Read-Only Mini-Project
A Windows laptop says it is connected to Wi-Fi, yet a page will not load. Before changing drivers or resetting the network, inspect what Windows actually reports. This small Python project runs one read-only command and makes its output available in your terminal.
You will build a Wi-Fi interface checker, not a password viewer. It does not request saved keys, reconnect the adapter or change network settings. That narrower purpose makes it a useful first exercise in operating-system automation: run a fixed command, handle failure, then explain what the evidence does and does not prove.
Start safely: the demo runs without querying Wi-Fi. Use live mode only on a computer you own or are allowed to troubleshoot.
First separate a Wi-Fi problem from a Python problem
Open a normal Windows Terminal or PowerShell window. Start with this command, without Python:
netsh wlan show interfacesMicrosoft documents this as a way to display wireless interface information. A machine with a working wireless adapter may return its connection state, network name, signal and other fields. Labels and available details vary with Windows, language, hardware, drivers and permissions.
If Windows says the WLAN service is unavailable or the command is unknown, a Python wrapper cannot repair that. Keep the original message. On a server without the wireless networking components, this project may have no live Wi-Fi information to show.
A connected state describes the radio connection, not the entire route to the internet. It does not prove that DNS works, that a remote service is reachable or that a particular website is healthy. Keep those separate while diagnosing a failed request.
The project has a small, deliberate boundary
- Locate the Windows copy of
netsh.exein the system directory. - Run the fixed arguments
wlan show interfaceswithout a command shell. - Display the returned message and preserve failure as a nonzero program exit.
- Leave the adapter and stored network credentials alone.
There is no network-name input box. That removes the need to insert user input into a command. The program also leaves the report in Windows’ own wording instead of pretending that English field labels are a portable data format.
Create the Python checker
Make an empty project folder and save the following file as wifi_check.py. Do not name it subprocess.py or ctypes.py, because those names would shadow the modules that the example imports.
"""Read local Wi-Fi interface information. Never request saved credentials."""
import argparse
import ctypes
import os
from pathlib import Path
import subprocess
import sys
DEMO = """DEMO DATA, not a scan of this computer
Name : Wi-Fi
State : connected
SSID : ExampleHome
Signal : 78%
"""
def display_text(value):
"""Remove terminal escape/control characters without changing line breaks."""
return "".join(c for c in value if c.isprintable() or c in "\n\t")
def read_interfaces(executable, encoding, runner=subprocess.run):
result = runner(
[str(executable), "wlan", "show", "interfaces"],
shell=False,
capture_output=True,
timeout=10,
check=False,
)
stdout = result.stdout.decode(encoding, errors="replace")
stderr = result.stderr.decode(encoding, errors="replace")
return result.returncode, display_text(stdout), display_text(stderr)
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--demo", action="store_true", help="Use fictional output")
args = parser.parse_args(argv)
if args.demo:
print(DEMO, end="")
return 0
if sys.platform != "win32":
print("Live mode needs Windows. Try --demo.", file=sys.stderr)
return 2
root = os.environ.get("SystemRoot")
if not root or not Path(root).is_absolute():
print("Windows system directory is unavailable.", file=sys.stderr)
return 2
executable = Path(root) / "System32" / "netsh.exe"
if not executable.is_file():
print("The Windows netsh executable was not found.", file=sys.stderr)
return 2
try:
encoding = "cp" + str(ctypes.windll.kernel32.GetOEMCP())
code, output, error = read_interfaces(executable, encoding)
except subprocess.TimeoutExpired:
print("Wi-Fi query timed out. No settings were changed.", file=sys.stderr)
return 3
except (OSError, LookupError) as exc:
print("Wi-Fi query could not run: " + str(exc), file=sys.stderr)
return 3
print("Local Wi-Fi interface report. Review before sharing.")
if output.strip():
print(output.rstrip())
if error.strip():
print(error.rstrip(), file=sys.stderr)
if code:
print("Windows returned an error. Read its message above.", file=sys.stderr)
return 1
if not output.strip() and not error.strip():
print("Windows returned no interface details.")
return 0
if __name__ == "__main__":
raise SystemExit(main())
Why these details are in the example
subprocess.run receives a list of separate arguments and shell=False. It launches the program directly rather than passing a constructed command string to a shell. A fixed command is also easier to inspect in a test.
The ten-second timeout bounds the wait for the child process after it starts; it is not a promise that every operating-system process launch finishes within ten seconds. Python documents that initial process creation can have platform-specific delays.
The command returns bytes. The example asks Windows for its OEM code page, then decodes the text with replacement for invalid byte sequences. This avoids a decoding crash on unusual output, although replacement characters mean that some text could not be recovered exactly. If a network name looks wrong, compare it with the original Windows command rather than trusting a damaged rendering.
display_text removes control characters such as the terminal escape character before printing. It retains line breaks and tabs. This is a display safeguard, not anonymization: a report may still contain identifying network names or addresses.
The executable path comes from the Windows system directory rather than a matching filename in the project folder. This assumes an ordinary trusted Windows environment. It does not make a compromised computer safe, and you should not run downloaded executables with the same name to get around a missing system component.
Run the demo, then query your own computer
Open a terminal in the project folder. Confirm that your interpreter is Python 3.10 or newer, then run the demo:
python --version
python wifi_check.py --demoIf your Windows installation uses the Python launcher instead, use py in place of python. The demo prints this fictional example:
DEMO DATA, not a scan of this computer
Name : Wi-Fi
State : connected
SSID : ExampleHome
Signal : 78%The number is sample data, not a reading from your adapter. Demo mode returns before the Windows query, so it also works on a development machine with no Wi-Fi interface.
For a real local report on Windows, omit the flag:
python wifi_check.pyRead the original Windows message below the report heading. If it describes a disconnected interface, you have evidence about the current connection state. If it reports no wireless interface, first check whether the machine actually has one. Do not turn an absence of output into a claim that the network is secure or healthy.
In PowerShell, check the program’s exit code immediately afterwards:
$LASTEXITCODE- 0: demo completed or the Windows command returned success. This does not prove internet access.
- 1: Windows returned a command error. Read its message.
- 2: live mode cannot start in this environment, or the command-line arguments are invalid.
- 3: execution timed out or the program could not run or decode the query.
Keep the report private until you have reviewed it
The script does not upload the report or save a file. That does not make the output anonymous. Before sharing it, remove network names, hardware identifiers and other details that identify a person, workplace or location. If you paste it into an AI tool for help, share the smallest relevant error message instead of the whole report.
This is not a credential recovery tool, a network scanner or an access-control bypass. On a managed device, follow the administrator’s troubleshooting process. Do not disable security controls or elevate the terminal simply because a tutorial did not anticipate your configuration.
Test the failure paths without disconnecting anything
You do not need to break your Wi-Fi connection to check the error handling. Save this second file beside wifi_check.py. It replaces the command runner with small test doubles; none of these tests query or reconfigure an adapter.
import contextlib
import io
import subprocess
import unittest
from unittest.mock import patch
import wifi_check
class WifiCheckTests(unittest.TestCase):
def test_fixed_read_only_command_and_timeout(self):
def fake(command, **options):
self.assertEqual(command, ["netsh.exe", "wlan", "show", "interfaces"])
self.assertFalse(options["shell"])
self.assertEqual(options["timeout"], 10)
self.assertTrue(options["capture_output"])
return subprocess.CompletedProcess(command, 0, b"State : connected\r\n", b"")
code, output, error = wifi_check.read_interfaces("netsh.exe", "utf-8", fake)
self.assertEqual((code, output, error), (0, "State : connected\n", ""))
def test_nonzero_exit_and_stderr_are_preserved(self):
fake = lambda *a, **k: subprocess.CompletedProcess(a[0], 5, b"", b"Access denied")
self.assertEqual(wifi_check.read_interfaces("netsh.exe", "utf-8", fake),
(5, "", "Access denied"))
def test_localized_text_is_not_parsed_as_english(self):
text = "Estado : conectado\nSe\u00f1al : 78%\n"
fake = lambda *a, **k: subprocess.CompletedProcess(a[0], 0, text.encode("cp850"), b"")
self.assertEqual(wifi_check.read_interfaces("netsh.exe", "cp850", fake)[1], text)
def test_invalid_bytes_do_not_crash(self):
fake = lambda *a, **k: subprocess.CompletedProcess(a[0], 0, b"SSID : \xff", b"")
self.assertIn("\ufffd", wifi_check.read_interfaces("netsh.exe", "utf-8", fake)[1])
def test_timeout_propagates_to_main(self):
def fake(*a, **k):
raise subprocess.TimeoutExpired(a[0], 10)
with self.assertRaises(subprocess.TimeoutExpired):
wifi_check.read_interfaces("netsh.exe", "utf-8", fake)
def test_control_characters_removed(self):
self.assertEqual(wifi_check.display_text("ok\x1b\x00\r\nnext\tline"), "ok\nnext\tline")
def test_demo_never_queries_windows(self):
stream = io.StringIO()
with patch.object(wifi_check, "read_interfaces", side_effect=AssertionError("Live query")):
with contextlib.redirect_stdout(stream):
self.assertEqual(wifi_check.main(["--demo"]), 0)
self.assertIn("DEMO DATA", stream.getvalue())
def test_non_windows_returns_actionable_error(self):
stream = io.StringIO()
with patch.object(wifi_check.sys, "platform", "linux"):
with contextlib.redirect_stderr(stream):
self.assertEqual(wifi_check.main([]), 2)
self.assertIn("--demo", stream.getvalue())
if __name__ == "__main__":
unittest.main()
Run the test file from that folder:
python -m unittest -v test_wifi_check.pyThe suite contains eight test methods. They check fixed command arguments, timeout propagation, error output, localized text, invalid bytes, control-character handling, the demo boundary and the non-Windows guard. These are software checks, not a claim of compatibility with every adapter or Windows build.
Verification for this article, 26 October 2026: all eight tests and the demo were run successfully on the development host. A real read-only invocation was also attempted. That host returned “The following command was not found: wlan show interfaces.” The script reported the failure and exited with code 1. A successful live wireless-adapter report was not tested on that host.
For a broader testing method, follow the practical regression workflow for AI-generated code. It shows why a plausible-looking fix still needs checks that would reject a wrong alternative.
Troubleshoot the message you actually received
“Python is not recognized”
The interpreter did not start. Check your Python installation or try py --version on Windows. Keep that separate from the Wi-Fi command: there is no reason to edit a network setting to fix a missing interpreter.
The Windows command is missing or reports a service problem
Run netsh wlan show interfaces directly once and compare the message. A server image, missing wireless components, driver state or organization policy can explain why the command is unavailable. Use Windows Settings or ask the administrator to inspect the supported configuration. The tutorial deliberately does not install features or start services.
The name contains replacement characters
Byte decoding lost information. Check the original command in your Windows terminal and avoid adding a parser based on the corrupted string. The test with Spanish text exercises a decoding path; it does not certify every Windows locale.
The report says connected, but a website still fails
Write down the narrower observation: Windows reports an association with a wireless network. Next distinguish an application failure from a DNS or wider connectivity problem using your normal support process. Repeatedly running this same query will not tell you whether a remote service is down.
Share the outcome without copying the interface report
A support request rarely needs your network name to establish that a command failed. The original checker is useful locally, but its normal output can include identifying details. Instead of trying to recognise and redact every language’s field labels, keep that output out of the shared summary altogether.
Save this additional file as wifi_summary.py beside the reviewed wifi_check.py. It runs that checker with its normal input, output and error streams redirected to subprocess.DEVNULL, then creates a small JSON object from a fixed set of fields. It does not edit the original checker, parse an SSID or write a report file.
This is a sharing wrapper, not a sandbox: run only the reviewed exercise on a computer you may troubleshoot. Discarding standard streams does not prevent an altered child program from accessing files or the network. The checker still handles its raw Windows output in memory. The wrapper deliberately passes only SystemRoot in the child environment rather than inheriting unrelated application secrets.
"""Report the reviewed Wi-Fi checker's outcome without printing its raw report."""
import argparse
import json
import os
from pathlib import Path
import subprocess
import sys
def report(mode, outcome, checker_exit=None):
return {
"mode": mode,
"outcome": outcome,
"checker_exit": checker_exit,
"internet_reachability": "not_tested",
}
def run_report(script, mode, runner=subprocess.run):
if mode not in {"demo", "live"}:
raise ValueError("mode must be demo or live")
command = [sys.executable, "-B", str(script)]
if mode == "demo":
command.append("--demo")
environment = {}
if os.environ.get("SystemRoot"):
environment["SystemRoot"] = os.environ["SystemRoot"]
try:
result = runner(
command,
cwd=Path(script).parent,
env=environment,
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
shell=False,
check=False,
timeout=15,
)
except subprocess.TimeoutExpired:
return report(mode, "wrapper_timeout"), 3
except OSError:
return report(mode, "wrapper_could_not_run"), 3
outcomes = {0: "checker_succeeded", 1: "checker_command_error",
2: "checker_cannot_start", 3: "checker_execution_error"}
code = result.returncode
if code not in outcomes:
return report(mode, "unexpected_checker_exit"), 3
return report(mode, outcomes[code], code), code
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
choice = parser.add_mutually_exclusive_group(required=True)
choice.add_argument("--demo", action="store_true")
choice.add_argument("--live", action="store_true")
args = parser.parse_args(argv)
mode = "demo" if args.demo else "live"
script = Path(__file__).resolve().with_name("wifi_check.py")
if not script.is_file():
payload, code = report(mode, "checker_missing"), 2
else:
payload, code = run_report(script, mode)
print(json.dumps(payload, sort_keys=True))
return code
if __name__ == "__main__":
raise SystemExit(main())Try a fictional result before live mode
The mode must be explicit, so accidentally running the wrapper without arguments cannot start a wireless query. Start with:
python wifi_summary.py --demoWith the original checker beside it, the demo returns this JSON and exit code 0:
{"checker_exit": 0, "internet_reachability": "not_tested", "mode": "demo", "outcome": "checker_succeeded"}The original demo’s fictional network name is not included. Notice mode: demo: the output cannot be used as evidence about this computer’s actual adapter. For a permitted live check on Windows, use python wifi_summary.py --live, then inspect $LASTEXITCODE in PowerShell.
checker_succeeded means the checker returned 0. It does not establish that an adapter exists, that Windows reported a connected state or that the internet works. The checker can return success with no interface details. That is why every summary says internet_reachability: not_tested.
The wrapper preserves the checker’s documented exits 0 through 3. A missing sibling file returns checker_missing with wrapper exit 2. A wrapper timeout, process-start failure or unexpected child exit returns 3, with checker_exit: null because no recognised checker result is available. Its fifteen-second budget is separate from the checker’s ten-second command budget; process startup can add delay.
Test the summary boundary
Save the next file as test_wifi_summary.py. These tests use fake runners for the supported success and failure paths. They do not query an adapter, disconnect a network or change Windows settings.
import contextlib
import io
import json
from pathlib import Path
import subprocess
import sys
import unittest
from unittest.mock import patch
import wifi_summary
class WifiSummaryTests(unittest.TestCase):
def test_demo_fixed_command_discards_both_streams(self):
def fake(command, **options):
self.assertEqual(command, [sys.executable, "-B", "wifi_check.py", "--demo"])
for stream in ("stdin", "stdout", "stderr"):
self.assertEqual(options[stream], subprocess.DEVNULL)
self.assertFalse(options["shell"])
self.assertEqual(options["timeout"], 15)
self.assertNotIn("UNRELATED_TEST_SECRET", options["env"])
return subprocess.CompletedProcess(command, 0)
with patch.dict("os.environ", {"UNRELATED_TEST_SECRET": "fictional"}):
payload, code = wifi_summary.run_report("wifi_check.py", "demo", fake)
self.assertEqual(code, 0)
self.assertEqual(payload["outcome"], "checker_succeeded")
self.assertEqual(payload["internet_reachability"], "not_tested")
def test_live_does_not_append_demo_or_arbitrary_arguments(self):
def fake(command, **options):
self.assertEqual(command, [sys.executable, "-B", "wifi_check.py"])
return subprocess.CompletedProcess(command, 0)
self.assertEqual(wifi_summary.run_report("wifi_check.py", "live", fake)[1], 0)
def test_known_checker_exit_codes_are_preserved(self):
for value in (0, 1, 2, 3):
with self.subTest(value=value):
fake = lambda *a, **k: subprocess.CompletedProcess(a[0], value)
payload, code = wifi_summary.run_report("wifi_check.py", "demo", fake)
self.assertEqual((payload["checker_exit"], code), (value, value))
def test_unexpected_exit_is_not_reported_as_success(self):
fake = lambda *a, **k: subprocess.CompletedProcess(a[0], 91)
payload, code = wifi_summary.run_report("wifi_check.py", "demo", fake)
self.assertEqual((payload["outcome"], payload["checker_exit"], code),
("unexpected_checker_exit", None, 3))
def test_timeout_does_not_echo_command_or_output(self):
def fake(*a, **k):
raise subprocess.TimeoutExpired("fictional-private-path", 15,
output=b"SSID: FictionalOffice")
payload, code = wifi_summary.run_report("wifi_check.py", "demo", fake)
self.assertEqual((payload["outcome"], code), ("wrapper_timeout", 3))
self.assertNotIn("Fictional", json.dumps(payload))
def test_os_error_details_are_not_serialized(self):
def fake(*a, **k):
raise OSError("fictional-private-path")
payload, code = wifi_summary.run_report("wifi_check.py", "demo", fake)
self.assertEqual((payload["outcome"], code), ("wrapper_could_not_run", 3))
self.assertNotIn("fictional-private-path", json.dumps(payload))
def test_runner_output_cannot_expand_the_report_fields(self):
fake = lambda *a, **k: subprocess.CompletedProcess(
a[0], 1, "SSID: FictionalOffice", "Machine: FictionalLaptop")
payload, code = wifi_summary.run_report("wifi_check.py", "demo", fake)
self.assertEqual(set(payload), {"mode", "outcome", "checker_exit",
"internet_reachability"})
self.assertNotIn("Fictional", json.dumps(payload))
self.assertEqual(code, 1)
def test_missing_checker_does_not_start_a_process(self):
stream = io.StringIO()
with patch.object(Path, "is_file", return_value=False):
with patch.object(wifi_summary, "run_report", side_effect=AssertionError("Unexpected run")):
with contextlib.redirect_stdout(stream):
self.assertEqual(wifi_summary.main(["--demo"]), 2)
self.assertEqual(json.loads(stream.getvalue())["outcome"], "checker_missing")
def test_explicit_mode_is_required(self):
with contextlib.redirect_stderr(io.StringIO()):
with self.assertRaises(SystemExit) as error:
wifi_summary.main([])
self.assertEqual(error.exception.code, 2)
def test_unknown_mode_is_rejected_before_a_child_runs(self):
with self.assertRaises(ValueError):
wifi_summary.run_report("wifi_check.py", "invented-mode")
if __name__ == "__main__":
unittest.main()
python -m unittest discover -s . -p "test_*.py" -vWhen the folder contains the original eight-method test suite and this new ten-method suite, discovery should report 18 methods. The stream assertions are important: suppressing standard output alone would still leave an error message free to expose a path or identifier through standard error. The tests also check that exception details cannot become extra JSON fields.
Verification, 7 November 2026: all eighteen methods passed on Python 3.13.6, and the actual wrapper ran the original demo successfully. Separate disposable child fixtures printed fictional network and machine names to both streams, then exited with 0 or 1. Both wrapper results contained only the allowed JSON fields and no fixture identifiers. Those were constructed local tests, not a successful live-adapter test or an AI-model benchmark.
Keep the support question as narrow as the evidence
If live mode returns checker_command_error, you can share the fixed summary with a question such as: “The read-only checker returned exit 1. What does that establish, and which local message should I inspect next?” Do not turn the absence of raw details into a guess that a driver is broken. Use the original checker locally when you need the Windows error message; review that message separately before sharing any of it.
For this exercise, loss of detail is a deliberate trade-off. The wrapper does not tell a support person the SSID, signal level or exact Windows error. It is also not a general log anonymiser: Python startup errors, invalid command-line arguments and unexpected tracebacks fall outside its handled JSON paths. Review the output you actually received, and do not paste a terminal screenshot containing an earlier raw report.
The Python subprocess reference documents stream redirection, environment replacement and timeout behaviour. The unittest discovery guide explains how the command above selects both test files. The underlying Windows command remains the read-only show interfaces operation documented in Microsoft’s netsh wlan reference.
Extend the project without turning it into a secret collector
The separate sharing wrapper above is one implementation of a minimal result summary. For your own extension, add a test for a missing system executable before changing its behaviour. Keep the fixed command and avoid exposing arbitrary command arguments through a web form.
For a portfolio, include the source, tests and a short README describing the boundary: it inspects one local interface report and does not diagnose the entire network. Use demo output in a public screenshot. A precise limitation is more credible than promising that a small script can fix every connection problem.
Need the foundations first? Continue through the Python programming learning path. If your actual task is an Android device rather than a Windows adapter, use the separate wireless ADB guide; it serves a different purpose.
Official references and review notes
This is an original implementation and explanation. The sources below document the operating-system command and Python behaviour used in the project:
- Microsoft Learn: netsh wlan, including the show interfaces command.
- Python documentation: subprocess, including argument lists, captured output and timeouts.
- Microsoft Learn: GetOEMCP, the Windows OEM code-page function.
Reviewed on 26 October 2026. Recheck command availability and output handling when you change the operating system or interpreter. Choose another practical guide.






