827 words
4 minutes
Python OS Module – Practical Guide for Red Teamers

The os module helps Python talk to the Operating System.

As a red teamer / bug hunter / pentester etc …, you can use os module to:

  • Work with files and folders

  • Change current directory

  • Read environment variables (like PATH)

  • Build paths in a safe way

In this lesson we do no OOP. Only simple scripts.


1. Import os#

import os

You write this at the top of your script.


2. Current Working Directory (CWD)#

The current working directory is the folder where your script is running. (pwd in linux)

2.1 Get current directory#

import os
current = os.getcwd()
print(current)

Example output:

/home/zeroshadow/tools

This is useful to know where you are before reading or writing files.

2.2 Change directory (cd in Linux)#

import os
os.chdir("/home/zeroshadow/Documents")
print(os.getcwd())

Example output:

/home/zeroshadow/Documents

As a red teamer, you can change into:

  • loot folders

  • reports folders

  • wordlists folders


3. List Files and Folders (ls in linux)#

3.1 os.listdir()#

import os
items = os.listdir(".") # "." means current directory
print(items)

Example output:

['wordlists', 'reports', 'scan.py']

This is useful to:

  • See if wordlist exists

  • See scan result files

  • Check for log files

3.2 List files in a specific path#

import os
items = os.listdir("/home/zeroshadow/recon")
print(items)

4. Create and Remove Folders#

4.1 Create one folder — os.mkdir()#

import os
os.mkdir("loot")
print("Folder created: loot")

Now a folder named loot exists.

4.2 Create many nested folders — os.makedirs()#

import os
os.makedirs("loot/targets/reports")
print("Folders created: loot/targets/reports")

4.3 Remove empty folder — os.rmdir()#

import os
os.rmdir("empty_folder")
print("Removed: empty_folder")

os.rmdir() works only if folder is empty.


5. Work with Files#

For red team, files are:

  • scan.txt

  • targets.txt

  • passwords.txt

5.1 Delete a file — os.remove()#

import os
os.remove("old_scan.txt")
print("Deleted old_scan.txt")

5.2 Rename a file — os.rename()#

import os
os.rename("scan_temp.txt", "scan_final.txt")
print("Renamed file")

5.3 Rename / move a file to folder#

import os
os.rename("scan_final.txt", "reports/scan_final.txt")
print("Moved scan_final.txt to reports/")

This is useful after a scan: move result file into a reports folder.


6. Paths — os.path#

You should not hard-code paths with / or \\. Windows and Linux are different.

Use os.path to build paths in a safe way.

6.1 Join paths — os.path.join()#

import os
base = "/home/zeroshadow/recon"
file_name = "targets.txt"
path = os.path.join(base, file_name)
print(path)

Example output (Linux):

/home/zeroshadow/recon/targets.txt

6.2 Check if path exists — os.path.exists()#

import os
if os.path.exists("wordlists/common.txt"):
print("Wordlist found!")
else:
print("Wordlist missing!")

Example output:

Wordlist found!

6.3 Check if it is a file or folder#

import os
path = "reports"
if os.path.isdir(path):
print(path, "is a directory")
if os.path.isfile("scan.txt"):
print("scan.txt is a file")

Example output:

reports is a directory
scan.txt is a file

7. Environment Variables — os.environ#

Environment variables store system data like:

  • PATH

  • HOME

  • API keys (sometimes)

7.1 Read all environment variables#

import os
env = os.environ
print(env)

Output is big. It shows many keys and values.

7.2 Read one variable (example: PATH)#

import os
path = os.environ.get("PATH")
print("PATH:")
print(path)

As a red teamer, you can:

  • See where binaries are

  • See if a tool folder is in PATH

7.3 Set environment variable (only in this script)#

import os
os.environ["API_KEY"] = "test123"
print(os.environ.get("API_KEY"))

Output:

test123

This is useful for tools that read API keys from environment.


8. Walk Through Directories — os.walk()#

os.walk() lets you go through folders and files inside. Very useful for:

  • Finding config files

  • Looking for .php, .log, .bak, .zip, etc.

8.1 Simple walk example#

import os
for root, dirs, files in os.walk("."):
print("Current folder:", root)
print("Subfolders:", dirs)
print("Files:", files)
print("----")

This prints all folders and files under current directory.

8.2 Find all .log files#

import os
for root, dirs, files in os.walk("."):
for f in files:
if f.endswith(".log"):
full_path = os.path.join(root, f)
print(full_path)

As a red teamer, you can search for:

  • .log (logs)

  • .bak (backup files)

  • .sql (database dumps)

  • .conf (config files)


9. Running System Commands (Basic)#

For real work, it is better to use subprocess, but here is a simple example with os.system().

import os
os.system("ls") # on Linux

Or on Windows:

import os
os.system("dir")

This runs the command in the shell. For red team, you can:

  • Call nmap

  • Call ping

  • Call your own tools

⚠ For serious tools, use subprocess instead. It is safer.


10. Mini Red-Team Examples#

10.1 Check Important Folders#

import os
paths = ["wordlists", "reports", "loot"]
for p in paths:
if os.path.exists(p):
print(p, "OK")
else:
print(p, "MISSING")

Example output:

wordlists OK
reports MISSING
loot OK

10.2 List Only .txt Files in Current Folder#

import os
for name in os.listdir("."):
if name.endswith(".txt"):
print("TXT:", name)

Example output:

TXT: targets.txt
TXT: passwords.txt
TXT: scan.txt

⭐ Final Project — Simple Red Team File Manager#

Goal: build a small script that:

  1. Creates folders for a target

  2. Saves paths in a clean way

  3. Checks if important files exist

  4. Lists report files

🔹 Step 1 — Code#

import os
# 1) Ask for target name
target = input("Enter target name (example: acme.com): ").strip()
# 2) Build base folder for this target
base_dir = os.path.join("loot", target)
reports_dir = os.path.join(base_dir, "reports")
wordlists_dir = os.path.join(base_dir, "wordlists")
# 3) Create folders if they do not exist
for folder in [base_dir, reports_dir, wordlists_dir]:
if not os.path.exists(folder):
os.makedirs(folder)
print("Created:", folder)
else:
print("Exists:", folder)
# 4) Check for a main wordlist file inside wordlists
main_wordlist = os.path.join(wordlists_dir, "main.txt")
if os.path.exists(main_wordlist):
print("Wordlist found:", main_wordlist)
else:
print("Wordlist missing:", main_wordlist)
# 5) List report files if any
print("\nReport files:")
if os.path.exists(reports_dir):
files = os.listdir(reports_dir)
if not files:
print("No reports yet.")
else:
for f in files:
print("-", f)
else:
print("Reports folder does not exist.")

🔹 Step 2 — What this project does#

  • Asks you for a target name (like acme.com)

  • Creates this structure if missing:

    • loot/<target>/

    • loot/<target>/reports/

    • loot/<target>/wordlists/

  • Checks if loot/<target>/wordlists/main.txt exists

  • Lists report files in loot/<target>/reports/

This is a real base for a red team / bug bounty file system. You can later add:

  • scan results

  • screenshots

  • notes

  • export to report


End of os Module Lesson ✅#

You now know how to:

  • Work with folders

  • Work with files

  • Build paths

  • Use environment variables

  • Walk directories