30 Days of CTF Series | Day 6: Python for CTF (Just Enough Python to Solve Challenges)

Welcome to Day 6 of the 30 Days of CTF series.
Remember the robot from Day 4? It asked a simple maths question, you typed the answer and got the flag. Now imagine it asks 100 questions in 10 seconds. No human can type that fast. But a 15 line Python script can.
That is why every CTF player learns Python. You do not need to become a software developer. You only need just enough Python to decode data, read files and talk to servers automatically. That is exactly what we will learn today.
Practice labs for Day 6:
Setting Up Python
Python 3 is already installed on Kali Linux, Parrot OS and most Ubuntu systems. Check it:
$ python3 --version
Python 3.11.2
There are two ways to run Python:
1. Interactive mode (great for quick tests):
$ python3
>>> 2 + 3
5
>>> exit()
2. Script mode (for real solutions). Create a file called solve.py:
$ nano solve.py
Write your code, save it with Ctrl + O, exit with Ctrl + X, then run it:
$ python3 solve.py
Install the CTF library we will use later:
$ pip install pwntools
On newer Kali versions, if pip shows an error about an externally managed environment, use:
$ sudo apt install python3-pwntools
Part 1: Python Basics in 10 Minutes
Variables and printing:
name = "Hacklido"
points = 100
print(name, points)
Strings (text):
flag = "HackCTF{py7h0n_rul3s}"
print(len(flag)) # length of the string: 21
print(flag.upper()) # HACKCTF{PY7H0N_RUL3S}
print(flag[::-1]) # reverse the string
print(flag[0:7]) # first 7 characters: HackCTF
flag[::-1] is a favourite CTF trick. Some challenges hide the flag written backwards.
Lists:
ports = [21, 22, 80, 443]
for port in ports:
print("Checking port", port)
If conditions:
answer = "HackCTF{test}"
if answer.startswith("HackCTF{"):
print("Looks like a flag!")
else:
print("Not a flag")
Loops with range:
for i in range(5):
print(i) # prints 0, 1, 2, 3, 4
Functions:
def add(a, b):
return a + b
print(add(25, 17)) # 42
Note that Python uses indentation (spaces at the start of a line) to group code. Always use 4 spaces inside loops, ifs and functions.
Part 2: Characters, Numbers and Bytes
This is the most important part for CTFs. Computers store every character as a number.
ord() and chr():
print(ord("A")) # 65
print(chr(72)) # H
So if a challenge gives you a list of numbers, they are often letters in disguise:
numbers = [72, 97, 99, 107, 67, 84, 70]
print("".join(chr(n) for n in numbers)) # HackCTF
Strings vs bytes:
Python has normal text (str) and raw data (bytes). Bytes have a b in front:
text = "hello"
data = b"hello"
data = text.encode() # str to bytes
text = data.decode() # bytes to str
Network tools and decoding functions often work with bytes, so remember .encode() and .decode().
Part 3: Decoding Like a CTF Player
On Day 1, you used CyberChef to decode Base64. Here is how to do the same in Python, which is much faster when you have to decode many times.
Base64:
import base64
encoded = "aGFja2xpZG97ZmlyNXRfZmw0Z30="
print(base64.b64decode(encoded).decode())
Hex:
hex_data = "4861636b435446"
print(bytes.fromhex(hex_data).decode()) # HackCTF
Multiple layers:
Some challenges encode the flag again and again. A loop solves it:
import base64
data = "...your encoded text..."
for i in range(20):
try:
data = base64.b64decode(data).decode()
print(i + 1, data)
except Exception:
break
This keeps decoding until it can no longer decode, and prints every layer so you can see the flag appear.
XOR (a CTF classic):
XOR is a simple operation used to hide data. The good news: if you XOR something twice with the same key, you get the original back.
secret = bytes([0x2a, 0x23, 0x21, 0x29])
key = 0x42
print(bytes(b ^ key for b in secret)) # b'hack'
We will go deeper into XOR on Day 15 (Classical Ciphers).
Part 4: Reading Files
with open("data.txt", "r") as f:
content = f.read()
print(content)
Search every line for the flag (like grep, but you can add your own logic):
with open("access.log") as f:
for line in f:
if "HackCTF" in line:
print(line.strip())
Part 5: Talking to Websites with requests
import requests
r = requests.get("http://example.com")
print(r.status_code) # 200
print(r.headers) # response headers
print(r.text) # page content
Combine it with what you already know:
import requests
r = requests.get("http://example.com")
if "HackCTF{" in r.text:
start = r.text.find("HackCTF{")
end = r.text.find("}", start)
print(r.text[start:end + 1])
Part 6: Talking to Servers with pwntools
pwntools is the most popular Python library in CTFs. It makes connecting to a challenge server as easy as using nc.
from pwn import *
io = remote("challenge.hacklido.com", 31337)
print(io.recvline()) # read one line from the server
io.sendline(b"42") # send an answer
print(io.recvall().decode()) # read everything that is left
remote(host, port) is the same as nc host port
recvline() reads one line
recvuntil(b"text") reads until a certain text appears
sendline(b"data") sends data with Enter at the end
interactive() lets you type manually, just like nc
Let’s Solve a Challenge Together
The Day 4 robot is back, and it is faster now:
“Answer 100 maths questions in 10 seconds and the flag is yours.”
nc challenge.hacklido.com 31337
Step 1: Connect manually first to understand the format.
$ nc challenge.hacklido.com 31337
Answer 100 questions. You have 10 seconds.
What is 25 + 17?
42
What is 9 * 6?
Too slow!
Every question looks like What is <number> <operator> <number>?. Now we know the pattern.
Step 2: Write solve.py.
from pwn import *
io = remote("challenge.hacklido.com", 31337)
while True:
line = io.recvline().decode().strip()
print(line)
if "HackCTF{" in line:
break
if line.startswith("What is"):
question = line.replace("What is", "").replace("?", "").strip()
a, op, b = question.split()
a, b = int(a), int(b)
if op == "+":
answer = a + b
elif op == "-":
answer = a - b
elif op == "*":
answer = a * b
io.sendline(str(answer).encode())
What this script does, line by line in simple words:
- Connects to the server.
- Reads one line at a time and prints it.
- Stops when it sees the flag.
- If the line is a question, it removes the extra words, splits it into number, operator and number.
- Calculates the answer and sends it back.
Step 3: Run it.
$ python3 solve.py
Answer 100 questions. You have 10 seconds.
What is 25 + 17?
What is 9 * 6?
...
What is 81 - 39?
HackCTF{pyth0n_b34ts_th3_r0b0t}
Flag captured in under a second. This is the real power of Python in CTFs: understand the pattern manually once, then let the script do the boring work.
Tip: You may see people use eval() to calculate the question directly. Avoid it. If a tricky server sends Python code instead of maths, eval() will run it on your machine.
Try It Yourself on Hacklido
1. Python for Pentesters: Zero to Tool Builder
A complete path that goes from Python basics to building real security tools like a port scanner, banner grabber and hash cracker. Today, complete the basics modules. The tool building modules will be very useful in later weeks.
Link: open learn.hacklido.com/learn and select Python for Pentesters: Zero to Tool Builder.
2. Lost in Base
As the name suggests, this is an encoding challenge. First identify which encoding is used, then try solving it with a Python script instead of CyberChef. The multiple layers loop from Part 3 may come in handy.
Link: learn.hacklido.com/challenges/lost-in-base
3. Obfuscated JavaScript
A developer tried to hide the flag inside a JavaScript file using hex characters. Use your Part 2 and Part 3 skills (chr(), bytes.fromhex()) to rebuild the flag. Check the hints on the challenge page if you get stuck.
Link: learn.hacklido.com/challenges/obfuscated-javascript
Day 6 Cheat Sheet
Save this in your notes:
python3 solve.py: run a script
s[::-1]: reverse a string
ord("A") / chr(65): character to number and back
"text".encode() / b"data".decode(): str to bytes and back
base64.b64decode(data): decode Base64
bytes.fromhex("4861"): decode hex
bytes(b ^ key for b in data): XOR with a single key
open("file").read(): read a file
requests.get(url).text: fetch a web page
remote(host, port): connect to a server (pwntools)
recvline(), recvuntil(), sendline(), interactive(): talk to the server
- Golden rule: solve it manually once, then automate it
Day 6 Task
What’s Next?
In Day 7, we will cover Encoding vs Encryption and finish Week 1 with a full review. You will learn to recognise Base64, Hex, Binary, URL encoding and ROT13 at a glance, and then put all of Week 1 together.
See you tomorrow on Day 7. Happy hacking.