Loading date…
LinkedIn Twitter Instagram YouTube WhatsApp
Malwarebytes - Cybersecurity for Everyone

Linux pstree Command Cheat Sheet: Spot Suspicious Processes Fast

Linux terminal showing pstree process tree with parent-child relationships for SOC incident response and threat hunting

Linux pstree Command Cheat Sheet: Trace Process Ancestry Like a SOC Analyst

Picture a 3 a.m. alert on a Linux web server: "unexpected interactive shell." You run ps aux and get several hundred lines. Somewhere in that wall of text is the one process that matters, but a flat list will not tell you who started it. A process tree will. If the chain reads nginx → sh → bash, you have a very different problem than sshd → bash from an admin's known jump host. This is an illustrative scenario, not a specific incident, but it plays out in Linux threat hunting and SOC incident response every week.

Sponsored
root@kali:~# lsusb
Best Adapters for Kali Linux
Wi-Fi adapters for your pentesting lab
Shop Now →
As an Amazon Associate, I earn from qualifying purchases. This costs you nothing extra.

That is why pstree belongs in every analyst's toolkit. This guide covers the flags that matter, shows how to read the output, and explains how to use pstree in a digital forensics and incident response (DFIR) workflow, including where it can mislead you.

Table of Contents

What pstree Actually Does

pstree is part of the psmisc package. It reads process data from /proc and uses each process's parent PID (PPID) to draw a hierarchy, with PID 1 (usually systemd) at the root. It shows relationships, not intent. That distinction matters later.

Three behaviors surprise newcomers:

  • Threads appear in braces. Entries like {nginx} are threads, not separate processes.
  • Identical siblings are compacted. Several identical children may show as 3*[sshd]. Use -c to expand them.
  • Output is sorted by name by default. Use -n to sort siblings by PID instead.

Essential pstree Flags

You do not need every option. These cover most real investigations. Confirm exact behavior on your system with man pstree, since options vary slightly between psmisc versions.

Flag What It Does Why Analysts Use It
-p Shows PIDs Lets you pivot into /proc, ps, and logs
-a Shows command-line arguments Reveals what a shell or interpreter was told to run
-l Does not truncate long lines Prevents long arguments from being cut off
-n Sorts siblings by PID Newest children tend to appear last, which helps with timelines
-s PID Shows the ancestors of a process Answers "who started this?" quickly
-u Shows UID transitions Highlights where a process changes user, such as a service dropping privileges
-c Disables compaction of identical subtrees Shows every sibling with its own PID
-H PID Highlights a process and its ancestors Makes one branch stand out in a busy tree
-T / -t Hides threads / shows full thread names Cuts noise on multithreaded services
-A, -U, -G ASCII, UTF-8, or VT100 line drawing Use -A when pasting into tickets or terminals that garble line characters

Two more are worth knowing. -Z shows SELinux security context, and -S shows namespace transitions, which is useful on container hosts. Both depend on version and system support. Two notes on the flags above: -h highlights the current process and its ancestors, while -H PID does the same for a PID you choose. And -u shows where the user changes in the tree. It does not print a username beside every process.

Reading pstree Output

Here is illustrative output from pstree -ap. The process names and PIDs are made up for demonstration.

systemd,1
  ├─cron,612 -f
  │   └─cron,2041 -f
  │       └─sh,2043 -c /usr/local/bin/backup.sh
  ├─nginx,845
  │   └─nginx,846
  └─sshd,901
      └─sshd,2210
          └─bash,2230
              └─pstree,2301 -ap

Read it top to bottom. cron launching a shell to run a backup script is routine. An interactive bash under sshd is what you would expect when someone logs in. The question for a SOC analyst is never "is there a shell?" but "does this shell belong under this parent, at this time, for this user?" Baselines make that answer fast.

Starting From a Specific PID or User

On a busy host, do not read the whole tree. Narrow it.

pstree -ap 1234
pstree -sp 1234
pstree -ap 1
pstree -u root
  • pstree -ap 1234 shows the subtree rooted at PID 1234, meaning what that process started.
  • pstree -sp 1234 shows the ancestor chain, meaning what started it.
  • pstree -ap 1 shows the full tree from systemd with arguments.
  • pstree -u root restricts the display to trees belonging to that user. The trailing argument is a username, not a flag.

Replace 1234 with the PID you are investigating. If the PID exits first, pstree will report that no such process exists. Short-lived processes are a limitation we cover below.

pstree for SOC Incident Response Triage

When an alert fires, these commands give you a fast first look. Use sudo so you can see processes owned by other users.

sudo pstree -ap
sudo pstree -ap 1234
sudo pstree -sp 1234

The first command is the full picture, the second is what a suspect process spawned, and the third is its lineage. Expect a text tree. On busy servers, pipe it to less.

Searching the tree for interesting names is tempting, but be careful. A pattern like bash|sh|zsh also matches sshd, and nc matches many unrelated names. Because grep returns single lines, you also lose the parent-child context that made pstree useful. A cleaner workflow is to find candidates by exact name, then ask pstree for each one's ancestry:

