Build a Python Process Monitor That Flags Suspicious Programs (Full Code)


Most malware doesn’t announce itself. It hides as a process with a boring name — svchost.exe, update, systemd-helper — running quietly in the background. The best defense is knowing what normal looks like on your machine, so anything strange stands out. Today we’ll build a Python process monitor that snapshots running processes and flags the suspicious ones.

The Code

import psutil
import time
from datetime import datetime
# Install first: pip install psutil
# Known-good system process names (add your own)
TRUSTED = {"systemd", "sshd", "cron", "bash", "python3",
"NetworkManager", "dbus-daemon", "dockerd"}
# Red flags in a process name or path
SUSPICIOUS_WORDS = ["miner", "xmrig", "crypt", "keylog",
"rat", "backdoor", "shell", "inject"]
def scan_processes():
findings = []
for proc in psutil.process_iter(["pid", "name", "exe", "username", "cpu_percent"]):
try:
info = proc.info
name = (info["name"] or "").lower()
exe = (info["exe"] or "").lower()
reasons = []
# Runs from a temp or hidden directory
if "/tmp/" in exe or "/dev/shm/" in exe:
reasons.append("runs from temp/hidden directory")
# Suspicious keyword in name or path
if any(w in name or w in exe for w in SUSPICIOUS_WORDS):
reasons.append("suspicious keyword in name/path")
# High CPU with an unknown name
if info["cpu_percent"] and info["cpu_percent"] > 80 \
and info["name"] not in TRUSTED:
reasons.append(f"high CPU usage ({info['cpu_percent']}%)")
# No executable path at all (common for injected code)
if not exe:
reasons.append("no executable path (possible injection)")
if reasons:
findings.append((info["pid"], info["name"],
info["username"], reasons))
except (psutil.NoSuchProcess, psutil.AccessDenied):
continue
return findings
def main():
print(f"[{datetime.now():%H:%M:%S}] Scanning processes...\n")
findings = scan_processes()
if not findings:
print("No suspicious processes found. All clear.")
for pid, name, user, reasons in findings:
print(f"[!] PID {pid} — {name} (user: {user})")
for r in reasons:
print(f" - {r}")
if __name__ == "__main__":
main()

How It Works

  1. Snapshot — psutil.process_iter lists every running process with its PID, name, executable path, owner and CPU usage.
  2. Location check — legitimate programs don’t run from /tmp or /dev/shm. Malware often does, because those directories are writable by anyone.
  3. Keyword check — names containing “miner”, “keylog” or “backdoor” are obvious, but the check catches sloppy malware that names itself honestly.
  4. Behavior check — a process burning 80%+ CPU that isn’t in your trusted list deserves a look. Crypto miners are the classic case.
  5. Missing path — a process with no executable path on disk is a strong injection signal.

Try It

Save as procmon.py, run pip install psutil, then python3 procmon.py. On a clean system you’ll see nothing — that’s the point. Run it again after starting a test program from /tmp and watch it flag the location.

Level Up

  • Baseline mode: run a scan on a clean system, save the process list to a file, and only alert on new names in later scans. That’s how real EDR tools think.
  • Loop it: wrap main() in a while True with time.sleep(300) and log findings to a file — a poor man’s always-on monitor.
  • Add alerts: send yourself an email or Telegram message when a finding appears, using the same pattern as our earlier uptime monitor.
  • Check network connections: proc.connections() shows which processes have open sockets — a process phoning home to a strange IP is the strongest signal of all.

You just built the core idea behind endpoint detection tools. Knowing what’s normal on your own machine is the first step to catching what isn’t.

Comments

Popular Posts