Replaced 12 Third-Party Packages with Python Stdlib
1. What I Built by Hand
I made a standalone Linux administration and security auditing tool called Linux_sys_admin.py. Attacks on Linux servers are so common nowadays and privilege escalation (LPE) is a constant headache. Admins usually end up running dozens of separate commands or writing messy bash scripts just to inspect the kernel state. My script brings security checking user audits current process inspection and file tracking into one place with zero third-party libraries
The script requires root permissions so it can safely read system-level files and kernel vfs(/proc). It checks things like duplicate accounts with UID 0 world-writable files(perm:777) SUID and SGID binaries and listening sockets(TCP/UDP).
2. Zero-Dep Verification Proofs
I have also made a python file for checking third-party packages in a python script and spotting it out :
First is verify_stdlib.py. It uses Python's own AST engine to parse every single import statement in the source code and validates each module against sys.stdlib_module_names. If a third-party module secretly get's imported in the test shows an error.
Second is deps-proof.txt which records the clean environment footprint.
Here is the actual check from verify_stdlib.py that walks the AST and flags anything that is not in sys.stdlib_module_name :
import ast
import sys
def find_bad_imports(filepath):
"""Walks the AST and flags any import that is not stdlib"""
with open(filepath, "r") as f:
tree = ast.parse(f.read(), filename=filepath)
stdlib = sys.stdlib_module_names
bad = []
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
root = alias.name.split(".")[0]
if root not in stdlib:
bad.append(root)
elif isinstance(node, ast.ImportFrom):
if node.module:
root = node.module.split(".")[0]
if root not in stdlib:
bad.append(root)
return bad
If this returns an empty list the script is clean.
3. What Packages I Would Normally Reach For
If this were an everyday project without zero-dependency constraints I would have immediately reached for:
psutil • watchdog • click • rich • colorama • tabulate • sdbus • systemd-python • pyyaml • filelock • xxhash • argcomplete
4. What It Actually Took to Replace Them
Swapping out those packages meant writing the underlying logic by hand. Here is the full breakdown of decisions and tradeoffs:
In total this ended up replacing 12 packages with a few hundred extra lines of stdlib code that I wrote by hand and when I checked pip list before and after there was nothing left to install at all so a fresh clone runs on any box with just python3 and no requirements.txt needed.
| Package | Standard Library Used | Why and How |
|---|---|---|
click |
argparse |
Flag parsing subcommand dispatch and auto-generated help screens are already built into argparse. So replacing it with click was not a big deal for me. |
psutil (processes) |
os.listdir("/proc") |
The Linux kernel exposes live process information as virtual text files. Reading status and cmdline directly helps us to skip psutil library. |
psutil (network) |
Manual parse of /proc/net/* |
Listening ports and socket states are stored in /proc/net/tcp and udp. I wrote hex address conversion logic to extract them directly. |
rich / colorama |
Raw ANSI escape sequences | Color codes like \033[91m are standard terminal escapes. I used them(writing the ANSI escape codes where a big headache for real). |
watchdog |
hashlib.sha256 + polling |
Finding a stdlib substitute for watchdog took hours. Watchdog watches files in real time through inotify so I switched to point-in-time checks hashing files whenever the user asks. This was probably the biggest tradeoff in the whole project because inotify tells you in a split of a second a file changes and my version only knows if a file changed whenever --check(switch) gets run next which could be minutes or hours later depending on how often the admin runs it. For a security tool that is a real gap since an attacker could modify a file and revert it before the next check and it would never show up in the hashes.json diff. I decided this was an acceptable tradeoff for a zero dependency hackathon build because inotify support in pure python without watchdog basically means writing raw inotify syscalls which was a difficult job to do which was eventually a rabbit hole.I had and point in time hashing still catches the vast majority of real tampering scenarios. |
xxhash |
hashlib.sha256 |
xxhash is fast but non-cryptographic. For system security and file modification tracking a cryptographic hash matters much more.To be honest this was my first smart choice of stdlib instead of the third-party library |
sdbus / systemd-python |
subprocess.run(["systemctl", ...]) |
Direct D-Bus bindings need C extensions. Calling the native systemctl binary already on the machine gives the same active service list. |
tabulate |
Manual f-string formatting | Fixed-width output like f"{name:<20}{uid:<8}" handles clean terminal columns without an extra formatting package. |
pyyaml / toml |
json |
hashes.json stores the file metadata database.Toml was also a good choice though I would have used that instead. |
filelock |
os.replace() atomic swap |
Instead of file locking I write data to a temporary file first and swap it into place with os.replace() which is an atomic operation on Linux. |
pwd helpers |
pwd & grp |
UID-to-username and GID-to-group lookups are native standard library modules on POSIX systems. |
argcomplete |
bash_tab_complete.bash |
Instead of a Python package I wrote a standalone bash completion function using the shell's builtin complete command.This script was completely optional though so I won't include that in my main stdlib replace count. |
Replacing psutil for Process Reading in Code
With psutil installed this would have been one line like psutil.process_iter() and it hands you back memory and CPU fields ready to use. Here is the actual chunk from my script reading /proc directly instead since that comparison is really the whole point of this writeup:
def read_proc_file(path):
try:
with open(path, "r") as f:
return f.read()
except (FileNotFoundError, PermissionError, OSError):
return None
def audit_processes():
proc_path = "/proc"
processes = []
for entry in os.listdir(proc_path):
if not entry.isdigit():
continue
pid = entry
status = read_proc_file(os.path.join(proc_path, pid, "status"))
cmdline = read_proc_file(os.path.join(proc_path, pid, "cmdline"))
if status is None:
continue
name = pid
uid = "?"
for line in status.splitlines():
if line.startswith("Name:"):
name = line.split(":", 1)[1].strip()
elif line.startswith("Uid:"):
uid = line.split()[1]
if cmdline:
command = cmdline.replace("\x00", " ").strip()
else:
command = name
processes.append((int(pid), uid, name, command))
The psutil version is obviously shorter but it hides everything behind the library. Reading status and cmdline by hand meant I had to actually learn the format of those files instead of just trusting a wrapper. Right now my version only pulls PID UID name and command out of status and cmdline since that was enough for a security audit but memory and CPU fields live in the same status file so adding them later is just a few more lines in that same for loop and not a rewrite.
Replacing Filelock and Watchdog in Code
Here is the chunk from my script showing chunk-based SHA-256 calculation and JSON writes:
import hashlib
import json
import os
def calculate_hash(filepath):
"""Calculates SHA-256 in 4096-byte binary chunks with pure hashlib"""
sha256 = hashlib.sha256()
try:
with open(filepath, "rb") as f:
while chunk := f.read(4096):
sha256.update(chunk)
return sha256.hexdigest()
except (PermissionError, FileNotFoundError):
return None
def save_hashes_atomically(data, target="hashes.json"):
temp_file = f"{target}.tmp"
with open(temp_file, "w") as f:
json.dump(data, f, indent=2)
os.replace(temp_file, target)
5. The 13 Security Commands Built In
Here is what each flag in the main script actually executes when run against a live system:
6. Other Projects & Work
Apart from this zero-dependency hackathon tool here are some of my other open-source projects built for Linux environments and Android security:
You can check out the rest of my repos directly on my GitHub: github.com/Bhavishyaa12