pgrep -a -x 'bash|dash|sh|zsh'
for pid in $(pgrep -x 'bash|dash|sh|zsh'); do pstree -sp "$pid"; done

The first line lists exact-name shell matches with arguments. The loop prints the ancestor chain of each. Anything whose chain looks wrong goes on your review list.

Then cross-check the tree against another view of the same data:

ps -eo pid,ppid,user,stat,lstart,args --forest

This adds the owning user, process state, and start time. Start time often matters more than the tree itself, because it lets you line up a process against log entries and the time of the alert.

Suspicious Process Chains to Review

None of these patterns is proof of compromise. Each is a prompt to investigate, and each has legitimate explanations you should rule out.

Chain Why It Deserves a Look Possible Benign Cause
Web server worker → shell Web servers rarely need interactive shells; this can indicate application compromise CGI scripts, deployment hooks, or app features that shell out
cron → download utility → interpreter Common persistence-and-fetch pattern (MITRE ATT&CK T1053.003) Package updates or scheduled sync jobs
sshd → shell at unusual hours or from unusual source May indicate misused or stolen credentials On-call admin work
Interpreter running from /tmp or /dev/shm Writable, world-accessible locations are popular staging areas Installer or build tools
Process name differs from its executable path Possible masquerading (T1036) Wrapper scripts or renamed binaries by vendors
Long-lived process owned by PID 1 with odd arguments Orphaned or daemonized processes get reparented, hiding their real origin Any normal daemon

The interpreter and shell-based rows map to MITRE ATT&CK's Unix Shell technique (T1059.004). Mapping findings to ATT&CK helps when you hand an investigation to another team or write it up for compliance review.

Verify Before You Conclude

Once a process looks suspicious, pivot to the facts the kernel exposes:

ps -p 1234 -o pid,ppid,user,stat,lstart,args
readlink -f /proc/1234/exe
readlink -f /proc/1234/cwd
tr '\0' ' ' < /proc/1234/cmdline
echo
cat /proc/1234/status
  • exe shows the real binary on disk. If the link ends with (deleted), the file was removed after launch, which is worth escalating.
  • cwd shows the working directory. Odd locations such as /tmp add weight to a suspicion.
  • cmdline uses null separators, so tr makes it readable. The extra echo just adds a newline.
  • status includes the name, parent PID, and UIDs.

Then check network activity for that PID:

sudo ss -tunap | grep 'pid=1234'

This lists TCP and UDP sockets tied to the process. Together, ancestry, binary path, arguments, connections, and timestamps give you a defensible conclusion. pstree alone does not.

Snapshots and Automation

During an investigation, preserve what you see. Save timestamped snapshots so you can compare them later:

pstree -ap > "pstree-$(date +%Y%m%d-%H%M%S).txt"
date -Is

The first command writes a full snapshot named with the current time. The second prints an ISO 8601 timestamp for your notes. Keep snapshots on read-only or off-host storage if you suspect tampering.

For a specific PID, check that it exists before querying:

PID=1234
if [ -d "/proc/$PID" ]; then
    pstree -ap "$PID"
else
    echo "PID $PID does not currently exist"
fi

For a quick live view, use watch rather than a flag. pstree itself does not refresh:

watch -n 2 'pstree -ap'

If you want a rolling record, this loop captures a snapshot every ten seconds until you press Ctrl+C:

while true; do
    date -Is
    pstree -ap
    sleep 10
done

Remember the limits of polling. Anything that starts and exits between two snapshots is invisible to this approach.

Where pstree Can Mislead You

  • Short-lived processes disappear. pstree shows a moment in time. For continuous coverage, rely on audit logging or endpoint telemetry instead.
  • Reparenting hides origins. When a parent exits, children are adopted by PID 1 or a subreaper process. A "clean" parent chain can simply mean the real parent is gone.
  • Names can be changed. A process can alter its displayed name or arguments. The /proc/PID/exe link is more trustworthy.
  • PIDs get reused. On long-running systems, a PID from an old log may now belong to something else. Always compare start times.
  • Visibility can be restricted. If /proc is mounted with the hidepid option, non-root users see only their own processes. Compromised hosts can also run tooling designed to conceal processes, so a clean tree is not proof of a clean system.
  • Containers add a layer. On the host, container processes appear under the container runtime. PIDs inside the container differ from host PIDs.

The takeaway: pstree is a relationship and visualization tool, not a malware verdict.

ps -ef --forest
ps auxf
ps -eo pid,ppid,user,stat,etime,args --forest
pgrep -a -f 'python'
pidof nginx
top -c
htop
  • ps -ef --forest and ps auxf give tree views with user and resource details.
  • The custom ps -eo format adds elapsed time (etime), which makes it easy to spot very new processes.
  • pgrep -a -f searches full command lines and prints matches with arguments.
  • pidof returns PIDs for an exact program name.
  • top -c and htop offer interactive views. htop includes a tree toggle.

Detection and Prevention Strategies

