Python for Cybersecurity
Python is the most widely used language in cybersecurity thanks to its versatility, the wealth of specialised libraries it offers, and the ease with which it lets you automate tests, network analysis, exploit development and interaction with remote services.
Virtual environments
Virtual environments are isolated environments that let you manage the dependencies and package versions required by a specific project, avoiding conflicts with globally installed libraries.
Creating and managing an environment with venv
# Create a new environment called "env"
python3 -m venv env
# Activate the environment (Linux/macOS)
source env/bin/activate
# Activate the environment (Windows)
env\Scripts\activate.bat
# Deactivate the environment
deactivate
Once the environment is active, all packages installed with pip remain isolated within it.
Creating and managing an environment with Anaconda
Anaconda provides a pre-configured Python distribution with many data science and cybersecurity libraries:
# Create a new environment
conda create --name env
# Activate the environment
conda activate env
# Deactivate the environment
conda deactivate
Installing Python libraries
Global installation
# Windows
pip install library_name
# Linux/macOS
pip install library_name
# or, with administrator privileges:
sudo pip install library_name
# or, in your home directory:
pip install --user library_name
Installation in an Anaconda environment
# With conda (searches the official channel)
conda install library_name
# With pip (searches PyPI)
pip install library_name
Uninstalling libraries
pip uninstall library_name # global or venv
conda remove library_name # in Anaconda environment
Main Python libraries for Cybersecurity
Pyshark — network analysis with Wireshark
Lets you analyse network packets through Wireshark’s Python interface.
pip install pyshark
import pyshark
# Capture packets in real time on the eth0 interface
cap = pyshark.LiveCapture(interface='eth0')
for pkt in cap.sniff_continuously(packet_count=10):
print(pkt)
Use cases: traffic analysis, network monitoring, filtering packets by protocol or field.
Pwntools — exploit development and CTF
Specialised library for writing exploits and interacting with remote services during CTF competitions.
pip install pwntools
from pwn import *
conn = remote('example.com', 1337)
conn.recvuntil(b'Input:')
conn.sendline(b'payload')
conn.interactive()
Use cases: CTF, exploit development, binary interaction, payload construction, debugging with GDB.
Pycryptodome — cryptography
Implements cryptographic algorithms and protocols: AES, RSA, SHA, HMAC, Diffie-Hellman and many more.
pip install pycryptodome
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
key = get_random_bytes(16)
cipher = AES.new(key, AES.MODE_EAX)
ciphertext, tag = cipher.encrypt_and_digest(b'secret message')
Use cases: data encryption/decryption, digital signatures, hashing, key exchange.
Scapy — low-level packet manipulation
Lets you create, send, receive and manipulate network packets at a low level.
pip install scapy
from scapy.all import *
# Send an ICMP packet (ping)
pkt = IP(dst="192.168.1.1") / ICMP()
reply = sr1(pkt, timeout=2)
if reply:
reply.show()
Use cases: network security testing, port scanning, sniffing, spoofing, DoS attacks (in a lab environment).
Requests — interacting with APIs and the web
Simplifies sending HTTP requests and handling responses.
pip install requests
import requests
# GET request with authentication
r = requests.get('https://api.example.com/data',
headers={'Authorization': 'Bearer TOKEN'})
print(r.status_code, r.json())
# POST request
r = requests.post('https://api.example.com/login',
json={'user': 'mario', 'pass': 'secret'})
Use cases: web API interaction, file downloading, authentication, web scraping.
BeautifulSoup — web scraping
Makes it easy to parse and extract data from HTML and XML documents.
pip install bs4
import requests
from bs4 import BeautifulSoup
r = requests.get('https://example.com')
soup = BeautifulSoup(r.text, 'html.parser')
# Extract all links
for link in soup.find_all('a'):
print(link.get('href'))
Use cases: web scraping, information extraction, crawling.
Selenium — browser automation
Automates the control of web browsers (Chrome, Firefox, etc.).
pip install selenium
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get('https://example.com/login')
driver.find_element(By.ID, 'username').send_keys('mario')
driver.find_element(By.ID, 'password').send_keys('secret')
driver.find_element(By.ID, 'submit').click()
Use cases: simulating user actions, web application testing, crawling JavaScript-heavy sites, form automation.
Library summary
| Library | Installation | Main use |
|---|---|---|
pyshark | pip install pyshark | Network packet analysis |
pwntools | pip install pwntools | CTF and exploit development |
pycryptodome | pip install pycryptodome | Cryptography |
scapy | pip install scapy | Low-level packet manipulation |
requests | pip install requests | HTTP, web APIs |
beautifulsoup4 | pip install bs4 | HTML/XML web scraping |
selenium | pip install selenium | Browser automation |
Additional resources
- Example repository: GitHub IIS-A-Avogadro-VC/cybersecurity
- pwntools documentation: docs.pwntools.com
- Scapy documentation: scapy.net
Ethical note: all the tools presented here must be used exclusively in authorised environments (labs, CTF competitions, your own systems). Unauthorised access to computer systems is illegal.
EC