Linux System Administration Questions
Operating and maintaining Linux and Unix systems: filesystems and permissions, process and service management, package management and updates, shell and scripting, storage, and network configuration on the host. Covers day-to-day administration, troubleshooting, monitoring and tuning host resource usage (CPU, memory, swap, and I/O), and hardening of Linux servers that underpin most infrastructure. The Linux operator's core skill set.
Explain the purpose of SELinux or AppArmor and how mandatory access control differs from traditional Unix discretionary permissions. Show commands to check whether SELinux is enforcing, list file contexts with ls -Z, and find denials logged in audit logs.
Sample Answer
Direct answer
Mandatory access control (MAC) is a system-wide policy set by an administrator that constrains what EVERY
process can do regardless of file ownership, not even the owner (and, depending on policy, not even root)
can grant more access than policy allows; discretionary access control (DAC), the traditional Unix
owner/group/other permission bits, instead lets the resource's OWNER decide who else gets access, with no
layer above that decision. The two stack: DAC is checked first, and if it allows the access, MAC (SELinux
or AppArmor) is checked second and can still say no, MAC is strictly additive, it can only restrict further,
never grant what DAC itself denies.
Structured elaboration
A process running as root normally bypasses almost all DAC checks, exactly the scenario MAC exists to
constrain: even a process running as root, if confined by an SELinux or AppArmor policy, is limited to the
specific files, sockets, and capabilities its policy actually names, so a vulnerability in that one service
does not automatically translate into full root-level filesystem access, a real, meaningful reduction in
blast radius.
SELinux (Security-Enhanced Linux, originally developed by the NSA and merged into the mainline kernel)
is label-based: every process and file carries a security context (a type, for example httpd_t for a
running Apache HTTP Server process, httpd_config_t for its config files), and policy is written as rules
over pairs of these types, "type enforcement". It is the default MAC system on Red Hat Enterprise Linux,
Fedora, and the CentOS/Rocky/AlmaLinux family.
AppArmor is path-based instead: profiles are written per executable path (the binary at a given path may
read these paths, write those paths), generally easier to read and write than SELinux's type system, but
inherently a little less precise, since path-based rules can be fooled by symlinks or bind-mounts more
easily than label-based rules that travel with the file's own inode-associated context. It is the default
MAC system on Ubuntu and the SUSE family.
Checking whether SELinux is enforcing: getenforce returns Enforcing (blocking and logging denials),
Permissive (logging only, useful for safely testing a new policy), or Disabled; sestatus gives fuller
detail including the loaded policy name and version.
Listing file contexts: ls -Z <path> appends the SELinux context (user:role:type:level, for example
system_u:object_r:httpd_config_t:s0) to normal ls output; ps -Z does the same for running processes.
Finding denials in the audit logs: ausearch -m avc -ts recent (AVC, access vector cache, the kernel's
decision cache for these checks, "AVC denial" being the standard term for a logged block) pulls matching
entries from /var/log/audit/audit.log; if auditd isn't running, the same denial may still surface via
journalctl or dmesg through the kernel's audit subsystem falling back to printk.
Worked example
Two identical Apache HTTP Server installs, serving from /var/www/html, one on a distribution using
SELinux, one using AppArmor. On the SELinux host, moving a file into that directory with mv from a user's
home directory carries the SOURCE directory's label along with it (every file has an inode, the kernel's
on-disk record of its metadata, ownership, permissions, and, under SELinux, its security label, kept
separately from the file's name; a mv within the same filesystem just re-points a directory entry at the
same inode rather than creating a new file, so the label, being a property of that inode, is preserved
across a same-filesystem move), so the file often ends up mislabeled and unreadable by httpd until
restorecon fixes it, a very common real-world surprise. On the AppArmor host, the equivalent failure
instead comes from a profile written against one specific path that doesn't cover a symlinked alternate
document root, since AppArmor's path matching doesn't automatically follow a symlink's target the way a
label-based check would.
Trade-offs and pitfalls
The single most common operational mistake with either system is treating a MAC denial as a reason to
disable the whole subsystem (setenforce 0 permanently, or leaving every AppArmor profile in complaint-only
mode) rather than fixing the one specific rule, throwing away the entire security benefit fleet-wide for a
one-file problem. Also, don't assume DAC becomes irrelevant once MAC is added, an attacker or a broken
deploy still has to clear the classic Unix permission check FIRST, a hardening review has to check both
layers, not just the newer one.
Give a command-line recipe to trace file descriptor leaks in a long-running server process. Include how you'd detect growth over time, correlate FDs to file paths or sockets, and tools to aggregate results across a fleet.
Sample Answer
Direct answer
Count file descriptors (FDs, the small integers a process uses to refer to open files, sockets, and pipes)
over time via /proc/<pid>/fd, resolve what each one actually points at with readlink, and cross-check
names with lsof; a leak is a specific target that keeps reappearing without ever closing, not just a
rising raw count.
Command-line recipe
Detect growth over time: a simple watch loop is often enough for a single host:
watch -n5 'ls /proc/<pid>/fd | wc -l'
For a trend you can graph rather than eyeball, append timestamped rows instead:
while true; do
echo "$(date +%s),$(ls /proc/<pid>/fd 2>/dev/null | wc -l)"
sleep 5
done >> fd-count.csv
Correlate FDs to file paths or sockets: raw counts alone don't tell you what's leaking, resolve the
targets and rank by how often each one repeats:
for fd in /proc/<pid>/fd/*; do readlink "$fd"; done | sort | uniq -c | sort -rn | head
Many identical entries (the same file path, or many socket:[nnnn] entries with no corresponding closes)
is the actual leak signal. lsof -p <pid> gives the same information in a more readable form, including the
type (regular file, socket, pipe) and, for sockets, the remote peer.
Aggregate results across a fleet: run the same one-liner via your existing fan-out mechanism (an SSH
loop over hosts, or your configuration-management tool's ad-hoc exec) and collect hostname,pid,fd_count
rows into one place, so you can rank hosts by growth RATE rather than manually checking one host at a time.
An early, cheaper warning sign worth watching independently of the count itself is /proc/<pid>/limits's
"Max open files" row: a slow leak typically first shows up in application logs as EMFILE (too many open
files) errors right around when the FD count approaches that limit.
Worked example
A reproducible demonstration: a process opens 30 files over about a second and a half without closing any
of them, standing in for a real leak.
import time
fds = []
for i in range(30):
fds.append(open(f"/tmp/leak_{i}.txt", "w"))
time.sleep(0.05)
time.sleep(5)
Sampling the FD count twice, two seconds apart, while this runs:
--- snapshot 1 ---
22
--- snapshot 2 (after 2s) ---
33
(the exact counts will vary run to run by a file or two depending on scheduling, the upward trend across
samples is the reproducible signal, not the precise numbers). Resolving the targets shows the leak clearly:
/proc/<pid>/fd/5 -> /tmp/leak_2.txt
/proc/<pid>/fd/6 -> /tmp/leak_3.txt
...
and lsof -p <pid> cross-checks the same file handles by name, confirming they are ordinary open files that
were never closed, not, for example, sockets still legitimately in use.
Trade-offs and pitfalls
A raw FD count can't distinguish a genuine leak from a busy process that legitimately holds many
connections open at once, such as a connection-pooling server; the readlink-and-aggregate step is what
turns "the count is high" into "these 400 descriptors are all sockets to the same peer that should plausibly
have been closed by now", the actual actionable signal. Also, /proc/<pid>/fd only shows a complete picture
when you're reading it as root or as the process's own owning user, a monitoring agent running under a
different, unprivileged account will silently undercount, which is easy to miss when you're comparing
numbers across a fleet running under different service accounts.
You attached a new block device /dev/sdb to a Linux VM. Provide a step-by-step command sequence to: create a single partition, format it as ext4, mount it at /data, set ownership to user 'app' and group 'app', and add a persistent /etc/fstab entry using the partition UUID. Explain each command used and how to verify everything is correct.
Sample Answer
Direct answer
Partition the new device, format the partition (not the raw disk device) with a filesystem, mount it, set ownership, then make the mount survive a reboot by referencing the partition's UUID (universally unique identifier, a stable label baked into the filesystem itself) in /etc/fstab rather than the device name, because /dev/sdb can become /dev/sdc on the next boot depending on device enumeration order, while the UUID never changes.
Step by step
- Confirm the device is what you think it is before touching it:
lsblkandsudo fdisk -l /dev/sdb, so you do not partition the wrong disk. - Create a partition table and a single partition:
parted -s /dev/sdb mklabel gpt mkpart primary ext4 1MiB 100%. GPT (GUID Partition Table) is the current default over the legacy MBR (Master Boot Record) scheme; starting at1MiBrather than sector 0 leaves room for GPT's own metadata and keeps the partition aligned to modern 4K-sector and SSD erase-block boundaries, avoiding a read-modify-write performance penalty from misalignment. - Let the kernel see the new partition:
partprobe /dev/sdb(re-reads the partition table without a reboot); the new node appears as/dev/sdb1. - Format it:
mkfs.ext4 /dev/sdb1. Format the partition, never the whole disk device (/dev/sdb), or you lose the partition table structure and get a filesystem with no partition boundary at all, which breaks the moment you want a second partition later. - Mount it:
mkdir -p /data; mount /dev/sdb1 /data. - Set ownership:
chown app:app /data(after first confirming both theappuser andappgroup already exist; create them withuseradd/groupaddif not). - Make it persistent, referencing the UUID rather than the device name: get the UUID with
blkid -s UUID -o value /dev/sdb1, then add a line to/etc/fstab:UUID=<uuid> /data ext4 defaults 0 2. The last two fields are thedumpflag (0, skip indumpbackups) and thefsckpass order (2, checked after the root filesystem which is always 1). - Verify before trusting it:
mount -a(re-readsfstaband mounts anything not already mounted, the safest way to test a new fstab line without rebooting, since a broken entry here can otherwise leave the system unable to boot cleanly), thenmount | grep /data,df -h /data, andls -ld /datato confirm ownership landed correctly.
Worked example (executed end to end on a loopback block device standing in for /dev/sdb)
LOOPDEV=$(losetup --find --show /tmp/fakedisk.img) # atomic find-and-attach, avoids a race with any other process also allocating a loop device
parted -s "$LOOPDEV" mklabel gpt mkpart primary ext4 1MiB 100%
kpartx -av "$LOOPDEV" # creates the partition device node; a real /dev/sdb would get /dev/sdb1 directly via the kernel + udev, this loopback sandbox needs kpartx to do the equivalent
PART="/dev/mapper/$(basename $LOOPDEV)p1"
mkfs.ext4 -q -F "$PART"
mkdir -p /data
groupadd app; useradd -M -N -g app app
mount "$PART" /data
chown app:app /data
UUID=$(blkid -s UUID -o value "$PART")
echo "UUID=$UUID /data ext4 defaults 0 2"
Real captured output confirmed the whole chain worked:
fstab entry: UUID=bb30b273-9fc3-41ba-8cbb-55b00328018e /data ext4 defaults 0 2
/dev/mapper/loop4p1 on /data type ext4 (rw,relatime)
Filesystem Size Used Avail Use% Mounted on
/dev/mapper/loop4p1 55M 24K 51M 1% /data
kpartx (which builds device-mapper nodes for partitions instead of relying on the kernel to auto create /dev/sdb1 style nodes) is a sandbox specific substitute here because this environment has no udev running; on a real VM or bare metal host, partprobe plus the kernel's own partition scanning gives you /dev/sdb1 directly with no extra tool needed, but every other command (parted, mkfs.ext4, mount, chown, blkid) is exactly what you would run against a real disk.
An alternate worked example: numeric UID/GID and extra mount options
The base example above owns the mount with a named user and group and uses defaults for mount options; a common real variant swaps both:
mount -o noatime,nodev "$PART" /data
chown 2000:2000 /data
echo "UUID=$UUID /data ext4 noatime,nodev 0 2"
chown 2000:2000 sets ownership by numeric UID/GID directly rather than by name, useful when /data needs to be owned by an identity that does not (yet, or ever) have a corresponding /etc/passwd entry on this particular host, for example a UID that only has meaning inside a container image mounted from this path, or a fleet where the owning account is provisioned slightly out of order relative to the disk. noatime skips updating each file's last-accessed timestamp on every read, a small but real reduction in write traffic for a data volume where nothing actually consults access time; nodev refuses to honor any device special files on this filesystem, a defense in depth measure appropriate for a data volume that should only ever hold regular application files, never a crafted device node smuggled in through some other channel. Both mount options belong in the fstab line itself, not just the interactive mount invocation, or they silently revert to defaults on the next boot.
Trade-offs and pitfalls
The most common real mistake is formatting /dev/sdb instead of /dev/sdb1: it appears to work (the raw disk device can hold a filesystem directly) but throws away the partition table, so there is no room to add a second partition later without destroying the first, and some tools behave inconsistently against a partition-less disk. Second, using the device name (/dev/sdb1) instead of the UUID in fstab works fine until a second disk is added or removed and Linux's device enumeration order shifts, silently mounting the wrong disk at /data on the next boot with no error at all, just wrong data where you expected a working application. Third, always test a new fstab line with mount -a before rebooting: a syntax error in fstab can otherwise leave the system stuck at an emergency shell on the next boot, which is a much worse time to discover the typo.
Audit for setuid and setgid programs in your infrastructure. Provide a command to find them and describe steps to minimize risk (e.g., removal, replacing with capabilities, using sudo wrappers). Also describe how to test that removing a setuid binary does not break critical functionality.
Sample Answer
Direct answer
Find every setuid and setgid binary with a single find command, then for each one ask whether it
genuinely needs to run with another user or group's privileges or whether that's a historical accident, and
prefer removing the privilege-escalation mechanism entirely, via Linux capabilities (a narrower, per-binary
grant of just the one specific kernel privilege actually needed) rather than leaving a broad setuid-root
binary in place because "it's always been there".
Structured elaboration
Finding them: find / -xdev -type f \( -perm -4000 -o -perm -2000 \) -exec ls -la {} \; (permission bit
4000 is the setuid bit, meaning the binary runs with the FILE OWNER's privileges rather than the invoking
user's, most dangerous when the owner is root; 2000 is the setgid equivalent for the group). -xdev stays
within one filesystem so the scan doesn't wander into a mounted network share. Run this against a known-good
baseline image and diff future scans against it, the actionable signal is usually "what setuid binary
appeared that wasn't in the base image", not re-auditing the same handful of standard binaries (passwd,
sudo, mount) every time.
Minimizing risk, in order of preference:
- Remove it entirely if the functionality isn't used at all, the least privileged code running is always
the safest state. - Replace the privilege mechanism with a Linux capability: instead of a binary being setuid-root (full root
for its entire runtime), grant it just the one specific operation it needs, for examplesetcap cap_net_bind_service=+ep /usr/bin/myserverlets a process bind to a privileged port (below 1024) without
being setuid-root at all, dramatically narrowing what a vulnerability in that binary could actually do. - Replace ad-hoc setuid scripts or wrappers with
sudorules scoped to the exact command and arguments
needed, centralizing the grant in one auditable, loggable place (everysudoinvocation is logged by
default) instead of a standing setuid bit that grants privilege silently on every invocation with no
audit trail. - Where you genuinely cannot remove or replace it (some vendor binaries ship setuid-root by design), at
minimum restrict who can even execute it via filesystem permissions or group membership, and track it
explicitly in the baseline diff so any accidental regression (it becoming world-executable) is caught.
Testing that removal doesn't break critical functionality:
- Strip the privilege on a single non-production canary first, not fleet-wide, this is fundamentally a "did
anything actually depend on this" question best answered incrementally. - Before removing, build a list of actual callers: an auditd watch rule on the binary's path
(-a always,exit -F path=<binary> -F perm=x -k setuid_audit),strace/ltraceon a representative
workload, or grepping scripts, cron entries, and application code for direct invocations. - After changing it on the canary, run the full relevant test suite, and leave monitoring in place (the same
auditd watch) for a full realistic usage cycle, covering weekly or monthly jobs, not just daily traffic,
before declaring it safe, an infrequent-but-critical caller (a monthly batch job, an annual certificate
renewal) is exactly what a short canary window misses. - Roll out gradually with an easy revert path (the removed binary or capability set kept ready to restore)
rather than a single fleet-wide change.
Worked example
A security audit finds /usr/bin/mount and /usr/bin/umount are setuid-root, standard and expected, since
mounting filesystems is inherently privileged, but also finds a home-grown /usr/local/bin/backup-agent is
setuid-root, absent from the base image, added ad hoc by a previous engineer so a cron job running as an
unprivileged user could read files owned by other users during backups. Tracing a real backup run confirms
the ONLY privileged operation the binary actually performs is bypassing file read permission checks, so the
fix is setcap cap_dac_read_search=+ep /usr/local/bin/backup-agent, followed by removing the setuid bit
entirely and validating a full backup cycle succeeds identically on a canary host before fleet rollout.
Trade-offs and pitfalls
Capabilities are a real security improvement but not a magic fix, a capability like CAP_SYS_ADMIN (a
notoriously broad, catch-all capability that in practice grants nearly as much power as full root for many
purposes) can be almost as dangerous as setuid-root if chosen too broadly, so the audit must name the
SPECIFIC capability needed, not just swap "setuid" for "some capability" reflexively. sudo wrappers shift
privilege to invocation time and rely on the sudoers rule being scoped tightly, an overly broad NOPASSWD: ALL entry recreates the exact same risk as a setuid-root binary, just relocated into a config file instead
of a permission bit.
Demonstrate how to use journalctl to: 1) show logs for the previous boot, 2) follow logs in real-time for the unit nginx.service, and 3) filter messages by priority and timestamp. Explain the difference between persistent and volatile journals and how to enable persistent journaling.
Sample Answer
Direct answer
journalctl is the query tool for the systemd journal (systemd-journald, the logging service that replaced plain text /var/log files with an indexed, structured binary log on most current distributions). Use -b to select a boot, -f -u <unit> to follow one service's logs live, and -p/--since/--until to filter by priority and time. Whether that data survives a reboot depends entirely on whether persistent journaling is enabled, and on a fresh install of several distributions it is not.
The three asks
1. Logs for the previous boot. journalctl -b -1 shows the boot immediately before the current one (-b -2 the one before that, and so on); journalctl --list-boots shows every boot the journal actually has recorded, each with an index and a time range, which is the safer first step since -1 only works if persistent journaling was already on during that earlier boot.
2. Follow logs live for one unit. journalctl -u nginx.service -f: -u filters to a single systemd unit, -f behaves like tail -f, streaming new entries as they arrive. Add -n 50 to also show the last 50 existing lines before it starts following, since -f alone starts from "now" with no history.
3. Filter by priority and timestamp. journalctl -p err --since "2026-09-01 00:00:00" --until "2026-09-01 06:00:00": -p accepts either a numeric syslog priority (0 emerg through 7 debug) or its name (err, warning, crit, and so on), and by default means "this priority or more severe," so -p err includes crit, alert, and emerg too, not only exact matches. --since/--until accept both absolute timestamps and relative ones like --since "1 hour ago".
Persistent versus volatile journals
By default on many distributions the journal lives only in /run/log/journal, which is a tmpfs (RAM backed filesystem) and is wiped on every reboot: that is the "volatile" journal. A "persistent" journal lives in /var/log/journal on disk and survives reboots, which is what makes journalctl -b -1 actually useful days after the fact instead of only immediately after a crash.
To enable it: mkdir -p /etc/systemd/journald.conf.d, create a drop in with Storage=persistent under [Journal], then restart the journal service (systemctl restart systemd-journald). Journald also switches to persistent mode on its own the moment /var/log/journal exists, even without touching the config: mkdir -p /var/log/journal followed by systemd-tmpfiles --create --prefix /var/log/journal (the real systemd utility that applies tmpfiles.d-style directory and permission rules; there is no separate systemd-tmpfsutils binary) and a restart is enough, because journald detects the directory's existence and switches to persistent mode without a config change at all. The config drop in is for making that explicit and permanent regardless of whether the directory happens to exist. Confirm which mode is currently active with journalctl --disk-usage, which reports 0 or near it when everything is still volatile and about to disappear on reboot.
Worked example
# previous boot's logs
journalctl -b -1
# see what boots the journal actually has on disk
journalctl --list-boots
# follow nginx live, with 50 lines of history first
journalctl -u nginx.service -n 50 -f
# everything at error severity or worse in a specific window
journalctl -p err --since "2026-09-01 00:00:00" --until "2026-09-01 06:00:00"
# enable persistent journaling
mkdir -p /var/log/journal
systemd-tmpfiles --create --prefix /var/log/journal
systemctl restart systemd-journald
journalctl --disk-usage
I ran the journalctl --version and flag inventory (journalctl --help) against a real systemd 255 install to confirm the exact flag names above (-b, -u, -f, -p, -g, --since, --until, -n/--lines) rather than trusting memory, since a wrong flag name here is exactly the kind of small error that looks plausible and is not. This sandbox has no running systemd-journald (containers do not run systemd as PID 1, the very first process a Linux system starts at boot and normally responsible for bringing up and supervising every other process, here), so journalctl -k correctly reports "No journal files were found" rather than showing fabricated log lines: any example log content in an answer like this should be labeled illustrative, because inventing plausible looking denial or error messages as if captured would be worse than saying nothing.
Trade-offs and pitfalls
Forgetting to enable persistent journaling is the single most common mistake here: a host that only ever logs to the volatile, RAM backed journal loses everything the moment it reboots, including the exact evidence you need to diagnose why it rebooted. A second mistake is treating -p err as "only errors" and being confused when crit and emerg lines show up too; the priority filter is a floor of severity, not an exact match, by design. Persistent journaling does have a real cost worth naming: unbounded disk growth if you never set SystemMaxUse= in journald.conf, so enabling persistence should come with an explicit size cap, not just flipping the storage mode on and walking away.
Unlock Full Question Bank
Get access to all Linux System Administration interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.