Objective. Students write Python scripts that use the socket and requests libraries to probe network services and retrieve HTTP-based threat-intelligence data within an isolated lab network.
This lesson, its worked examples and its practice questions has not yet been verified by an industry-certified professional or by a certification or approval body. It is a study draft and may contain errors. Do not use it as instructions for work on a job site or on live equipment. Always follow your instructor, your supervising professional, and current official references and regulations.
VoTechWorks program approval and accreditation are still in progress. Credentials are issued only by the certifying bodies named in each program, after their own exams.
Python is the dominant scripting language in cybersecurity because it is readable, cross-platform, and ships with powerful standard-library modules for networking. Security analysts use Python daily to automate reconnaissance, parse threat-intelligence feeds, and prototype detection tools. The two libraries you will use most in this lesson are socket (built into Python's standard library) and requests (a third-party HTTP library installable via pip). CompTIA CySA+ expects analysts to understand threat-intelligence workflows and automated data collection — skills you build directly in this lesson.
---
Before writing a single line of code, understand the legal and ethical boundary: scanning or probing any host without explicit written permission is unauthorized access under the Computer Fraud and Abuse Act (CFAA) and equivalent state laws. Every exercise in this lesson runs only against the designated lab target VM on your isolated lab network. Never point a scanner at the open internet, cloud services, or any host you do not own. Treat your API key like a password — store it as an environment variable, never hard-code it in a script you commit to a shared repository.
From a physical safety standpoint, this is a software-only lab; standard workstation safety applies (ergonomics, proper seating, no food or drink near equipment). No lockout/tagout or PPE beyond normal lab rules is required.
---
A socket is a software endpoint that enables two-way communication between processes across a network. When you open a TCP socket to a remote host and port, the operating system initiates a three-way handshake (SYN → SYN-ACK → ACK). If the handshake completes, the port is open and a service is listening. If the connection is refused or times out, the port is closed or filtered.
Python's `socket` module exposes this directly:
```python
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(1) # wait 1 second before declaring closed
result = s.connect_ex(("192.168.56.101", 80)) # 0 means success
s.close()
```
`connect_ex()` returns `0` on success and a non-zero error code on failure, making it ideal for scanners because it does not raise an exception on a closed port.
---
Scanning ports 1–1024 sequentially can take minutes because each connection waits for a timeout. Threading solves this by running many connection attempts concurrently. Python's `threading.Thread` class lets you launch a function in a separate thread:
```python
import threading
def scan_port(ip, port, open_ports):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(0.5)
if s.connect_ex((ip, port)) == 0:
open_ports.append(port)
s.close()
```
You create one `Thread` per port, start them all, then call `join()` on each so the main program waits for all threads to finish before saving results. Use a `threading.Lock` when multiple threads write to a shared list to prevent race conditions — two threads updating the same list simultaneously can corrupt data.
Save your results as JSON using `json.dump()`, which produces a structured file that other tools (SIEMs, spreadsheets) can ingest.
---
Threat-intelligence platforms such as AbuseIPDB and VirusTotal expose REST APIs — you send an HTTP GET or POST request and receive a JSON response containing reputation data about an IP address, domain, or file hash. The `requests` library makes this straightforward:
```python
import requests, os
api_key = os.environ.get("ABUSEIPDB_KEY") # never hard-code keys
url = "https://api.abuseipdb.com/api/v2/check"
params = {"ipAddress": "1.2.3.4", "maxAgeInDays": 90}
headers = {"Key": api_key, "Accept": "application/json"}
response = requests.get(url, headers=headers, params=params, timeout=10)
data = response.json()
score = data["data"]["abuseConfidenceScore"]
```
The `timeout` parameter prevents your script from hanging indefinitely if the API server is unreachable — always set one.
---
Production scripts must handle failures without crashing. Wrap network calls in `try/except` blocks and catch specific exceptions:
For a results CSV, use Python's `csv` module with `DictWriter`. If an IP lookup fails, write the IP with a score of `"ERROR"` so the row still exists and analysts know it was attempted.
---
This lesson maps directly to the CySA+ Threat Intelligence domain. Analysts are expected to consume threat feeds, enrich indicator data programmatically, and automate repetitive lookups so they can focus on analysis rather than copy-paste work. Port scanning maps to vulnerability management — identifying which services are exposed on a network asset before an attacker does.
---
1. Confirm your workstation is on the isolated lab VLAN only.
2. Verify the target VM IP with your instructor before scanning.
3. Store your AbuseIPDB API key as an environment variable — confirm with `echo $ABUSEIPDB_KEY`.
4. Never scan beyond the IP range listed in the lab guide.
Answer each question, then check it. Nothing is recorded; this is your own practice.
A free tech program — complimentary, as our commitment to get America working. Help us build VoTechWorks. Tell us what works, what doesn’t, and what you want to learn.