Manual pstree checks are great for triage, but they do not scale. Mature teams turn the same logic into automated detections inside their endpoint detection and response (EDR) tooling or SIEM.

Capture Process Execution Continuously

Linux auditd can record every program execution, including the parent PID. This sample rule is a starting point. It generates a lot of data, so test it before enabling it on production systems:

sudo auditctl -a always,exit -F arch=b64 -S execve -k exec_watch
sudo ausearch -k exec_watch -ts recent

The first command adds a runtime rule, and the second searches recent matching events. Rules added this way do not survive a reboot. Persist them in /etc/audit/rules.d/ once you are happy with the volume.

Build Alerts Around Parent-Child Relationships

  • Alert when a web server or database service account starts a shell or scripting interpreter.
  • Alert when cron jobs launch download utilities followed by an interpreter.
  • Flag executables launched from /tmp, /var/tmp, or /dev/shm.
  • Tune each rule against your baseline so legitimate deployment tools do not flood analysts with false positives.

Reduce the Attack Surface

  • Run services under dedicated, least-privilege accounts.
  • Mount temporary directories with noexec where your workloads allow it.
  • Remove unneeded interpreters and download utilities from production servers.
  • Patch internet-facing applications promptly, since application compromise is a common way for a shell to appear under a service account.
Sponsored
root@kali:~# lsusb
Best Adapters for Kali Linux
Wi-Fi adapters for your pentesting lab
Shop Now →
As an Amazon Associate, I earn from qualifying purchases. This costs you nothing extra.

These measures reduce risk but cannot guarantee protection. Layered controls and tested response procedures matter more than any one setting.

Installing pstree

If the command is missing, install the psmisc package.

# Debian / Ubuntu
sudo apt update
sudo apt install psmisc

# Fedora, RHEL, Rocky, AlmaLinux
sudo dnf install psmisc

# Arch Linux
sudo pacman -S psmisc

# Check version and options
pstree --version
pstree --help

Quick Reference

pstree              Basic process tree
pstree -p           Include PIDs
pstree -a           Include command-line arguments
pstree -ap          PIDs + arguments
pstree -n           Sort siblings by PID
pstree -c           Do not compact identical subtrees
pstree -A           ASCII line drawing
pstree -s PID       Show ancestors of a process
pstree -sp PID      Ancestor chain with PIDs
pstree -ap PID      Subtree rooted at a PID
pstree -H PID       Highlight a process and its ancestors (if supported)
watch -n 2 pstree -p   Refresh every 2 seconds

Expert Tips

  • Baseline first. Save a snapshot of a healthy server. Comparing against a known-good tree is faster than judging from memory.
  • Ancestry beats names. A process called python3 is unremarkable. A python3 whose parent is your web server deserves attention.
  • Always record the timestamp. Pair every observation with a start time so it can be matched to logs.
  • Use -A for tickets. ASCII output pastes cleanly into case notes and chat tools.
  • Expect false positives. Configuration management, CI agents, and backup tools legitimately spawn shells. Document them so the next analyst does not repeat the work.
  • Escalate with evidence. Include the tree, the exe path, the command line, connection data, and timestamps in the handoff.

FAQ

What is the pstree command used for?

It displays running processes as a tree based on parent-child relationships. Administrators use it to understand service structure, and security teams use it to trace where a process came from.

What is the difference between pstree -p and pstree -a?

-p adds process IDs. -a adds command-line arguments. Combine them as pstree -ap for most investigations.

How do I find the parent of a specific process?

Run pstree -sp PID to see the full ancestor chain, or ps -p PID -o pid,ppid,comm,args for the immediate parent.

Does pstree refresh automatically?

No. Use watch -n 2 'pstree -ap' to refresh it at an interval. The -c flag only disables compaction of identical subtrees.

Can pstree detect malware?

No. It shows relationships, not intent. Use it to find processes worth investigating, then verify with executable paths, command lines, network connections, and endpoint telemetry.

Why do some processes show up under PID 1?

When a parent process exits, its children are adopted by PID 1 or a designated subreaper. Daemons also detach deliberately, so many legitimate services appear there.

Why is pstree not installed on my system?

It ships in the psmisc package, which some minimal images omit. Install it with your package manager, as shown above.

Conclusion

A flat process list tells you what is running. A process tree tells you why. With a handful of flags, pstree -ap and pstree -sp PID, you can answer the question that drives most Linux triage: who started this? The next step is just as important. Verify the executable, command line, network activity, and timing before drawing a conclusion, and build the relationships that matter into automated detections so you are not relying on a human to be at the keyboard when something starts.

Analysis based on SOC monitoring and hands-on Linux command-line investigation practice.

Shubham Chaudhary

Shubham Chaudhary is a cybersecurity specialist and founder of Xpert4Cyber. He shares practical tutorials, guides and the latest news on Networking, Windows Server, Linux Server, Ethical Hacking, Digital Forensics, Malware Analysis, Threat Hunting and Monitoring, OSINT, Cloud Computing and AI, with a focus on defense and security awareness. Educational and defensive use only.

Post a Comment

Previous Post Next Post