🚧 Under construction — VoTechWorks is being built. A free tech program — complimentary, as our commitment to get America working.
voTechWorksGrade 13 · a vocational technology learning center, by urbanicity
newSchoolWorks.com › VoTechWorks › Technology & Design › Cybersecurity › Scripting for Cybersecurity › Lesson 7
TEC-CYBE44-05 · Lesson 7 · 14 clock hours · lab

Python Networking: Sockets, Requests, and Service Interrogation

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.

⚠ Pending professional review

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 Networking: Sockets, Requests, and Service Interrogation

Why Python for Cybersecurity?

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.

---

Authorized Use and Lab Safety

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.

---

How Sockets Work

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.

---

Building a Multi-Threaded Port Scanner

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.

---

The Requests Library and HTTP APIs

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.

---

Graceful Error Handling

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.

---

Connecting to CySA+ Objectives

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.

---

Lab Checklist Before You Start

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.

Key terms9

SocketA software interface that allows a program to send and receive data over a network; in Python, the socket module provides access to TCP and UDP communication primitives.
connect_ex()A Python socket method that attempts a TCP connection and returns 0 on success or a non-zero error code on failure, without raising an exception — useful in port scanners.
ThreadingA technique for running multiple tasks concurrently within one process; in a port scanner, each thread checks a different port simultaneously, greatly reducing total scan time.
Race ConditionA bug that occurs when two or more threads read and write shared data at the same time in an unpredictable order, potentially corrupting results; prevented with a threading.Lock.
REST APIA web service interface that accepts HTTP requests (GET, POST, etc.) and returns structured data, typically JSON; threat-intelligence platforms expose REST APIs for automated lookups.
Abuse Confidence ScoreA numeric value (0–100) returned by AbuseIPDB indicating how likely an IP address is to be malicious, based on community-submitted abuse reports.
Environment VariableA named value stored in the operating system's process environment; used to pass secrets like API keys to scripts without embedding them in source code.
Timeout (network)A maximum wait period set on a network call; if the remote host does not respond within that time, the call fails with a Timeout error rather than blocking forever.
Threat Intelligence FeedA data source — such as AbuseIPDB or VirusTotal — that provides continuously updated information about known malicious IPs, domains, URLs, or file hashes.
In class: Instructor demo: write a simple TCP port scanner using Python sockets that accepts a target IP and port range, attempts connections with a timeout, and prints open/closed results — emphasizing that this is run only against lab VMs the student owns. · Lab exercise: students build on the demo to produce a multi-threaded port scanner using threading.Thread that scans ports 1–1024 on a provided lab target VM, records open ports, and saves results to a JSON file. · API integration exercise: students write a Python script that reads a list of IP addresses from a file, submits each to the AbuseIPDB or VirusTotal public API (using a free account key stored as an environment variable), and appends the abuse-confidence score to a results CSV.
Materials: Ubuntu VM, isolated lab network with designated target VM, Python 3 socket and requests documentation, free AbuseIPDB API account, course lab guide chapter 7, CompTIA CySA+ objectives (threat intelligence domain)
Check: Port scanner correctly identifies all open ports on the lab target (verified against instructor's known-open-ports list), saves valid JSON, and the API script appends scores without crashing on an unreachable IP; 100% of known-open ports must be found, API script must handle errors gracefully.

Practice check8

Answer each question, then check it. Nothing is recorded; this is your own practice.

Compliance and Assessment
1. A student runs a Python port scanner against a host on the internet without permission. Which law most directly makes this unauthorized access a federal crime in the United States?
Security Operations
2. In Python's socket module, what does a return value of 0 from connect_ex() indicate?
Security Operations
3. Why is a threading.Lock used when multiple threads write to a shared list in a port scanner?
Security Operations
4. An analyst's Python script submits IP addresses to a threat-intelligence API. The script must not crash when an IP address is unreachable. Which approach best satisfies this requirement?
Threats, Attacks and Vulnerabilities
5. Which practice best protects a free-tier API key used in a Python threat-intelligence script?
Threat Intelligence
6. A CySA+ analyst wants to enrich a list of suspicious IP addresses with community-sourced abuse data automatically. Which capability of AbuseIPDB best supports this workflow?
Security Operations
7. A multi-threaded port scanner finishes but the saved JSON file is missing several open ports that were confirmed manually. What is the most likely cause?
Threat Intelligence
8. Which CompTIA CySA+ domain most directly covers the skill of programmatically consuming threat-intelligence feeds to enrich indicator data?
Record this lesson on my transcript. Sign in with your key and enrollment email to record lessons (enroll free if you have no key). This page stays open to read and practise.