Python Modules for Networking & Cybersecurity
Introduction
Python provides many modules that let you interact with networks, create servers, and secure data.
In this section we cover Scapy, socket, hashlib, and cryptography with simple examples.
Scapy Basics
Scapy is a powerful library for packet crafting and analysis. It allows you to sniff (capture) packets,
build custom packets, and send them. It is used for learning and testing network security.
Example: Sniff Packets with Scapy
This code listens for packets and prints a summary of each one.
Socket Module
The socket module gives low-level access to network connections. You can build servers, clients,
and experiment with TCP/UDP communication.
Example: Simple TCP Client
The following code connects to [Link] on port 80 and sends a basic HTTP request.
Hashlib
Hashlib provides hashing algorithms such as SHA-256 and MD5. Hashes are used to verify data
integrity. They are one-way functions.
Example: Hash a Password
This code converts a password into a SHA-256 hash to store securely.
Cryptography
The cryptography module allows encryption and decryption of data. You can encrypt files,
messages, or keys to protect sensitive information.
Example: Encrypt and Decrypt a Message
This code shows how to use Fernet symmetric encryption.
Scapy Sniffing Example
from [Link] import sniff
def show_packet(packet):
print([Link]())
sniff(count=5, prn=show_packet)
Socket TCP Client Example
import socket
s = [Link](socket.AF_INET, socket.SOCK_STREAM)
[Link](("[Link]", 80))
[Link](b"GET / HTTP/1.1\r\nHost: [Link]\r\n\r\n")
print([Link](1024))
[Link]()
Hashlib Example
import hashlib
password = "mypassword"
hashed = hashlib.sha256([Link]()).hexdigest()
print("SHA256 Hash:", hashed)
Cryptography Example
from [Link] import Fernet
key = Fernet.generate_key()
cipher = Fernet(key)
message = b"Hello, Sudais!"
encrypted = [Link](message)
decrypted = [Link](encrypted)
print("Key:", key)
print("Encrypted:", encrypted)
print("Decrypted:", decrypted)