What you'll learn
Lesson 01 taught you to validate operational inputs, keep changes reviewable, and preserve uncertainty. Now you'll apply those boundaries to networking. Network evidence can be incomplete even when a Python script runs perfectly: a lookup is not a connection, and a connection is not a healthy application.
- Distinguish inventory enumeration, hostname resolution, IP reachability, TCP transport checks and application health.
- Validate CSV exports, duplicate host identities and IPv4/CIDR scope before processing targets.
- Use ipaddress to verify address families and explicitly approved probe scope.
- Describe socket timeouts, connection refused, DNS failures and why no result is not proof of an outage.
- Recognize that DNS records can be valid while a service is still unavailable, and vice versa.
- Explain SSH host-key verification, command authorization and safe parsing of remote diagnostic output.
- Create a read-only, per-device summary with unknown outcomes preserved and follow-up actions separated from observations.
Prerequisite: Complete Automation Projects & Git Workflows, or be comfortable validating dictionaries, handling errors and creating read-only operational plans. For Python CSV basics, revisit Filesystem & Structured Data Pipelines.
Separate inventory, discovery, and verification
An inventory is a list of devices someone expects to exist. Discovery gathers observations about what responds. Verification compares those observations against an explicit expectation. The three are not interchangeable. A row in a CSV is not evidence that a host is currently online, and a DNS lookup is not evidence that the application is healthy. Treat every tool result as evidence with limited meaning.
Inventory is a claim
CSV exports, CMDB entries and DHCP leases can be outdated. Preserve a source, host identifier, address and site for each proposed target; reject missing and duplicated identities rather than guessing.
Discovery is an observation
A TCP connection, ICMP reply or DNS answer is a snapshot of one protocol and one path. A failed attempt may reflect policy or probe limitations rather than device failure.
Verification needs a definition
Before probing, specify the allowed targets and what success means: a TCP socket accepted, the expected HTTP response returned, or a trusted configuration matched. These are different outcomes.
def observed_state(inventory_row, probe):
if not inventory_row.get('host'):
return 'invalid-inventory'
if probe is None:
return 'unknown'
if probe.get('tcp_connected') is True:
return 'tcp-connected'
return 'not-verified'
print(observed_state({'host':'APP-01'}, None))A device appears in an inventory, its hostname resolves, but port 443 does not connect. Which observations are certain? Reveal the explanation after predicting.
Only that the inventory contains the device and name resolution returned an address. The TCP attempt failed on that path and port. The device may still be powered on, or a firewall may block that connection.
Validate a CSV inventory before using it
Python's csv.DictReader maps header names to row values; it does not automatically validate the schema. Check required columns, unexpected or duplicate headers, malformed rows, duplicate host identifiers and nonempty fields before proposing any network activity. Keep the original export unchanged and build a normalized list. A duplicate with a conflicting address should stop that target from being used.
Check headers explicitly
A typo like ip_adress or a duplicate host column can silently derail an automation. Examine reader.fieldnames and reject unexpected columns or structurally malformed rows.
Normalize with a reason
Trim whitespace and normalize hostnames consistently. Validate an IPv4 address with ipaddress.ip_address instead of counting periods or splitting strings.
Fail safely on ambiguity
When two records share a hostname, don't choose the first or last record. Mark the input invalid until the authoritative inventory is corrected.
import csv
from io import StringIO
from ipaddress import ip_address
csv_text = 'host,ipv4,site\nAPP-01,192.0.2.10,HQ\n'
reader = csv.DictReader(StringIO(csv_text, newline=''))
for row in reader:
address = ip_address(row['ipv4'])
print(row['host'], address, row['site'])What happens if the CSV has the correct headers but a row has an extra comma? Reveal the explanation after predicting.
DictReader can place extra values under a None key. A robust script validates row shape, rejects malformed records, and does not assume valid headers imply valid data.
Limit probes to known, approved scope
An IP address can be syntactically correct but outside the environment you're authorized to investigate. Python's ipaddress.ip_network and ip_address help compare addresses with an approved subnet. Apply scope rules to proposed targets before using socket, ping or SSH. A CIDR prefix is not a permission grant: the responsible organization must authorize the specific hosts, services, methods and expected load.
CIDR is a filter
ip_address('192.0.2.5') in ip_network('192.0.2.0/28') is true; that tells you membership, not whether probing is approved. Use documented inventory ownership and authorization as well.
Avoid the entire Internet
Do not discover arbitrary networks by iterating all addresses or guessing hosts. Begin with a trusted, explicit inventory and select only authorized targets.
Bound operational impact
A safe plan has a small device list, specific ports, short timeouts, a rate limit, and a stop condition. Even read-only probes can cause alerts or operational load.
from ipaddress import ip_address, ip_network
approved = ip_network('192.0.2.0/28')
for raw in ['192.0.2.10','192.0.2.42']:
address = ip_address(raw)
print(raw, 'in-scope' if address in approved else 'out-of-scope')Does being inside an approved subnet always mean that every device and port is authorized for scanning? Reveal the explanation after predicting.
No. Subnet membership is just one check. The approved scope must also identify authorized hosts, protocols, timing and activity. When permissions are unclear, do not probe.
Interpret TCP connectivity and probe failures
A TCP connect tests whether a connection can be established to a particular address and port. Python's socket.create_connection(host_port, timeout=...) provides a simple client for an authorized test. If it succeeds, the transport handshake completed; it does not prove the service returns correct responses. Connection refused, a timeout, and a name-resolution error have different operational meanings. ICMP ping uses a different protocol and may be blocked even when TCP works.
Connected doesn't mean healthy
A web server can accept TCP on 443 while returning HTTP 503. For service health, make an authorized application-level request and validate the expected response separately.
Refused versus timed out
ConnectionRefusedError usually indicates the target or intermediary actively rejected the connection; a timeout means no successful answer arrived within the deadline. Neither alone identifies the root cause.
DNS and address issues are separate
socket.gaierror indicates hostname resolution failed. A direct IP test can help isolate DNS from reachability, but respect the same authorization boundary.
import socket
# Example only: local loopback, never run in the browser workbench.
try:
with socket.create_connection(('127.0.0.1', 8765), timeout=2):
print('tcp-connected')
except ConnectionRefusedError:
print('refused')
except socket.timeout:
print('timeout')
except OSError:
print('connection-error')Your check connects to port 443. Can you automatically close the application incident ticket? Reveal the explanation after predicting.
No. It proves only a TCP connection succeeded. An application-level health check and any expected content or authentication tests must pass before you claim service recovery.
Evaluate DNS answers without overclaiming
DNS translates names into records, which may point to multiple IPv4 or IPv6 addresses. In Python, socket.getaddrinfo() can ask the OS resolver for addresses. Responses may vary by host, resolver, cache and record type. An unexpected answer deserves investigation, but a successful resolution does not prove the host can be reached. Compare normalized answers with a documented approved set and preserve an unknown state when a lookup fails.
A / AAAA are address families
IPv4 A records and IPv6 AAAA records can coexist. Don't silently discard IPv6 or assume there is always exactly one IP address.
Resolve through the configured OS
socket.getaddrinfo uses platform resolver behavior and can reflect caches and system resolver configuration. It does not directly prove which authoritative DNS server produced the answer.
Comparison needs a baseline
An answer that differs from one approved address may be a legitimate failover or a suspicious change. Compare with the complete approved set and flag unexpected answers for review, not automatic rewriting. This Phase 02 example is an allowed-address membership policy: a partial subset can pass. Phase 04's configuration drift comparison uses exact equality against a versioned baseline.
from ipaddress import ip_address
approved = {'192.0.2.20', '192.0.2.21'}
answers = ['192.0.2.21', '192.0.2.20']
observed = {str(ip_address(value)) for value in answers}
print('allowlisted-answers' if observed <= approved else 'review')
# This checks allowed membership, NOT exact DNS baseline equality.If getaddrinfo returns two addresses while your baseline lists one, should the tool immediately overwrite DNS? Reveal the explanation after predicting.
No. Confirm the expected record set, resolver and environment first. Multiple answers can be legitimate. Report the difference and require separately authorized remediation.
Treat SSH as an authenticated, read-only channel
SSH provides an encrypted remote session after server identity and client authentication checks. Tools such as Paramiko can issue commands programmatically, but host-key verification must not be bypassed to make an exercise pass. Use approved credentials, bounded timeouts, a small allowlist of diagnostic commands and predictable parsing. Command output is untrusted text: a line that says 'healthy' is not proof it came from the intended server unless you validated the connection and command context.
Check the server identity
A host key helps verify the SSH server you're connecting to. Reject unexpected host keys and escalate verification rather than auto-accepting unknown hosts.
Separate inputs from commands
Don't concatenate arbitrary hostnames or user strings into shell commands. Use fixed, authorized read-only commands and validated target selection.
Parse complete output
Account for missing lines, duplicate keys, exit status, stderr and target identity. Treat incomplete or contradictory output as unknown, not success.
output = 'device=SW-01\nservice=active\n'
fields = {}
for line in output.splitlines():
key, value = line.split('=', 1)
fields[key] = value
print(fields.get('device'), fields.get('service'))
# Learning-only output; a real parser must validate keys and duplicates.The SSH connection succeeds but the command exits nonzero. Is the requested service healthy? Reveal the explanation after predicting.
Not established. Record the exit status, safe error summary and target; validate the diagnostic command and investigate rather than treating SSH connection success as command success.
Design a bounded, evidence-first health report
A fleet report should show what was attempted and what was observed without pretending that all failures have the same cause. Store an explicit device identifier, method, port or service, result, and an aware UTC timestamp. A probe may be connected, refused, timed out, misconfigured or unknown. Never report an untested device as healthy, never fabricate latency, and keep repeated checks bounded.
Per-target status stays independent
One unavailable device should not abort the entire report. Capture errors for each device and continue when authorized; stop globally for malformed scope or unsafe configuration.
One observation per method
Write 'tcp-connected' instead of 'online', 'dns-resolved' instead of 'healthy' and 'unknown' instead of assuming failure. Keep timestamps per observation.
Keep output useful
Sort hosts deterministically and report counts alongside unresolved items. Logs must avoid credentials, tokens and unnecessary confidential configuration.
from datetime import datetime, timezone
observation = {
'device': 'APP-01',
'method': 'tcp/443',
'result': 'unknown',
'time_utc': datetime.now(timezone.utc).isoformat(),
}
print(observation['device'], observation['result'])One device never responds before the timeout. Should the fleet report show it as 'down'? Reveal the explanation after predicting.
Not on that evidence alone. Record a timeout or unknown response for the specific method and path, with enough context for follow-up. Additional checks are needed to establish a broader outage.
Try a real, authorized localhost connection
This optional exercise runs on your own computer and never contacts external networks. It contrasts a successful TCP handshake with application-level verification. No administrative access or credentials are needed.
python -m http.server 8765 --bind 127.0.0.1- Open Terminal A and start a disposable HTTP server bound only to loopback: python -m http.server 8765 --bind 127.0.0.1. If the port is occupied, choose another free high port in both commands.
- In Terminal B, create a new Python script. Use socket.create_connection(('127.0.0.1', 8765), timeout=2) in a with block and catch ConnectionRefusedError, socket.timeout and OSError separately.
- Observe that 'tcp-connected' only means the port accepted a connection. Make a separate read-only HTTP request to http://127.0.0.1:8765/ with urllib.request.urlopen and inspect its HTTP status. Do not infer the complete application is healthy solely from that response.
- Stop the disposable HTTP server with Ctrl+C. Rerun your TCP check and compare the exception/result to the connected state.
- Record the method, target, UTC timestamp, observed status and what the observation does not prove. Commit the script and a short README to a new local branch, without logs or secrets.
Practice network evidence with real Python
Seven original tasks challenge you to write robust code for CSV inventories, CIDR scoping, TCP outcomes, DNS baselines, SSH output, layered health checks and network handoffs. Each has alternate grading fixtures, including bad data and uncertain outcomes; the browser does not contact devices.
After reading, use the shared Continue Your Learning Path panel below to mark Lesson 02 complete and enter the seven-challenge Practice milestone. The course navigation above records progress across both phases.
Official references and further reading
Read the original API contracts and platform behavior before using these techniques on authorized infrastructure.
