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.
As the Systems Administrator, create a new user 'alice' with UID 1500, primary group 'developers', and home directory /home/alice. Set an initial password, configure password aging so it expires periodically, and demonstrate how to lock and unlock the account. Explain where password aging information is stored on the system and how you would inspect it for an existing user.
Sample Answer
Direct answer
useradd with explicit -u, -g, and -d flags creates the account with exactly the UID (user ID), primary group, and home directory specified rather than whatever the system would pick by default; chage manages password aging afterward, stored in /etc/shadow (not /etc/passwd, which holds the account's other fields but never the password aging policy); and locking an account is a distinct, reversible operation from deleting or disabling it, done by prefixing the password hash rather than removing it.
Creating the account
groupadd -g 2000 developers
useradd -u 1500 -g developers -m -d /home/alice -s /bin/bash alice
passwd alice
-u 1500: the explicit UID requested.-g developers: setsdevelopersas alice's primary group (must already exist, created above with a matching explicit GID for consistency across hosts if that matters to your environment, though the GID number itself was not specified in the requirement).-m: create the home directory if it does not already exist, populated from/etc/skel(the skeleton directory whose contents,.bashrcand similar default dotfiles, are copied into every new home directory).-d /home/alice: the explicit home directory path.-s /bin/bash: login shell.passwd alice: sets the initial password interactively.
Password aging
chage -M 90 -W 7 alice
-M 90: maximum 90 days between password changes, after which the password expires. -W 7: warn the user starting 7 days before that expiration. chage -l alice displays the current policy for an existing user, which is the command to reach for when inspecting rather than setting:
Last password change : Sep 24, 2026
Password expires : Dec 23, 2026
Password inactive : never
Account expires : never
Minimum number of days between password change : 0
Maximum number of days between password change : 90
Number of days of warning before password expires : 7
Where this is actually stored
Password aging fields live in /etc/shadow, one line per user, colon separated: username, the hashed password, and then the aging fields chage manages (last change date, minimum days, maximum days, warning days, inactivity period, and expiration date), all stored as integers, mostly counts of days since the Unix epoch. /etc/passwd holds the account's UID, GID, home directory, and shell, but never the password hash or aging policy on any current Linux system, which is exactly why /etc/shadow exists as a separate, more tightly permissioned file (root-only readable) in the first place.
Locking and unlocking
usermod -L alice
passwd -S alice
usermod -L (equivalent to passwd -l) prepends a ! to the password hash field in /etc/shadow, which makes the stored hash fail to match any input, blocking password authentication without touching the hash itself, meaning it can be reversed cleanly. passwd -S alice reports the current status compactly (L for locked, P for a usable password set, NP for no password set at all). Unlocking:
usermod -U alice
Worked example (executed)
groupadd -g 2000 developers
useradd -u 1500 -g developers -m -d /home/alice -s /bin/bash alice
id alice
chage -M 90 -W 7 alice
usermod -L alice
passwd -S alice
Real captured output:
uid=1500(alice) gid=2000(developers) groups=2000(developers)
alice L 2026-09-24 0 90 7 -1
L confirms locked status, and the fields after it (2026-09-24 0 90 7 -1) are exactly the last-change date, minimum, maximum, and warning days set above, plus an unset inactivity period (-1), read directly out of /etc/shadow by passwd -S, not a separate source of truth. Attempting usermod -U immediately afterward, before ever setting a real password with passwd, correctly refused with "unlocking the user's password would result in a passwordless account," a real safety check worth knowing about since it means unlock only works cleanly once an actual password hash exists to unlock back to.
Additional provisioning detail worth having ready
Beyond the base flow above: /etc/skel controls what a new home directory starts with, so a custom .bashrc or default config for new hires belongs there, not hand-copied per account. -G (capital, distinct from -g) adds supplementary group memberships beyond the primary group, for example useradd ... -G sudo,docker alice for a user who needs more than just her primary group's access. Forcing a password change at first login, common for a newly provisioned account whose initial password was set by an admin rather than chosen by the user: chage -d 0 alice, which sets the last-change date to the epoch, so the aging policy immediately considers the current password expired and prompts for a change on next login. To pair this provisioning flow with an automatic lockout after repeated bad login attempts (rather than only the manual usermod -L shown above), the same pam_faillock.so module used for account security policy elsewhere on the system can be configured with deny=3 in /etc/security/faillock.conf, so any account, alice's included, locks itself out after three consecutive failures without an administrator needing to intervene by hand each time.
Trade-offs and pitfalls
The most common mistake is locking an account with usermod -L and assuming that also blocks SSH key based login: it only disables password authentication, an account locked this way can still log in over SSH with a valid key if one is authorized, so a genuine "disable this account" action for a departing employee needs usermod -L plus either removing or invalidating their authorized_keys, and separately expiring the account itself (usermod -e 1 sets an account expiration date in the past, which does block all login methods, not just password). Second, chage -M alone with no -W warning gives a user zero notice before their password simply stops working, which reads as a mysterious lockout rather than an expected policy; always pair a maximum age with a reasonable warning window. Third, remember -g (primary group) and -G (supplementary groups) are genuinely different flags with different effects: confusing them either leaves a user without the intended primary group ownership on files they create, or fails to grant a supplementary group's access at all.
You are designing a multi-tenant server that runs user workloads as separate services. Using systemd, cgroups and Linux namespaces, design an isolation strategy that reduces risk of noisy neighbors while keeping management feasible. Discuss trade-offs for resource guarantees, security, and operational complexity.
Sample Answer
Direct answer
Recommendation: one systemd slice per tenant (tenant-<id>.slice), with each tenant's services
placed Slice=tenant-<id>.slice and resource limits (CPUQuota=, MemoryMax=, IOWeight=) set
on the slice rather than per-service, plus per-service PrivateTmp=yes,
NetworkNamespacePath=/PrivateNetwork=yes, and ProtectSystem=strict for namespace-level
isolation. This gets meaningful resource fairness and blast-radius containment from mechanisms
already built into systemd, without standing up a full container runtime, at the cost of weaker
isolation than actual containers or VMs for a genuinely adversarial multi-tenant workload.
Structured elaboration
cgroups: resource guarantees
A cgroup (control group) is the kernel mechanism that groups processes and enforces resource
limits and accounting on the group as a whole; systemd creates and manages one automatically per
unit and per slice. Nesting each tenant's services under their own slice means CPUQuota=,
MemoryMax=, and IOWeight= set on the slice apply to the tenant's combined workload, not just
one service, which is what actually prevents one tenant's burst from starving another's, the
"noisy neighbor" problem this design exists to solve.
Namespaces: isolation boundary
A namespace is the kernel mechanism that gives a process its own view of some global resource
(process IDs, network interfaces, mounts, hostname) instead of sharing the host's. Per tenant
service:
PrivateTmp=yes: separate/tmpand/var/tmpper service, so tenants cannot see or collide
on temp files.ProtectSystem=strict/ProtectHome=yes: mount namespace changes making most of the
filesystem read-only to the service, sharply reducing what a compromised tenant process can
tamper with.PrivateNetwork=yes(own network namespace, no interfaces except loopback unless explicitly
configured) orNetworkNamespacePath=(share a specific pre-created namespace) if tenants need
real network isolation from each other, not just from the host.DynamicUser=yes(a fresh, unprivileged UID/GID allocated per service invocation) avoids the
operational overhead of provisioning a real user account per tenant while still ensuring no two
tenants' services share a UID.NoNewPrivileges=yes: sets the kernel'sno_new_privsbit on the service's process, so it can
never gain more privileges than it started with for the rest of its life, nosetuid/setgid
binaries, no file capabilities, no escalating viasudo. It costs nothing for a service that
never legitimately needs to escalate, and closes off a whole class of privilege-escalation exploit
if the service is ever compromised.
graph TD
A[system.slice] --> B[tenant-a.slice]
A --> C[tenant-b.slice]
B --> B1[tenant-a-app.service]
B --> B2[tenant-a-worker.service]
C --> C1[tenant-b-app.service]
B1 -. private mount namespace + PrivateTmp .-> B1
B1 -. private net namespace via NetworkNamespacePath .-> B1
B --> BLIM[CPUQuota / MemoryMax / IOWeight on tenant-a.slice]
C --> CLIM[CPUQuota / MemoryMax / IOWeight on tenant-b.slice]
Worked example
Directives verified as syntactically valid against a live systemd 255 via systemd-analyze verify:
# tenant-a.slice
[Slice]
CPUQuota=200%
MemoryMax=4G
IOWeight=100
# tenant-a-app.service
[Service]
Slice=tenant-a.slice
DynamicUser=yes
PrivateTmp=yes
ProtectSystem=strict
NoNewPrivileges=yes
ExecStart=/opt/app/bin/worker
Every tenant-a service placed under Slice=tenant-a.slice is accounted and limited as one pool:
if tenant-a-app.service and tenant-a-worker.service together try to exceed CPUQuota=200%,
the kernel throttles the combined group, not just one of the two services individually, which is
the actual guarantee a tenant is being sold ("your workloads collectively get up to 2 cores," not
"each of your processes independently gets 2 cores").
Trade-offs and pitfalls
Resource guarantees: slice-level limits give fairness against other tenants but not
isolation from noisy processes within the same tenant's own slice; a tenant with two services
sharing one slice's quota can still starve each other, size limits at whichever granularity
actually needs the guarantee.
Security: namespaces plus DynamicUser/ProtectSystem meaningfully raise the bar against a
compromised tenant process reading another tenant's files or the host's, but they share the same
kernel; a kernel-level exploit (a namespace escape, a cgroup-accounting bug) affects every tenant
on the host simultaneously. This is a materially weaker boundary than separate VMs, appropriate
for cooperating internal tenants or a trusted-but-imperfect multi-tenant SaaS control plane, not
for running arbitrary untrusted third-party code.
Operational complexity: systemd slices and per-service hardening directives are configuration,
not new infrastructure, they are the cheapest option to operate (no container runtime, no
orchestrator) and the easiest to reason about with existing systemctl/journalctl tooling. That
simplicity is the actual trade-off being made against the stronger, more complex isolation a
container runtime or firecracker-style microVM per tenant would provide.
Recommendation, stated as a choice: for internal or semi-trusted tenants where operational
simplicity matters and workloads are already systemd-managed services, slices plus namespace
hardening is the right default; move to real containers or VMs the moment "adversarial tenant" or
"regulatory isolation requirement" enters the picture, since no amount of systemd configuration
changes that they share one kernel.
A Python worker should gracefully finish processing its current job when systemd stops it. How would you implement a SIGTERM handler in Python to allow graceful shutdown, ensure in-flight jobs complete or checkpoint, and have systemd wait for this completion? Provide a short code example using the signal module and explain systemd timeout configuration (TimeoutStopSec).
Sample Answer
Direct answer
Register a SIGTERM handler with Python's signal module that only flips a flag, never do real work inside
the handler itself, then have the main loop check that flag between (not during) units of work, and size
TimeoutStopSec, the stop-timeout setting in systemd (the Linux service manager that starts,
stops, and supervises the worker), to comfortably exceed the longest single job so systemd's own
SIGKILL backstop never fires before the worker finishes checkpointing.
Structured elaboration
Signal handlers in Python run asynchronously with respect to whatever bytecode the main thread was
executing, so only a very small set of operations are actually safe inside one; setting a plain flag is
safe and standard practice, anything heavier (closing connections, writing checkpoints) belongs in the main
loop, which checks the flag at a safe point between jobs. On the systemd side, TimeoutStopSec must exceed
the worst realistic job duration plus checkpoint time, and the unit (the systemd service's
configuration file, shown below) should leave KillMode at its default (control-group, meaning
systemd tracks the whole cgroup, the kernel's grouping of every process the service spawned, and
can signal all of them together) rather than none (which would stop that tracking, leaving any
children the worker spawned to be cleaned up on their own), so the normal
signal-then-timeout-then-SIGKILL escalation still acts as the real safety net if the worker ever
does get stuck.
For jobs that are NOT quick to finish (a long batch job rather than a short unit of work), waiting for the
current job to finish outright risks not finishing before the timeout at all; instead the job itself should
periodically check the same flag and checkpoint progress at safe boundaries, so a restart resumes rather
than starts over.
Worked example
#!/usr/bin/env python3
"""Graceful-shutdown worker: finishes or checkpoints in-flight work on SIGTERM."""
import signal
import sys
import time
shutdown_requested = False
def handle_sigterm(signum, frame):
global shutdown_requested
shutdown_requested = True # do the minimum possible here; no I/O, no allocation
def process_one_job(job_id: int) -> None:
print(f"job {job_id}: started", flush=True)
time.sleep(1) # stand-in for real work
print(f"job {job_id}: done", flush=True)
def main() -> int:
signal.signal(signal.SIGTERM, handle_sigterm)
job_id = 0
while not shutdown_requested:
job_id += 1
process_one_job(job_id)
if shutdown_requested:
print(f"SIGTERM received, checkpoint after job {job_id}, exiting cleanly", flush=True)
break
return 0
if __name__ == "__main__":
sys.exit(main())
Run and send SIGTERM about 1.5 seconds in (partway through the second job):
job 1: started
job 1: done
job 2: started
job 2: done
SIGTERM received, checkpoint after job 2, exiting cleanly
worker exit code: 0
For a job whose single unit of work is itself long-running, add an internal check-and-checkpoint point
rather than waiting for the whole job to finish:
def process_long_job(chunks):
for i, chunk in enumerate(chunks):
do_work(chunk)
if shutdown_requested:
save_checkpoint(resume_at=i + 1)
return
Matching systemd configuration:
[Service]
Type=simple
ExecStart=/usr/bin/python3 /opt/worker/worker.py
KillSignal=SIGTERM
TimeoutStopSec=45
(TimeoutStopSec=45 here assumes a worst-case job plus checkpoint time comfortably under 45 seconds; size
it to your actual longest job, not this example's 1-second stand-in.)
Trade-offs and pitfalls
A common bug is registering the handler only for SIGTERM and forgetting SIGINT, so local development with
Ctrl-C (an immediate KeyboardInterrupt) behaves completely differently from systemctl stop in
production; registering both to the same handler keeps local and production behavior consistent. Also,
catching SIGTERM but never actually exiting (looping indefinitely "waiting for a good moment") doesn't
avoid systemd's timeout, it still fires and SIGKILLs the process anyway, so the checkpoint-and-exit path
needs its own hard internal deadline, not an open-ended wait for a perfect stopping point.
Explain the structure of a systemd unit file. Write an example service unit for /opt/app/bin/myservice that runs as user appuser, restarts on failure with a 10s backoff, writes logs to journald, and declares a dependency on network-online.target. Explain each directive you include.
Sample Answer
Direct answer
A systemd unit file is an INI-style config split into named sections; a service unit typically
has [Unit] (metadata and dependency ordering), [Service] (how to run and supervise the
process), and [Install] (how systemctl enable wires it into a boot target).
# /etc/systemd/system/myservice.service
[Unit]
Description=My Service
After=network-online.target
Wants=network-online.target
StartLimitIntervalSec=60
StartLimitBurst=5
[Service]
Type=simple
User=appuser
ExecStart=/opt/app/bin/myservice
Restart=on-failure
RestartSec=10s
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target
Structured elaboration
[Unit]: what this unit is and what it needs to exist before it starts
Description=is free-text shown bysystemctl statusand in logs; purely documentation.After=network-online.targetorders this unit to start after the target is reached, it does
not by itself pull the target in as a dependency.Wants=network-online.targetis the dependency itself: a soft (non-fatal-if-it-fails)
requirement that the target be started too.After=andWants=are deliberately separate:
Wantssays "bring it in,"Aftersays "and wait for it first"; using onlyAfterwithout a
correspondingWants/Requireswould order correctly if the target happens to start for some
other reason, but would not actually pull it in.StartLimitIntervalSec=60/StartLimitBurst=5cap the restart loop: more than 5 (re)starts
within any 60 second window and systemd gives up, marking the unit failed with
start-limit-hitrather than restarting forever, this is what stops a genuinely broken binary
from spinning the CPU and flooding the journal indefinitely. These two belong in[Unit], not
[Service], even though they are entirely about restart behavior: putting
StartLimitIntervalSec=in[Service]is a common and easy mistake (it reads like a sibling of
Restart=/RestartSec=, which genuinely are[Service]keys) and systemd's own verifier
catches it (see the worked example below).
[Service]: how to run and supervise it
Type=simpletells systemd the process named inExecStartis the main process; systemd
considers the unit started as soon as it forks that process, with no separate readiness signal.User=appuserruns the process as a dedicated non-root user rather than root, standard
least-privilege practice for a service that does not need root.ExecStart=/opt/app/bin/myserviceis the actual command to run.Restart=on-failurerestarts the service automatically if it exits with a non-zero code or is
killed by a signal, but not on a cleanType=simpleexit code 0 or an explicitsystemctl stop.RestartSec=10sis the delay before each restart attempt, the "10s backoff" the question asks
for.StandardOutput=journal/StandardError=journalroute the process's stdout/stderr into the
systemd journal (this is actually the default on modern systemd and is written here for
explicitness), viewable withjournalctl -u myservice.
[Install]: how enable wires it up
WantedBy=multi-user.target means systemctl enable myservice creates a symlink so this unit
starts automatically once the system reaches the normal multi-user boot target; without an
[Install] section, systemctl enable has nothing to attach to and the unit would only ever
start when invoked manually or pulled in by another unit's dependency.
Worked example
Verified with systemd's own static checker on a live systemd 255 installation (Ubuntu 24.04). The
first version placed StartLimitIntervalSec= in [Service], which is where it is easy to reach
for since it reads like a sibling of Restart=/RestartSec=:
$ systemd-analyze verify /etc/systemd/system/myservice.service
/etc/systemd/system/myservice.service:12: Unknown key name 'StartLimitIntervalSec' in section 'Service', ignoring.
$ echo $?
0
The exit code is still 0 (this is a warning, not a parse failure), but the key is silently
dropped: the 60 second window never actually applies, so the restart-loop cap does not behave as
documented. Moving both StartLimitIntervalSec=60 and StartLimitBurst=5 into [Unit] (the unit
file shown above) verifies clean with no output at all:
$ systemd-analyze verify /etc/systemd/system/myservice.service
$ echo $?
0
A clean exit with genuinely no output means every directive parsed and every referenced target
(network-online.target, multi-user.target) resolved to a real unit name, this is the same
check systemctl daemon-reload performs before accepting a new or edited unit file. An exit code
of 0 alone is not sufficient proof the file is correct, since the misplaced-key case above also
exits 0; read the actual output, not just the exit status.
Trade-offs and pitfalls
Type=simpleassumes the started process does not fork into the background itself; a
double-forking daemon underType=simpleconfuses systemd about which process is actually the
service (useType=forkingwithPIDFile=for that class of program instead).Restart=on-failurealone, withoutStartLimitBurst/StartLimitIntervalSec, will restart a
crash-looping binary forever at a fixed 10 second cadence, burning CPU and filling the journal;
always pair a restart policy with a start limit.- Running as
User=appuserrequires that user to already exist and to have whatever file
permissions/opt/appneeds; a unit file referencing a user that was never created fails at
start time with a permission or "user not found" error, not atsystemd-analyze verifytime
(verify only checks unit-file syntax, not runtime preconditions like the user existing). After=on a target does not guarantee the service behind that target is actually ready to
accept work, only that the target was reached;network-online.targetspecifically waits for a
network management daemon to report connectivity, but a database or downstream dependency
reportingactiveis a different problem entirely, covered by an explicit readiness check
rather than unit ordering alone.StartLimitIntervalSec=/StartLimitBurst=belong in[Unit]; systemd 255 silently ignores
StartLimitIntervalSec=if it is left in[Service](verified above), withexit 0from
systemd-analyze verify, not a hard failure. Always read the verifier's actual output, not just
its exit code, and double check restart-limit placement specifically since it is the one
Restart-family key that does not live next toRestart=/RestartSec=.
A long-running daemon gradually increases resident memory until the OS OOM-kills it. Describe methods and tools you would use to determine whether the leak is in the application, a third-party library, or the kernel. Include steps with pmap, /proc/<pid>/smaps, mass heap profiling tools, valgrind or sampling profilers, and how to gather evidence safely on production.
Sample Answer
Direct answer
Separate confirming the trend from localizing the source, and escalate tooling gradually: start with
read-only, always-safe checks (/proc/<pid>/status, /proc/<pid>/smaps) to confirm genuine unbounded
growth and roughly localize it to application heap versus a shared library versus the kernel, then bring in
heavier, invasive tools like valgrind only in a reproduction environment, never attached live to the
production process you're actually trying to save.
Escalation, tier by tier
Tier 0, confirm the trend (always safe): /proc/<pid>/status for VmRSS (resident set size, the
process's actual physical memory in use) versus VmSize (virtual memory, including reserved-but-unused
regions) versus VmSwap, sampled over an hour or more, not a single snapshot, since RSS naturally grows to
a plateau in most healthy allocators and only genuine leaks keep climbing without bound. When the OOM killer
(out-of-memory killer, the kernel mechanism that selects and kills a process using an internal oom_score
when the system cannot reclaim any more memory) does fire, its dmesg/journalctl -k message includes the
victim's RSS at the moment of the kill, a free forensic snapshot you should always capture first.
Tier 1, localize kernel vs userspace vs a specific library (still read-only): /proc/<pid>/smaps (or the
faster smaps_rollup for an aggregate) breaks memory into individual mapped regions, heap, stack, each
shared library's mapping, anonymous memory, with Rss and Pss (proportional set size, memory shared
across processes counted proportionally) per region. Growth concentrated in [heap] or anonymous mappings
points at the application or its allocator; growth in one specific library's mapping points at that library.
slabtop//proc/slabinfo distinguishes a genuinely different problem, kernel-side object accumulation
(dentries, inodes, network buffers) under Slab, from your process's own RSS growth, since those need
entirely different fixes.
Tier 2, attribute growth to code (heavier, once "application heap" is confirmed): language-runtime-native
profilers first, since they're built to run safely in production: Python's tracemalloc (toggled at
runtime via a signal handler without a restart), a JVM's jcmd <pid> GC.class_histogram, or Go's built-in
pprof heap endpoint. Sampling profilers (perf record -g -p <pid>) attribute CPU or allocation call
stacks without instrumenting every allocation. valgrind (specifically its memcheck/massif tools) is
NOT safe to attach to a live production process, it re-executes the program under a slow instrumented
interpreter, often 10 to 50 times slower, so it belongs in a reproduction environment, replaying production
traffic against a canary instance, not on the incident host itself.
Tier 3, ambiguous kernel vs userspace: compare free's "available" trend against the sum of every
process's RSS; if available memory shrinks faster than any single process's RSS is growing, suspect the
kernel side (slab objects, pinned page cache, a kernel module leak), which needs /proc/meminfo's Slab,
SReclaimable, SUnreclaimable trend rather than any per-process tool.
Worked example
A long-running Python worker's RSS climbs from 200MiB to 4GiB over six hours before being OOM-killed.
dmesg shows oom-kill: ... Killed process 4821 (worker) total-vm:4300000kB, anon-rss:4100000kB. Hourly
smaps_rollup samples show [heap] and anonymous mappings climbing linearly while every shared library's
Rss stays flat, ruling out a library-level leak. Enabling tracemalloc on a canary instance via a runtime
signal-triggered dump of the top allocation sites by size points to a cache dictionary that is never
evicted, growing by one entry per unique request key it has ever seen. The fix bounds the cache with an
LRU (least-recently-used) eviction policy rather than letting it grow forever.
Trade-offs and pitfalls
Never reach for valgrind or a gdb attach on a production process as a first move, gdb freezes every
thread the instant you attach, and valgrind's overhead can itself trigger request timeouts, turning an
intermittent leak into an active outage you caused while investigating it. RSS that climbs then plateaus at
a stable, higher level is usually just an allocator warming its arena or cache, not a leak, only escalate
tooling once you've confirmed genuinely monotonic, unbounded growth over hours, not minutes, ruling out a
one-time warm-up.
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.