Users, groups and access control
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q1 You need to onboard 50 new developers onto a shared build server, each with their own account and SSH key. How do you do it?
Beginner
Situation read โ Bulk, repeatable user creation with consistent groups and key-only login.
What I'd do โ
- Get a CSV of
username,pubkeyfrom the ticket. - Create a
developersgroup once:sudo groupadd developers. - Loop over the file:
while IFS=, read -r u key; do
sudo useradd -m -s /bin/bash -G developers "$u"
sudo install -d -m 700 -o "$u" -g "$u" /home/$u/.ssh
echo "$key" | sudo tee /home/$u/.ssh/authorized_keys >/dev/null
sudo chown "$u:$u" /home/$u/.ssh/authorized_keys
sudo chmod 600 /home/$u/.ssh/authorized_keys
done < users.csv- Lock passwords (
passwd -l) since login is key-only, and verify withgetent group developers.
Why โ Scripted creation avoids typos and wrong permissions that break key auth.
Interview tip โ Say that beyond a handful of servers you would do this with Ansible's user and authorized_key modules, or central identity (LDAP/SSSD).
Q2 Three teams share one server and each needs a project directory only its members can write to, with new files staying group-owned. How do you set it up?
Beginner
Situation read โ Classic group-shared directory with the setgid bit.
What I'd do โ
- Create groups
team-a,team-b,team-cand add members withusermod -aG. - Create directories and set ownership:
sudo mkdir -p /srv/projects/{team-a,team-b,team-c}
for t in team-a team-b team-c; do
sudo chown root:$t /srv/projects/$t
sudo chmod 2770 /srv/projects/$t
done- Set
umask 002for those users (in/etc/profile.d/) so files are group-writable.
Why โ The setgid bit (2 in 2770) makes new files inherit the directory's group instead of the creator's primary group.
Interview tip โ Mention that users must log out and back in for new group membership to apply.
Q3 A junior engineer needs to restart nginx but must not get full root. How do you grant that?
Beginner
Situation read โ Least privilege through a narrow sudo rule.
What I'd do โ
- Create a drop-in with
sudo visudo -f /etc/sudoers.d/nginx-ops:
%nginx-ops ALL=(root) NOPASSWD: /usr/bin/systemctl restart nginx, /usr/bin/systemctl reload nginx, /usr/bin/systemctl status nginx- Add the user to
nginx-ops. - Test:
sudo -l -U aliceand have them runsudo systemctl reload nginx.
Why โ Full paths and exact arguments stop the rule from being used to run arbitrary commands. visudo validates syntax so you can't lock yourself out of sudo.
Interview tip โ Point out that granting sudo vim or sudo less is effectively root because they can spawn a shell.
Q4 An engineer leaves the company today. What do you do with their Linux account on 30 servers?
Beginner
Situation read โ Revoke access immediately but keep data and audit trail.
What I'd do โ
- Lock the account and kill sessions:
sudo usermod -L -e 1 bob # lock password, expire account
sudo pkill -KILL -u bob
sudo mv /home/bob/.ssh/authorized_keys /root/offboard-bob.keys- Search for their keys in other accounts:
grep -r "bob@" /home/*/.ssh/authorized_keys /root/.ssh/authorized_keys. - Check
crontab -l -u boband running services owned by them. - After the retention period, archive the home dir and
userdel -r bob.
Why โ Locking first is reversible; deleting right away can break jobs or ownership that nobody knew depended on that user.
Interview tip โ Say you do this from a central tool (Ansible, IdP/LDAP disable) so no server is missed.
Q5 A service account for a backup tool must exist on every server but nobody should be able to log in as it. How do you create it?
Beginner
Situation read โ System user with no shell, no password, no home clutter.
What I'd do โ
sudo useradd --system --no-create-home --shell /usr/sbin/nologin backupsvc
sudo passwd -l backupsvc
getent passwd backupsvcGive it ownership only of what it needs, for example /var/backups/app.
Why โ --system uses a low UID range and no aging; nologin blocks interactive shells while still allowing the process to run as that user.
Interview tip โ Mention systemd DynamicUser=yes as an alternative when the service needs no persistent identity.
Q6 Your security team requires passwords to expire every 90 days for human users only. How do you implement it?
Beginner
Situation read โ Password aging policy, applied to existing and future users.
What I'd do โ
- For new users, set defaults in
/etc/login.defs:PASS_MAX_DAYS 90,PASS_MIN_DAYS 1,PASS_WARN_AGE 14. - For existing humans (UID >= 1000):
awk -F: '$3>=1000 && $3<65534 {print $1}' /etc/passwd | xargs -I{} sudo chage -M 90 -m 1 -W 14 {}
chage -l alice- Exclude service accounts and key-only accounts where expiry would just break automation.
Why โ login.defs only affects accounts created afterwards; chage fixes the existing ones.
Interview tip โ Note that modern guidance (NIST 800-63B) prefers strong passwords plus MFA over forced rotation, but you implement what policy says.
Q7 Two developers need read access to /var/log/app/ without being added to the adm or root group. How?
Intermediate
/var/log/app/ without being added to the adm or root group. How?Situation read โ Fine-grained access beyond owner/group/other: use ACLs.
What I'd do โ
sudo setfacl -R -m u:alice:rX,u:bob:rX /var/log/app
sudo setfacl -d -m u:alice:rX,u:bob:rX /var/log/app # default ACL for new files
getfacl /var/log/appCheck that logrotate does not recreate files with modes that drop the ACL mask (create 0640 keeps the mask usable).
Why โ ACLs grant per-user rights without changing the file's owner or group, and default ACLs apply to files created later.
Interview tip โ Mention the + in ls -l output as the sign that an ACL exists.
Q8 You have 200 servers and user accounts are drifting between them. How do you centralise identity?
Intermediate
Situation read โ Local /etc/passwd management does not scale; move to a directory service.
What I'd do โ
- Pick a source of truth: FreeIPA, Active Directory, or an LDAP behind your IdP.
- Join servers with SSSD (
realm joinfor AD/IPA) and usesssdin/etc/nsswitch.confforpasswdandgroup. - Store SSH public keys in the directory and serve them via
AuthorizedKeysCommand /usr/bin/sss_ssh_authorizedkeys. - Control who may log in per host group with HBAC rules or
simple_allow_groups. - Keep one local break-glass admin per server.
Why โ One place to add, remove and audit users; offboarding becomes a single disable.
Interview tip โ Mention SSSD caching so logins still work if the directory is briefly unreachable.
Q9 A contractor needs SFTP access to upload files to one directory and nothing else. How do you set that up?
Intermediate
Situation read โ Chrooted SFTP-only account.
What I'd do โ
sudo useradd -s /usr/sbin/nologin -G sftponly contractor1- Prepare the chroot (must be root-owned and not group-writable):
sudo mkdir -p /sftp/contractor1/upload
sudo chown root:root /sftp/contractor1 && sudo chmod 755 /sftp/contractor1
sudo chown contractor1:contractor1 /sftp/contractor1/upload- In
/etc/ssh/sshd_config:
Match Group sftponly
ChrootDirectory /sftp/%u
ForceCommand internal-sftp
AllowTcpForwarding no
X11Forwarding nosshd -t && systemctl reload sshd, then test withsftp.
Why โ internal-sftp needs no binaries inside the chroot, and ForceCommand blocks shell access.
Interview tip โ The most common failure is chroot ownership; sshd refuses if the chroot path is writable by the user.
Q10 Auditors want to know exactly which commands admins ran with sudo last month. How do you provide that going forward?
Intermediate
Situation read โ Command-level audit trail that survives on-box tampering.
What I'd do โ
- Enable sudo logging in
/etc/sudoers.d/logging:
Defaults logfile=/var/log/sudo.log
Defaults log_input, log_output
Defaults iolog_dir=/var/log/sudo-io/%{user}- Add auditd rules for execve by admins:
-a always,exit -F arch=b64 -S execve -F euid=0 -F auid>=1000 -k root-cmds. - Ship
/var/log/secureorauth.log, sudo logs and audit logs to a central SIEM. - Answer queries with
ausearch -k root-cmds --start this-monthor in the SIEM.
Why โ Local logs can be wiped by root; forwarding them off-box keeps them trustworthy.
Interview tip โ sudoreplay can replay recorded sessions when log_output is on.
Q11 Developers keep running sudo su - and doing everything as root. How do you change that without blocking their work?
Intermediate
sudo su - and doing everything as root. How do you change that without blocking their work?Situation read โ Shared root sessions destroy accountability; replace with per-command sudo.
What I'd do โ
- List what they actually need (restart services, read logs, deploy) from sudo logs.
- Write
Cmnd_Aliasrules for those commands in/etc/sudoers.d/. - Remove the broad
ALLrule, and explicitly deny shells:!/bin/su, !/usr/bin/su, !/bin/bash(as defence, knowing deny lists are bypassable). - Give the team
journalctlaccess via thesystemd-journalgroup instead of sudo. - Communicate, roll out to one server, then the fleet.
Why โ Every action gets tied to a named user in the logs.
Interview tip โ Admit deny lists in sudo are weak; allow lists are the real control.
Q12 A developer reports that their newly added group membership is not working even though id alice shows it. What do you explain and do?
Beginner
id alice shows it. What do you explain and do?Situation read โ Group lists are loaded at login, so existing sessions don't see the change.
What I'd do โ
- Confirm:
id alice(reads the database) vsidin their session (current process). - Have them log out and back in, or run
newgrp groupnamefor a subshell. - For services running as that user, restart the service.
Why โ The kernel stores supplementary groups in the process credentials when the session starts.
Interview tip โ This is also why systemctl restart is needed after adding a service user to a group.
Q13 You must give the monitoring agent permission to read every process's /proc/<pid>/ info and bind to port 162 without running as root. How?
Advanced
/proc/<pid>/ info and bind to port 162 without running as root. How?Situation read โ Use Linux capabilities instead of root.
What I'd do โ
- In the systemd unit:
[Service]
User=monagent
AmbientCapabilities=CAP_NET_BIND_SERVICE CAP_SYS_PTRACE CAP_DAC_READ_SEARCH
CapabilityBoundingSet=CAP_NET_BIND_SERVICE CAP_SYS_PTRACE CAP_DAC_READ_SEARCH
NoNewPrivileges=yessystemctl daemon-reload && systemctl restart monagent.- Verify:
grep Cap /proc/$(pidof monagent)/status | xargsand decode withcapsh --decode=....
Why โ Capabilities split root into small privileges; the bounding set guarantees the process can never gain more.
Interview tip โ Prefer AmbientCapabilities in systemd over setcap on the binary, because file caps get lost on package upgrades.
Q14 You need a shared admin account for an emergency, but auditors forbid shared passwords. What do you set up?
Advanced
Situation read โ Break-glass access that is controlled and audited.
What I'd do โ
- Create one local
breakglassuser per server with a long random password stored in a vault (HashiCorp Vault, 1Password) that requires approval to check out. - Rotate the password automatically after every checkout.
- Disable its SSH key login; allow console or a dedicated bastion only.
- Alert on any login: an auditd rule or a PAM
pam_exechook that notifies the SIEM. - Test it quarterly.
Why โ You still have a way in when LDAP/SSO is down, while every use is traceable to a person.
Interview tip โ Mention that SSH certificates with short TTLs from Vault are a modern alternative.
Q15 A user's home directory is on a server with quotas, and one person filled the shared /home. How do you stop this happening again?
Intermediate
/home. How do you stop this happening again?Situation read โ Enforce per-user disk quotas.
What I'd do โ
- For XFS, mount with
uquotain/etc/fstab(/dev/vg0/home /home xfs defaults,uquota 0 0) and remount/reboot. - Set limits:
sudo xfs_quota -x -c 'limit bsoft=9g bhard=10g alice' /home
sudo xfs_quota -x -c 'report -h' /home- For ext4 use
usrquota, thenquotacheck -cum /home,quotaon /home,setquota -u alice 9G 10G 0 0 /home.
Why โ Hard limits stop a single user from starving everyone; soft limits give a warning first.
Interview tip โ XFS quota must be enabled at mount time; remount is not enough for the root filesystem.
Q16 How would you make sure a user can only log in during business hours from the office network?
Intermediate
Situation read โ PAM access controls by time and origin.
What I'd do โ
- Time: add
account required pam_time.soto/etc/pam.d/sshd, and in/etc/security/time.conf:
sshd;*;alice;Wk0900-1800- Origin: add
account required pam_access.soand in/etc/security/access.conf:
+ : alice : 10.20.0.0/16
- : alice : ALL- Back it up with
Match User alice+AllowUsers [email protected].*in sshd for defence in depth.
Why โ PAM account modules decide whether an authenticated user may log in.
Interview tip โ Always test PAM changes with a second root session open.
Q17 A team wants a shared Git deploy user on the server, but you need to know who deployed. How do you design it?
Intermediate
Situation read โ Shared account, individual identity.
What I'd do โ
- Put each person's key in
~deploy/.ssh/authorized_keyswith a forced command and env tag:
command="/usr/local/bin/deploy-wrapper alice",no-port-forwarding,no-pty ssh-ed25519 AAAA... alice- The wrapper logs
aliceplus$SSH_ORIGINAL_COMMANDto syslog and runs only allowed actions. - sshd also logs the key fingerprint per login (
LogLevel VERBOSE).
Why โ You keep a single deploy account but every action is tied to a key owner.
Interview tip โ Better long-term answer: deploy from CI with a dedicated identity, not humans over SSH.
Q18 The security team wants all interactive shell sessions to time out after 15 minutes idle. How?
Beginner
Situation read โ Idle shell and SSH timeouts.
What I'd do โ
- Shell: create
/etc/profile.d/tmout.sh:
TMOUT=900
readonly TMOUT
export TMOUT- SSH: in
sshd_configsetClientAliveInterval 300andClientAliveCountMax 3, then reload.
Why โ TMOUT closes idle bash shells; readonly stops users from unsetting it. Client-alive settings drop dead SSH connections.
Interview tip โ Note ClientAlive* detects unresponsive clients, not idle users; TMOUT handles idleness.
Q19 You suspect someone added an extra UID 0 account. How do you check and respond?
Intermediate
Situation read โ Hidden root accounts are a classic backdoor.
What I'd do โ
awk -F: '$3==0 {print $1}' /etc/passwd
awk -F: '$2=="" {print $1}' /etc/shadow # empty passwords
ls -l /etc/passwd /etc/shadow; rpm -V setup 2>/dev/null || debsums -c 2>/dev/null
lastlog | head; last -F | headIf anything besides root shows UID 0, treat the host as compromised: isolate, preserve evidence, and investigate rather than just deleting the line.
Why โ An attacker with root can add accounts; removing the symptom leaves the way they got in open.
Interview tip โ Mention monitoring /etc/passwd with auditd (-w /etc/passwd -p wa -k identity) or file integrity tools like AIDE.
Q20 A developer accidentally ran chmod -R 777 /var/www. How do you restore sane permissions?
Beginner
chmod -R 777 /var/www. How do you restore sane permissions?Situation read โ Reset directories and files separately.
What I'd do โ
sudo chown -R www-data:www-data /var/www
sudo find /var/www -type d -exec chmod 755 {} +
sudo find /var/www -type f -exec chmod 644 {} +Then re-apply exceptions such as writable upload dirs (775) or executable scripts, and check config files holding secrets (640).
Why โ Directories need x to be entered; files usually should not be executable.
Interview tip โ If the files came from a package, rpm --setperms pkg or reinstalling restores the original modes.
Q21 You need to rename a user from jsmith to john.smith on a server without breaking their files. How?
Intermediate
jsmith to john.smith on a server without breaking their files. How?Situation read โ Change login name and home path, keep UID.
What I'd do โ
- Make sure they are logged out:
pkill -u jsmith. - Run:
sudo usermod -l john.smith -d /home/john.smith -m jsmith
sudo groupmod -n john.smith jsmith- Check crontabs (
/var/spool/cron/jsmithis renamed by some distros, not all), sudoers entries and any config referencing the old name.
Why โ Files are owned by UID, not name, so keeping the UID means ownership stays correct.
Interview tip โ Mention that NFS-shared homes need the same change on every host or the UID mapping breaks.
Q22 A new compliance rule says no user may reuse their last five passwords and passwords need 14+ characters. How do you enforce it?
Intermediate
Situation read โ PAM password quality and history.
What I'd do โ
- In
/etc/security/pwquality.conf:minlen = 14,minclass = 3,dictcheck = 1. - For history, use
pam_pwhistory. On RHEL 9 use authselect:authselect enable-feature with-pwhistoryand setremember = 5in/etc/security/pwhistory.conf. - On Debian/Ubuntu add to
/etc/pam.d/common-password:password required pam_pwhistory.so remember=5 use_authtokbeforepam_unix. - Test with
passwdas a normal user.
Why โ pwquality checks strength at change time; pwhistory stores previous hashes in /etc/security/opasswd.
Interview tip โ On RHEL, editing /etc/pam.d/system-auth directly gets overwritten by authselect.
Q23 You have to give a CI runner user the right to run Docker but you are worried about security. What do you do?
Advanced
Situation read โ Membership in the docker group is root-equivalent.
What I'd do โ
- Prefer rootless Docker or Podman for the runner user:
dockerd-rootless-setuptool.sh install. - If rootful Docker is required, run the runner on a dedicated, disposable VM that has no other secrets.
- Never mount
/var/run/docker.sockinto untrusted job containers. - Consider building with BuildKit rootless or Kaniko/Buildah.
Why โ Anyone in docker can run docker run -v /:/host --privileged and own the host.
Interview tip โ Say clearly "docker group = root", interviewers look for that.
Q24 A team needs some files to be impossible to delete even by root accidentally, such as a critical config. How?
Advanced
Situation read โ Extended file attributes.
What I'd do โ
sudo chattr +i /etc/resolv.conf # immutable
sudo chattr +a /var/log/audit.trail # append-only
lsattr /etc/resolv.confRemove with chattr -i before planned changes.
Why โ The immutable flag blocks write, rename, delete and link even for root, until someone removes it with CAP_LINUX_IMMUTABLE.
Interview tip โ It protects against mistakes and tools rewriting files, not against an attacker with root, who can just run chattr -i.
Q25 How would you design user and access management for a 500-server fleet with no shared passwords and fast offboarding?
Advanced
Situation read โ Scale, auditability and instant revocation.
What I'd do โ
- Identity from the IdP (Okta/Entra) synced to FreeIPA/AD or used directly by an access proxy.
- SSH with short-lived certificates (Vault SSH CA, Teleport, or
step-ca): servers trustTrustedUserCAKeys, certs last 8 hours. - Role-based principals mapped to sudo rules (
AuthorizedPrincipalsFile). - All access through a bastion or proxy with session recording.
- Only one break-glass local account, vaulted.
Why โ Disable the user in the IdP and they lose access everywhere within hours, with no key cleanup.
Interview tip โ Contrast it with authorized_keys sprawl, which is the failure mode most companies are trying to escape.
Storage, disks and filesystems
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q26 You get paged at 3 AM: the root filesystem on a production server is at 98% and climbing. Walk through your response.
Beginner
Situation read โ Stop the bleeding first, then find the root cause in daylight.
What I'd do โ
- Find what is growing:
df -h /
sudo du -xh --max-depth=1 / 2>/dev/null | sort -h | tail
sudo du -xh --max-depth=1 /var/log | sort -h | tail- Quick safe wins:
journalctl --vacuum-size=500M, remove rotated logs (*.gz),apt-get clean/dnf clean all. - If a single log is huge and still open, truncate it rather than delete:
sudo truncate -s 0 /var/log/app/app.log. - Once stable, fix the cause (missing logrotate, debug logging left on, runaway dump files).
Why โ du -x stays on one filesystem so mounted volumes don't confuse you, and truncating keeps the app's file handle valid.
Interview tip โ Say "I buy time first, then write a ticket for the root cause and an alert at 80%."
Q27 A new 200 GB EBS volume is attached to an EC2 instance. How do you make it usable and persistent across reboots?
Beginner
Situation read โ Partition (optional), format, mount, fstab by UUID.
What I'd do โ
lsblk # find it, e.g. /dev/nvme1n1
sudo mkfs.xfs /dev/nvme1n1
sudo mkdir -p /data
sudo blkid /dev/nvme1n1 # copy the UUID
echo 'UUID=<uuid> /data xfs defaults,nofail 0 2' | sudo tee -a /etc/fstab
sudo mount -a && df -h /dataWhy โ Device names like /dev/nvme1n1 can change between boots; UUIDs don't. nofail keeps the instance booting if the volume is detached.
Interview tip โ Always run mount -a after editing fstab, before rebooting, to catch mistakes.
Q28 The /var LVM logical volume is nearly full and there is free space in the volume group. How do you grow it online?
Beginner
/var LVM logical volume is nearly full and there is free space in the volume group. How do you grow it online?Situation read โ LVM lets you grow without downtime.
What I'd do โ
sudo vgs # confirm VFree
sudo lvextend -r -L +20G /dev/vg0/var # -r resizes the filesystem too
df -h /varIf you prefer separate steps: xfs_growfs /var for XFS, resize2fs /dev/vg0/var for ext4.
Why โ Both XFS and ext4 can grow while mounted.
Interview tip โ Mention that XFS can't shrink, so you grow in sensible increments rather than all at once.
Q29 The volume group has no free space. You've been given a new disk. How do you add it to grow /var?
Intermediate
/var?Situation read โ Add a physical volume to the VG, then extend.
What I'd do โ
lsblk # new disk /dev/sdc
sudo pvcreate /dev/sdc
sudo vgextend vg0 /dev/sdc
sudo lvextend -r -l +100%FREE /dev/vg0/var
sudo pvs; sudo vgs; df -h /varWhy โ The LV spans both PVs transparently.
Interview tip โ Flag the risk: a linear LV across two disks fails if either disk fails, so on bare metal put RAID underneath.
Q30 A cloud VM's root disk was enlarged from 30 GB to 80 GB in the console, but df still shows 30 GB. What do you do?
Beginner
df still shows 30 GB. What do you do?Situation read โ The block device grew, but the partition and filesystem did not.
What I'd do โ
lsblk # disk 80G, partition still 30G
sudo growpart /dev/nvme0n1 1 # from cloud-guest-utils / cloud-utils-growpart
sudo xfs_growfs / # XFS
# or: sudo resize2fs /dev/nvme0n1p1 # ext4
df -h /If root is on LVM: growpart, then pvresize /dev/nvme0n1p3, then lvextend -r.
Why โ Three layers must each be resized: disk, partition, filesystem.
Interview tip โ Note that cloud-init's growpart module does this automatically at boot on many images.
Q31 You need to move a busy MySQL data directory from the root disk to a new, faster volume. Plan it.
Intermediate
Situation read โ Short downtime is unavoidable for a consistent copy unless you replicate.
What I'd do โ
- Pre-sync while running:
rsync -aHAX /var/lib/mysql/ /mnt/newvol/mysql/. - Stop MySQL, run a final
rsync -aHAX --delete(fast, only changes). - Mount the new volume at
/var/lib/mysqlvia fstab (better than changingdatadir). - Fix SELinux labels if enforcing:
restorecon -Rv /var/lib/mysql. - Start MySQL, check the error log and run a test query. Keep the old copy for a few days.
Why โ Two-pass rsync keeps downtime to the size of the delta, and mounting at the original path avoids config and SELinux changes.
Interview tip โ For zero downtime, mention building a replica on the new volume and failing over.
Q32 A team wants a shared directory mounted on 10 app servers. How do you set up NFS?
Beginner
Situation read โ NFS server export plus client mounts.
What I'd do โ
- Server:
sudo dnf install -y nfs-utils # or apt install nfs-kernel-server
sudo mkdir -p /exports/shared
echo '/exports/shared 10.0.1.0/24(rw,sync,root_squash)' | sudo tee -a /etc/exports
sudo systemctl enable --now nfs-server
sudo exportfs -rav- Open firewall for NFSv4 (TCP 2049).
- Clients:
10.0.1.10:/exports/shared /mnt/shared nfs4 defaults,_netdev,nofail 0 0in fstab, thenmount -a.
Why โ root_squash maps client root to nobody, so root on a client can't own the share. _netdev waits for the network at boot.
Interview tip โ Say UIDs must match across clients (or use NFSv4 idmapping) otherwise ownership looks wrong.
Q33 An NFS server will be down for maintenance and clients must not hang. How do you prepare the clients?
Intermediate
Situation read โ Hard mounts block processes in D state until the server returns.
What I'd do โ
- Before maintenance, stop the apps that use the mount and
umount /mnt/sharedon clients. - Long term, use autofs so the mount happens on access and expires when idle:
# /etc/auto.master.d/shared.autofs
/mnt /etc/auto.shared --timeout=300
# /etc/auto.shared
shared -fstype=nfs4,rw 10.0.1.10:/exports/shared- Only use
soft,timeo=for read-only, non-critical data, because soft mounts can corrupt writes.
Why โ Hard mounts protect data integrity; the price is hanging processes when the server is gone.
Interview tip โ Showing you know that soft is a data-integrity trade-off scores points.
Q34 You need to free a disk that is mounted, but umount says "target is busy". What do you do?
Beginner
umount says "target is busy". What do you do?Situation read โ Some process has a file open or a cwd on that mount.
What I'd do โ
sudo fuser -vm /data
sudo lsof +f -- /dataStop those services cleanly (or ask users to cd out), then umount /data. Last resort: umount -l /data (lazy) and make sure nothing writes afterwards.
Why โ Killing a database to unmount is worse than stopping it properly.
Interview tip โ Mention that a shell sitting in the directory, often your own, is the classic culprit.
Q35 A batch job writes millions of tiny files per day. Which filesystem and options would you pick?
Advanced
Situation read โ Inode density and metadata performance matter more than throughput.
What I'd do โ
- Prefer XFS: inodes are allocated dynamically, so you don't run out early.
- If ext4 is required, format with more inodes:
mkfs.ext4 -i 4096 /dev/sdbor-N <count>. - Mount with
noatimeto avoid a metadata write on every read. - Use a directory hashing scheme (
ab/cd/abcdef...) so no single directory holds millions of entries. - Reconsider the design: object storage or packing files into archives is often better.
Why โ ext4 fixes the inode count at format time; tiny files exhaust inodes before blocks.
Interview tip โ Show you'd monitor df -i alongside df -h.
Q36 You must take consistent backups of a filesystem that is constantly being written to. How?
Intermediate
Situation read โ Use point-in-time snapshots.
What I'd do โ
- On LVM:
sudo lvcreate -s -n data_snap -L 10G /dev/vg0/data
sudo mount -o ro,nouuid /dev/vg0/data_snap /mnt/snap # nouuid needed for XFS
sudo tar -czf /backup/data-$(date +%F).tar.gz -C /mnt/snap .
sudo umount /mnt/snap && sudo lvremove -y /dev/vg0/data_snap- For databases, flush or use the DB's own tool first (
mysqldump --single-transaction,pg_basebackup), orfsfreezearound the snapshot. - In the cloud, use EBS snapshots with application-consistent hooks.
Why โ A snapshot gives a frozen view; copying a live directory produces a torn backup.
Interview tip โ Mention that an LVM snapshot becomes invalid if its COW space fills, so size it for the change rate.
Q37 A developer asks for a 4 GB swap on a server with no free partitions. How do you add it?
Beginner
Situation read โ Use a swap file.
What I'd do โ
sudo fallocate -l 4G /swapfile # on XFS/ext4; use dd on btrfs or if fallocate fails
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
echo '/swapfile none swap defaults 0 0' | sudo tee -a /etc/fstab
swapon --show; free -hWhy โ chmod 600 stops users reading memory pages written to swap.
Interview tip โ Mention vm.swappiness and that some workloads (Kubernetes nodes historically, latency-sensitive DBs) avoid swap on purpose.
Q38 You need software RAID 1 across two disks on a bare-metal server. How do you build and monitor it?
Intermediate
Situation read โ mdadm mirror.
What I'd do โ
sudo mdadm --create /dev/md0 --level=1 --raid-devices=2 /dev/sdb /dev/sdc
cat /proc/mdstat
sudo mkfs.xfs /dev/md0
sudo mdadm --detail --scan | sudo tee -a /etc/mdadm.conf # /etc/mdadm/mdadm.conf on Debian
sudo dracut -f # or update-initramfs -uEnable alerts: set MAILADDR [email protected] in mdadm.conf and run mdmonitor.
Why โ Saving the array config and rebuilding initramfs makes the array assemble at boot with the same name.
Interview tip โ "RAID is not a backup" is the line interviewers want to hear.
Q39 A disk in your RAID 1 array failed. How do you replace it without downtime?
Intermediate
Situation read โ Degraded mirror; swap and resync.
What I'd do โ
cat /proc/mdstat # [U_] means degraded
sudo mdadm /dev/md0 --fail /dev/sdc --remove /dev/sdc
# physically replace the disk (hot-swap bay)
sudo sfdisk -d /dev/sdb | sudo sfdisk /dev/sdc # copy partition table if partitioned
sudo mdadm /dev/md0 --add /dev/sdc
watch cat /proc/mdstatIf the array is also the boot disk, reinstall the bootloader on the new disk.
Why โ The array keeps serving from the healthy disk while it rebuilds.
Interview tip โ Check smartctl -a on the surviving disk; a second failure during rebuild is the real risk.
Q40 Your application logs fill disks on 100 servers. Design a log retention approach.
Intermediate
Situation read โ Local retention short, central retention long.
What I'd do โ
- logrotate config per app:
/var/log/myapp/*.log {
daily
rotate 7
compress
delaycompress
missingok
notifempty
copytruncate
maxsize 500M
}- Cap journald:
SystemMaxUse=1Gin/etc/systemd/journald.conf. - Ship logs to a central system (Loki, Elasticsearch, CloudWatch) with an agent like Fluent Bit or Vector.
- Put
/var/logon its own LV so it can't fill root.
Why โ Local disks are for a few days of debugging; central storage gives search and long retention.
Interview tip โ Explain copytruncate vs signalling the app (postrotate) and when each is safer.
Q41 You need to encrypt a data disk on a Linux server holding customer data. How do you do it?
Advanced
Situation read โ LUKS encryption at rest, with a plan for unlocking at boot.
What I'd do โ
sudo cryptsetup luksFormat --type luks2 /dev/sdb
sudo cryptsetup open /dev/sdb securedata
sudo mkfs.xfs /dev/mapper/securedata- Add to
/etc/crypttab:securedata UUID=<luks-uuid> none luksand mount via fstab. - For unattended boot, bind to TPM2 (
systemd-cryptenroll --tpm2-device=auto /dev/sdb) or network-bound Clevis/Tang. - Back up the LUKS header:
cryptsetup luksHeaderBackup /dev/sdb --header-backup-file hdr.img.
Why โ If the header is lost, the data is gone forever; TPM/Tang avoids a human typing a passphrase.
Interview tip โ In the cloud, mention provider-managed encryption (EBS + KMS) as usually enough unless policy requires OS-level keys.
Q42 A team wants a filesystem mounted at /tmp that clears on reboot and can't run binaries. How do you set it up?
Intermediate
/tmp that clears on reboot and can't run binaries. How do you set it up?Situation read โ tmpfs with hardened mount options.
What I'd do โ
sudo systemctl enable tmp.mounton distros that ship it, or add to fstab:
tmpfs /tmp tmpfs defaults,size=2G,nodev,nosuid,noexec,mode=1777 0 0sudo mount -o remount /tmp(or reboot) and verify withfindmnt /tmp.- Test installers and tools that unpack to
/tmpand run from there; setTMPDIRfor them ifnoexecbreaks them.
Why โ noexec blocks a common attacker trick of dropping binaries in /tmp; 1777 keeps the sticky bit so users can't delete each other's files.
Interview tip โ Mention the sticky bit by name.
Q43 Your company wants nightly backups of /etc, /home and /var/www to a remote server, retained for 30 days. Design it.
Intermediate
/etc, /home and /var/www to a remote server, retained for 30 days. Design it.Situation read โ Deduplicated, encrypted, versioned backups.
What I'd do โ
- Use restic or borg rather than plain tar:
export RESTIC_REPOSITORY=sftp:backup@backup01:/srv/restic/web01
export RESTIC_PASSWORD_FILE=/root/.restic-pass
restic backup /etc /home /var/www --exclude-caches
restic forget --keep-daily 30 --prune- Run from a systemd timer, log to the journal, alert on failure.
- Do a monthly restore test to a scratch directory.
Why โ Dedup keeps storage small, encryption protects the remote copy, and forget handles retention.
Interview tip โ "Backups you haven't restored are hopes, not backups."
Q44 A disk is showing reallocated sectors in SMART. What do you do?
Intermediate
Situation read โ The disk is failing; plan replacement before it dies.
What I'd do โ
sudo smartctl -a /dev/sda | grep -Ei 'Reallocated|Pending|Uncorrectable|overall'
sudo smartctl -t long /dev/sda- Confirm backups are current and restorable.
- If in RAID, schedule a disk swap. If not, migrate data now.
- Watch
dmesgfor I/O errors.
Why โ A rising reallocated or pending count predicts failure.
Interview tip โ Mention running smartd so this alert arrives automatically, not when you happen to look.
Q45 You need to check and repair an ext4 filesystem that reported errors. How do you do it safely?
Intermediate
Situation read โ Never run fsck on a mounted read-write filesystem.
What I'd do โ
- Unmount the filesystem (for root, boot into rescue mode or schedule a check at boot).
- Take a snapshot or image first if the data matters (
ddor a cloud snapshot). - Run:
sudo e2fsck -f -y /dev/vg0/data- For XFS use
xfs_repair /dev/vg0/data(use-nfirst for a dry run). - Check
lost+foundfor recovered files afterwards.
Why โ Repairing a mounted filesystem can corrupt it further.
Interview tip โ Mention that tune2fs -l shows the last check time and mount count.
Q46 A partner sends you an ISO image you need to inspect. How do you look at its contents without burning it?
Beginner
Situation read โ Loop mount.
What I'd do โ
sudo mkdir -p /mnt/iso
sudo mount -o loop,ro image.iso /mnt/iso
ls /mnt/iso
sudo umount /mnt/isoWhy โ The loop device presents a file as a block device; ro avoids accidental modification.
Interview tip โ losetup -a lists active loop devices, which helps clean up leftovers.
Q47 A server needs a large shared scratch space across two disks for speed, and data loss is acceptable. What do you build?
Advanced
Situation read โ Striping for throughput, no redundancy.
What I'd do โ
sudo pvcreate /dev/sdb /dev/sdc
sudo vgcreate scratch /dev/sdb /dev/sdc
sudo lvcreate -i 2 -I 256k -l 100%FREE -n fast scratch
sudo mkfs.xfs /dev/scratch/fastMount with noatime and label it clearly as non-persistent.
Why โ A striped LV (-i 2) spreads I/O over both disks; losing either disk loses everything, which is acceptable for scratch.
Interview tip โ Compare with mdadm --level=0; both work, LVM is easier to resize.
Q48 You must migrate a filesystem from ext4 to XFS on a live system. What is your plan?
Advanced
Situation read โ There is no in-place conversion; you copy data to a new filesystem.
What I'd do โ
- Create a new LV or disk and format XFS.
- Pre-copy with
rsync -aHAXS --numeric-ids /data/ /newdata/. - Stop writers, final rsync with
--delete. - Swap mount points in fstab (by UUID) and mount.
- Restore SELinux contexts, start services, verify, keep the old volume read-only for rollback.
Why โ -H keeps hardlinks, -A ACLs, -X xattrs (SELinux labels), -S sparse files: all things plain cp can lose.
Interview tip โ Mention that XFS can't shrink, so size it right.
Q49 Users complain that ls in a directory with 3 million files takes forever. What would you change?
Advanced
ls in a directory with 3 million files takes forever. What would you change?Situation read โ Huge flat directories are slow to list and sort.
What I'd do โ
- Short term: avoid sorting and stat:
ls -forfind . -maxdepth 1 -printf '%f\n' | head. - Restructure into hashed subdirectories (
a1/b2/file), done by the app. - Move processed files to dated archive dirs or object storage.
- Make sure
dir_indexis on for ext4 (tune2fs -l | grep features).
Why โ ls reads and sorts every entry and, with colour or -l, stats each one.
Interview tip โ Mention that rm * fails with "Argument list too long"; use find -delete.
Q50 How would you decide disk layout (partitions/LVs) for a new production Linux server?
Advanced
Situation read โ Isolation, growth room and security options.
What I'd do โ
- Small
/boot(1 GB) and/boot/efi. - LVM for everything else, leaving free space in the VG.
- Separate LVs:
/,/var,/var/log,/var/log/audit,/home,/tmp, and the app data volume. - Mount options:
nodev,nosuid,noexecon/tmpand/var/tmp;nodevon/home. - In the cloud, keep data on separate volumes so instances can be rebuilt.
Why โ A runaway log can't fill root, and CIS benchmarks expect these separations.
Interview tip โ Mention leaving unallocated VG space so you can extend whichever LV grows.
Processes, services and systemd
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q51 Your team has a Python API that someone starts with nohup python app.py &. Make it a proper service running as a non-root user.
Beginner
nohup python app.py &. Make it a proper service running as a non-root user.Situation read โ Turn an ad-hoc process into a managed, restartable systemd unit.
What I'd do โ
sudo useradd --system --shell /usr/sbin/nologin --home /opt/api api- Create
/etc/systemd/system/api.service:
[Unit]
Description=Orders API
After=network-online.target
Wants=network-online.target
[Service]
User=api
Group=api
WorkingDirectory=/opt/api
EnvironmentFile=/etc/api/api.env
ExecStart=/opt/api/venv/bin/gunicorn -b 0.0.0.0:8000 app:app
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.targetsudo systemctl daemon-reload && sudo systemctl enable --now api- Check
systemctl status apiandjournalctl -u api -f.
Why โ systemd restarts on crash, starts at boot, captures logs and runs it as a locked-down user.
Interview tip โ Mention Restart=on-failure vs always, and that ExecStart needs an absolute path.
Q52 The service you created must bind to port 443, but it runs as a non-root user. How?
Beginner
Situation read โ Ports below 1024 need CAP_NET_BIND_SERVICE.
What I'd do โ
Add to the [Service] section:
AmbientCapabilities=CAP_NET_BIND_SERVICE
CapabilityBoundingSet=CAP_NET_BIND_SERVICEThen daemon-reload and restart. Alternatives: put nginx in front on 443 and proxy to a high port, or use socket activation.
Why โ You grant one privilege instead of running the whole app as root.
Interview tip โ Mention sysctl net.ipv4.ip_unprivileged_port_start exists but it is a host-wide change.
Q53 You need to change one setting (memory limit) in a vendor-supplied unit file without editing it. How?
Beginner
Situation read โ Use a drop-in override.
What I'd do โ
sudo systemctl edit vendor-agentAdd:
[Service]
MemoryMax=512MSave; systemd writes /etc/systemd/system/vendor-agent.service.d/override.conf and reloads. Restart the service and check with systemctl show vendor-agent -p MemoryMax or systemctl cat vendor-agent.
Why โ Package upgrades overwrite /usr/lib/systemd/system/*.service, but never your drop-ins.
Interview tip โ To clear a list setting like ExecStart, write an empty ExecStart= line first in the drop-in.
Q54 A service depends on a database on the same host and fails at boot because the DB isn't ready. How do you fix the ordering?
Intermediate
Situation read โ Ordering vs requirement vs readiness.
What I'd do โ
- In the app unit:
[Unit]
Requires=postgresql.service
After=postgresql.service- If "started" isn't the same as "accepting connections", add a readiness check:
ExecStartPre=/usr/bin/pg_isready -h localhost -t 30- Make the app itself retry connections; that's the real fix.
Why โ After= only orders; Requires=/Wants= pulls the unit in. Neither waits for the DB to be ready unless the DB unit uses Type=notify.
Interview tip โ Explain the difference between Wants (soft) and Requires (hard).
Q55 A service keeps crashing and systemd stops restarting it after a few attempts. How do you tune this?
Intermediate
Situation read โ Start rate limiting is kicking in.
What I'd do โ
- Look:
systemctl status appshows "Start request repeated too quickly". - Find the cause in
journalctl -u app -b. - Tune if appropriate:
[Unit]
StartLimitIntervalSec=300
StartLimitBurst=10
[Service]
Restart=on-failure
RestartSec=10- Reset after fixing:
systemctl reset-failed app.
Why โ Rate limiting prevents a crash loop from burning CPU. Tuning gives transient issues time to clear, but it doesn't hide real bugs.
Interview tip โ Mention that StartLimit* belongs in [Unit] on current systemd.
Q56 A long-running app must reload its config without dropping connections. How do you wire this into systemd?
Intermediate
Situation read โ Reload instead of restart.
What I'd do โ
[Service]
ExecStart=/usr/local/bin/myapp --config /etc/myapp.yml
ExecReload=/bin/kill -HUP $MAINPIDThen systemctl reload myapp. Validate the config first in ExecReload if the app supports it, for example nginx uses nginx -t before the signal.
Why โ The app re-reads config on SIGHUP while keeping its sockets open.
Interview tip โ systemctl reload-or-restart is handy in automation when you're not sure a unit supports reload.
Q57 A script needs to run once at boot after networking, then exit. How do you do it with systemd?
Beginner
Situation read โ A oneshot unit.
What I'd do โ
[Unit]
Description=Register node at boot
After=network-online.target
Wants=network-online.target
[Service]
Type=oneshot
ExecStart=/usr/local/bin/register-node.sh
RemainAfterExit=yes
[Install]
WantedBy=multi-user.targetEnable it with systemctl enable register-node.
Why โ Type=oneshot makes systemd wait for completion; RemainAfterExit keeps it "active" so dependents see it as done.
Interview tip โ Prefer this over /etc/rc.local, which many distros no longer run by default.
Q58 Ops wants to limit a noisy batch service to 2 CPUs and 4 GB RAM on a shared host. How?
Intermediate
Situation read โ cgroup v2 limits via systemd.
What I'd do โ
sudo systemctl set-property batch.service CPUQuota=200% MemoryMax=4G MemoryHigh=3.5G
systemctl show batch -p CPUQuotaPerSecUSec -p MemoryMax
systemd-cgtopFor ad-hoc jobs: systemd-run --scope -p CPUQuota=100% -p MemoryMax=2G ./job.sh.
Why โ CPUQuota=200% equals two full CPUs; MemoryHigh throttles before MemoryMax triggers the OOM killer.
Interview tip โ set-property persists by writing a drop-in; add --runtime for a temporary change.
Q59 A security review says your services run with too many privileges. Which systemd hardening options would you add?
Advanced
Situation read โ Sandbox the service using systemd's built-in options.
What I'd do โ
[Service]
User=app
NoNewPrivileges=yes
ProtectSystem=strict
ReadWritePaths=/var/lib/app /var/log/app
ProtectHome=yes
PrivateTmp=yes
PrivateDevices=yes
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectControlGroups=yes
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
SystemCallFilter=@system-service
CapabilityBoundingSet=Score it with systemd-analyze security app.service and iterate until the app still works.
Why โ If the app is exploited, the attacker lands in a read-only, capability-free box.
Interview tip โ Mention systemd-analyze security by name; it shows you've done this for real.
Q60 You need to run a nightly job as a specific user only while they're not logged in, and it should start even if they never log in. How?
Advanced
Situation read โ User-level systemd services need lingering.
What I'd do โ
sudo loginctl enable-linger builder
sudo -iu builder
mkdir -p ~/.config/systemd/user
# create job.service and job.timer there
systemctl --user daemon-reload
systemctl --user enable --now job.timerWhy โ Without lingering, the user's systemd manager only runs while they have a session, so user units stop at logout.
Interview tip โ This is also how rootless Podman containers keep running after logout.
Q61 An app forks into a background daemon itself. systemd thinks it died right after start. How do you configure the unit?
Intermediate
Situation read โ Wrong service Type.
What I'd do โ
- Best: run the app in the foreground (most have a
--foregroundor-Dflag) and keepType=simpleorexec. - If it must fork:
[Service]
Type=forking
PIDFile=/run/myapp/myapp.pid
ExecStart=/usr/sbin/myapp -dWhy โ With Type=simple, the parent exits after forking and systemd considers the service stopped and may kill the child.
Interview tip โ Mention Type=notify for apps that signal readiness with sd_notify.
Q62 You need to stop a service from being started by anyone, even as a dependency, during an investigation. How?
Beginner
Situation read โ disable isn't enough; use mask.
What I'd do โ
sudo systemctl stop cups
sudo systemctl mask cups
systemctl status cups # shows "masked"
# later
sudo systemctl unmask cupsWhy โ Mask links the unit to /dev/null, so neither manual starts nor dependencies can activate it. disable only removes boot-time links.
Interview tip โ Remember to mask the .socket too for socket-activated services.
Q63 A process is using 100% CPU on a production box. What's your approach before killing it?
Beginner
Situation read โ Understand it before you kill it; it might be important.
What I'd do โ
top -c # or htop; find PID and command
ps -o pid,ppid,user,etime,cmd -p <PID>
sudo ls -l /proc/<PID>/cwd /proc/<PID>/exe
sudo strace -p <PID> -f -c # syscalls summary, Ctrl+C after a few secondsIf it's legitimate but should be less greedy: renice +10 -p <PID>. If runaway: kill -TERM, then kill -KILL if it ignores TERM.
Why โ SIGTERM lets the app clean up; SIGKILL can leave locks and half-written files.
Interview tip โ Grab a thread dump (jstack, py-spy dump) before killing for the postmortem.
Q64 A legacy app has no systemd unit and must survive SSH logout while you build one. What quick options do you have?
Beginner
Situation read โ Detach the process from the terminal for now.
What I'd do โ
tmux new -s legacythen run it; detach withCtrl+b d.- Or a transient systemd unit, which is better:
sudo systemd-run --unit=legacy-app --uid=appuser /opt/legacy/run.sh
journalctl -u legacy-app -fnohup ./run.sh > out.log 2>&1 &as a last resort.
Why โ systemd-run gives logging and control (systemctl stop legacy-app) without writing a file.
Interview tip โ Mention SIGHUP: closing the terminal sends it, which is why plain & processes die.
Q65 You need two instances of the same worker service with different config on one host. How?
Intermediate
Situation read โ systemd template units.
What I'd do โ
Create /etc/systemd/system/[email protected]:
[Service]
User=worker
EnvironmentFile=/etc/worker/%i.env
ExecStart=/opt/worker/bin/worker --queue %i
Restart=on-failure
[Install]
WantedBy=multi-user.targetThen:
sudo systemctl enable --now worker@emails worker@reports
systemctl status 'worker@*'Why โ %i is replaced with the instance name, so one file serves any number of instances.
Interview tip โ Templates are also how getty@tty1 and openvpn@client work.
Q66 A service should only start when a request arrives on its port, to save memory. How?
Advanced
Situation read โ Socket activation.
What I'd do โ
/etc/systemd/system/tool.socket:
[Socket]
ListenStream=9000
[Install]
WantedBy=sockets.targettool.servicewithExecStart=/usr/local/bin/tooland the app reading the inherited socket (LISTEN_FDS).systemctl enable --now tool.socket.
Why โ systemd holds the port; the first connection starts the service, and no connection is lost during startup.
Interview tip โ The app must support receiving the socket from systemd; not every app does.
Q67 Developers want to see the logs of only their service from the last hour, without sudo. How?
Beginner
Situation read โ journald access for non-root users.
What I'd do โ
sudo usermod -aG systemd-journal alice
# then alice runs:
journalctl -u api --since "1 hour ago" --no-pager
journalctl -u api -p err -fWhy โ Members of systemd-journal (and adm on Debian/Ubuntu) can read the system journal.
Interview tip โ Mention --since, -p priority and -o json for scripts.
Q68 The journal is lost on every reboot and you need logs from before a crash. What do you change?
Beginner
Situation read โ journald is in volatile mode.
What I'd do โ
sudo mkdir -p /var/log/journal
sudo systemd-tmpfiles --create --prefix /var/log/journal
sudo sed -i 's/^#\?Storage=.*/Storage=persistent/' /etc/systemd/journald.conf
sudo systemctl restart systemd-journald
journalctl --list-bootsAfterwards use journalctl -b -1 -e for the previous boot.
Why โ With Storage=auto, journald persists only if /var/log/journal exists.
Interview tip โ Pair it with SystemMaxUse= so persistent logs don't fill the disk.
Q69 A Java service takes 3 minutes to shut down and systemd kills it after 90 seconds, corrupting state. Fix it.
Intermediate
Situation read โ Default stop timeout is too short.
What I'd do โ
[Service]
TimeoutStopSec=300
KillSignal=SIGTERM
KillMode=mixedThen investigate why shutdown takes 3 minutes (draining connections, flushing caches).
Why โ systemd sends KillSignal, waits TimeoutStopSec, then sends SIGKILL. KillMode=mixed sends SIGTERM only to the main process and SIGKILL to leftovers at the end.
Interview tip โ Mention that DefaultTimeoutStopSec is set globally in /etc/systemd/system.conf.
Q70 You need to temporarily run a command with a lower I/O priority so a backup doesn't hurt the database. How?
Intermediate
Situation read โ CPU and I/O niceness, or cgroup I/O weights.
What I'd do โ
nice -n 19 ionice -c3 tar -czf /backup/data.tgz /data
# or with cgroups:
sudo systemd-run --scope -p IOWeight=10 -p CPUWeight=10 tar -czf /backup/data.tgz /dataWhy โ ionice -c3 (idle class) only gets disk time when nobody else wants it; cgroup weights work on cgroup v2 with any I/O scheduler that supports them.
Interview tip โ Mention that ionice classes depend on the I/O scheduler; IOWeight is the more modern approach.
Q71 A daemon writes a PID file and ops scripts use it, but after crashes the stale PID points to a different process. How do you fix the design?
Advanced
Situation read โ PID files are racy; let the supervisor track the process.
What I'd do โ
- Run the daemon in the foreground under systemd (
Type=simple/notify), which tracks it by cgroup. - Scripts use
systemctl is-active app,systemctl kill apporsystemctl show -p MainPID app. - If PID files must stay, put them in
/run(cleared at boot) viaRuntimeDirectory=app.
Why โ cgroup tracking can't confuse processes, and /run is a tmpfs, so stale files vanish on reboot.
Interview tip โ "Let systemd own process lifecycle" is the senior answer.
Q72 You have to schedule a maintenance reboot of a host but want running services to stop cleanly in the right order. How?
Beginner
Situation read โ Use systemd shutdown, not a hard reset.
What I'd do โ
sudo shutdown -r 02:00 "Kernel patching"
# check / cancel
shutdown --show 2>/dev/null; sudo shutdown -cDrain the host from load balancers first, and make sure units have correct After= ordering, since systemd stops units in reverse start order.
Why โ A clean shutdown runs ExecStop and lets databases flush.
Interview tip โ Mention draining traffic before rebooting; that's what separates ops from just commands.
Q73 An app needs environment variables containing secrets. How do you give them to a systemd service safely?
Advanced
Situation read โ Avoid secrets in unit files, which are world-readable.
What I'd do โ
- Better: use systemd credentials:
[Service]
LoadCredential=db_password:/etc/app/secrets/db_password
ExecStart=/opt/app/bin/appThe app reads $CREDENTIALS_DIRECTORY/db_password. With systemd-creds encrypt, use LoadCredentialEncrypted= (TPM-bound).
2. Acceptable: EnvironmentFile=/etc/app/app.env with chmod 600 root:root.
3. Best for fleets: fetch from Vault or a cloud secret manager at start.
Why โ Environment= lines show up in systemctl show, and environment variables leak to child processes and /proc/<pid>/environ.
Interview tip โ Mention that systemctl show reveals Environment= to any user.
Q74 A cron-started process spawns children that keep running after the parent is killed. How do you clean this up properly?
Advanced
Situation read โ Orphaned process trees; you need group or cgroup-wide termination.
What I'd do โ
- Now: find the process group/session and kill it:
ps -eo pid,pgid,sid,cmd | grep job
kill -TERM -- -<PGID>- Long term: run the job as a systemd service/timer, so
systemctl stopkills the whole cgroup (KillMode=control-group, default).
Why โ Signals sent to one PID don't reach its children; cgroups contain every descendant.
Interview tip โ The minus sign in kill -- -PGID targets the process group, a detail interviewers like.
Q75 You must find which service is listening on an unexpected port 8443 on a server. How?
Beginner
Situation read โ Map port to process, then process to package or unit.
What I'd do โ
sudo ss -tlnp 'sport = :8443'
sudo lsof -i :8443
systemctl status <PID> # shows the owning unit
rpm -qf /proc/<PID>/exe 2>/dev/null || dpkg -S "$(readlink /proc/<PID>/exe)"Why โ systemctl status <PID> finds the unit from the cgroup, telling you who installed and runs it.
Interview tip โ If the owner is unknown and not in any package, treat it as a possible compromise.
Scheduling, automation and scripting
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q76 A database dump must run every night at 1:30 AM. How do you schedule it with cron so it is reliable?
Beginner
Situation read โ Cron entry plus everything cron doesn't give you: environment, logging, failure alerts.
What I'd do โ
- Write a script with
set -euo pipefailand absolute paths. - Add a system cron file
/etc/cron.d/db-dump:
SHELL=/bin/bash
PATH=/usr/local/bin:/usr/bin:/bin
[email protected]
30 1 * * * postgres /usr/local/bin/db-dump.sh >> /var/log/db-dump.log 2>&1- Test by running the script as that user:
sudo -u postgres /usr/local/bin/db-dump.sh.
Why โ Cron runs with a minimal PATH and no login profile, which is the number-one reason jobs work by hand but fail in cron.
Interview tip โ Mention /etc/cron.d files include a user column, unlike crontab -e.
Q77 Convert that nightly cron job to a systemd timer. Why would you?
Intermediate
Situation read โ Timers add logging, dependencies and catch-up runs.
What I'd do โ
/etc/systemd/system/db-dump.service:
[Service]
Type=oneshot
User=postgres
ExecStart=/usr/local/bin/db-dump.sh/etc/systemd/system/db-dump.timer:
[Timer]
OnCalendar=*-*-* 01:30:00
Persistent=true
RandomizedDelaySec=300
[Install]
WantedBy=timers.targetsystemctl enable --now db-dump.timer, check with systemctl list-timers.
Why โ Output goes to the journal, Persistent=true runs a missed job after downtime, and resource limits and OnFailure= alerts are available.
Interview tip โ Validate calendar expressions with systemd-analyze calendar '*-*-* 01:30:00'.
Q78 A cron job runs every 5 minutes, but sometimes takes 8 minutes and two copies overlap, corrupting data. How do you prevent that?
Beginner
Situation read โ Need a lock so only one instance runs.
What I'd do โ
*/5 * * * * app flock -n /run/lock/sync.lock /usr/local/bin/sync.shOr inside the script:
exec 9>/run/lock/sync.lock
flock -n 9 || { echo "already running"; exit 0; }Why โ flock uses a kernel lock that is released automatically when the process dies, unlike a hand-made lock file that goes stale.
Interview tip โ A systemd timer also won't start a second copy while the service is still active.
Q79 You have 300 servers running the same cron job at midnight, and they hammer a shared API. How do you fix it?
Intermediate
Situation read โ Thundering herd; spread the start times.
What I'd do โ
- With systemd timers:
RandomizedDelaySec=1800(andFixedRandomDelay=truefor a stable per-host offset). - With cron, add a random sleep:
0 0 * * * sleep $((RANDOM % 1800)); /usr/local/bin/job.sh(needsSHELL=/bin/bash). - Or derive the minute from the hostname in your config management (Ansible
randomfilter withseed=inventory_hostname).
Why โ Jitter turns a spike into a flat load.
Interview tip โ Mention that $RANDOM is a bash feature and cron's default shell is /bin/sh.
Q80 A job must run on the last day of every month. Cron has no "last day" field. What do you do?
Intermediate
Situation read โ Use a date check or a systemd calendar expression.
What I'd do โ
- Cron: run on days 28โ31 and check tomorrow's date:
0 23 28-31 * * [ "$(date -d tomorrow +\%d)" = "01" ] && /usr/local/bin/month-end.sh- systemd timer:
OnCalendar=*-*~01 23:00:00(the~means counting from the end of the month).
Why โ % is special in crontab and must be escaped as \%.
Interview tip โ The escaped % is a classic "why doesn't my cron work" gotcha.
Q81 You inherited a server and need to know every scheduled job on it. Where do you look?
Beginner
Situation read โ Jobs hide in many places.
What I'd do โ
for u in $(cut -d: -f1 /etc/passwd); do sudo crontab -l -u "$u" 2>/dev/null | sed "s/^/$u: /"; done
ls -l /etc/crontab /etc/cron.d/ /etc/cron.{hourly,daily,weekly,monthly}/
systemctl list-timers --all
atq
ls /var/spool/cron/ /var/spool/cron/crontabs/ 2>/dev/nullWhy โ User crontabs, system crontabs, run-parts directories, systemd timers and at jobs are all separate.
Interview tip โ Mentioning systemd timers and anacron shows you know modern distros.
Q82 A one-off data fix must run at 9 PM tonight, just once. How do you schedule it?
Beginner
Situation read โ One-shot scheduling.
What I'd do โ
echo "/usr/local/bin/fix-data.sh >> /tmp/fix.log 2>&1" | at 21:00
atq
at -c <job> # see the full job
atrm <job> # cancelOr with systemd: systemd-run --on-calendar='2026-11-09 21:00' /usr/local/bin/fix-data.sh.
Why โ No need to add then remember to remove a cron line.
Interview tip โ atd must be running; check systemctl status atd.
Q83 A laptop-style VM is often off at night, so the daily cleanup job never runs. How do you make sure it runs once a day anyway?
Beginner
Situation read โ Machines that aren't always on need catch-up scheduling.
What I'd do โ
- Put the script in
/etc/cron.daily/, which anacron runs once a day when the machine is up. - Or use a systemd timer with
OnCalendar=dailyandPersistent=true.
Why โ Plain cron only runs at the exact minute; if the host is off, the run is skipped.
Interview tip โ /var/spool/anacron/ holds the last-run timestamps.
Q84 Write a safe bash script header for a production maintenance script. What goes in it and why?
Intermediate
Situation read โ Fail fast, clean up, log.
What I'd do โ
#!/usr/bin/env bash
set -Eeuo pipefail
IFS=$'\n\t'
trap 'echo "ERROR line $LINENO: $BASH_COMMAND" >&2' ERR
tmpdir=$(mktemp -d)
trap 'rm -rf "$tmpdir"' EXIT
log() { logger -t maint "$*"; echo "$(date -Is) $*"; }Why โ -e exits on error, -u catches unset variables, pipefail catches failures inside pipes, the ERR trap tells you where it died, and the EXIT trap always cleans up temp files.
Interview tip โ Mention shellcheck in CI for every script.
Q85 A cleanup script must delete files older than 14 days in /data/exports, but someone once deleted / by mistake with a similar script. How do you write it safely?
Intermediate
/data/exports, but someone once deleted / by mistake with a similar script. How do you write it safely?Situation read โ Guard against empty variables and wrong paths.
What I'd do โ
#!/usr/bin/env bash
set -euo pipefail
target="${EXPORT_DIR:?EXPORT_DIR not set}"
[[ "$target" == /data/exports* ]] || { echo "refusing: $target"; exit 1; }
find "$target" -xdev -type f -mtime +14 -print -deleteRun once with -print only (no -delete) to review.
Why โ ${VAR:?} aborts if empty, so rm -rf "$VAR/" can never become rm -rf /. -xdev stops find crossing into other mounts.
Interview tip โ Mention the famous Steam bug (rm -rf "$STEAMROOT/"* with an empty variable).
Q86 You need to run the same command on 40 servers right now and you don't have Ansible set up. What do you do?
Intermediate
Situation read โ Parallel SSH, carefully.
What I'd do โ
# hosts.txt has one host per line
parallel-ssh -h hosts.txt -i -t 30 'uptime' # pssh package
# or plain bash + xargs
xargs -P 10 -I{} ssh -o BatchMode=yes -o ConnectTimeout=5 {} 'uptime' < hosts.txtRun on one host first, then a small batch, then the rest.
Why โ BatchMode=yes stops it hanging on password prompts; limiting parallelism avoids overloading shared services.
Interview tip โ Say you'd move it into an Ansible ad-hoc command (ansible all -m shell -a uptime) as soon as possible.
Q87 Your team writes shell scripts that parse ls output. Why is that a problem and what do you suggest?
Intermediate
ls output. Why is that a problem and what do you suggest?Situation read โ Filenames can have spaces, newlines and globs.
What I'd do โ
# bad
for f in $(ls /data); do ...; done
# good
for f in /data/*; do [[ -e "$f" ]] || continue; ...; done
# or for recursion
find /data -type f -print0 | while IFS= read -r -d '' f; do ...; doneWhy โ ls output is for humans; word-splitting breaks on spaces and newlines. Globs and -print0 are safe.
Interview tip โ Always quote variables: "$f".
Q88 A script must read a config file with KEY=VALUE lines, but you don't want to source it because it could contain commands. What do you do?
Advanced
KEY=VALUE lines, but you don't want to source it because it could contain commands. What do you do?Situation read โ Parse instead of executing.
What I'd do โ
declare -A cfg
while IFS='=' read -r key value; do
[[ "$key" =~ ^[A-Z_][A-Z0-9_]*$ ]] || continue
cfg["$key"]="$value"
done < /etc/myapp/settings.conf
echo "${cfg[DB_HOST]}"Why โ source runs whatever is in the file with the script's privileges, which is dangerous if the file is writable by others.
Interview tip โ Mention checking the file owner and permissions before trusting it.
Q89 A cron job's output fills root's mailbox with thousands of messages. How do you handle cron output properly?
Beginner
Situation read โ Cron mails any output; redirect deliberately.
What I'd do โ
- Send normal output to a log and only errors to mail:
[email protected]
*/10 * * * * app /usr/local/bin/job.sh > /var/log/job.log 2>&1 || echo "job failed"- Or log to syslog:
job.sh 2>&1 | logger -t job. - Clean the backlog:
> /var/spool/mail/root.
Why โ Silent success, loud failure is the right pattern.
Interview tip โ Better still: report to a dead-man's switch (Healthchecks.io, Cronitor) so missed runs alert too.
Q90 How would you get alerted if a critical nightly job silently stops running altogether?
Intermediate
Situation read โ Failure alerts don't fire if the job never starts. You need a heartbeat.
What I'd do โ
- At the end of a successful run, ping a dead-man's switch:
/usr/local/bin/backup.sh && curl -fsS -m 10 --retry 3 https://hc.example.com/ping/<uuid>- Or push a metric
job_last_success_timestampto Prometheus Pushgateway / node_exporter textfile collector, and alert iftime() - job_last_success_timestamp > 90000. - For systemd timers, add
OnFailure=notify@%n.service.
Why โ The absence of a signal is what you alert on.
Interview tip โ "Alert on missing success, not just on failure" is a senior-level answer.
Q91 A script must process a 50 GB log file line by line quickly. What tools would you use?
Intermediate
Situation read โ Avoid bash loops for big data; use stream tools.
What I'd do โ
LC_ALL=C grep -F ' 500 ' access.log | awk '{print $7}' | sort | uniq -c | sort -rn | head
# split into chunks and process in parallel
split -n l/8 access.log part_ && ls part_* | parallel -j8 "grep -c ERROR {}"Why โ while read in bash is very slow on large files; grep, awk, sort are optimised C. LC_ALL=C skips locale processing for big speedups.
Interview tip โ Mention zgrep/zcat for compressed logs instead of unpacking.
Q92 Your team wants every server to automatically install security updates. How do you set it up and stay safe?
Intermediate
Situation read โ Automate patching without surprise outages.
What I'd do โ
- Ubuntu/Debian:
apt install unattended-upgradesand enable security origins in/etc/apt/apt.conf.d/50unattended-upgrades. - RHEL/Rocky:
dnf install dnf-automatic, setupgrade_type = securityandapply_updates = yesin/etc/dnf/automatic.conf, thensystemctl enable --now dnf-automatic.timer. - Roll out in rings: canary hosts first, then the fleet a day later. Control reboots separately.
Why โ Security-only updates have low regression risk; rings catch the rest.
Interview tip โ Mention needs-restarting -r (RHEL) or /var/run/reboot-required (Ubuntu) for reboot detection.
Q93 You must run a job only on the primary node of a two-node cluster, but both nodes have the same cron. How?
Advanced
Situation read โ Make the job check leadership before acting.
What I'd do โ
- If there's a floating VIP (keepalived/Pacemaker), check it:
ip -o addr show | grep -q '10.0.0.100/' || exit 0- Or take a distributed lock (Consul
consul lock, etcd lease, a DB advisory lockSELECT pg_try_advisory_lock(42)). - Better: make it a cluster resource in Pacemaker, or a Kubernetes CronJob with
concurrencyPolicy: Forbid.
Why โ Duplicated runs cause double emails, double billing and similar issues.
Interview tip โ Mention making jobs idempotent so a double run is harmless anyway.
Q94 A script you wrote works for you but fails when run by sudo with "command not found". Why?
Beginner
sudo with "command not found". Why?Situation read โ sudo resets PATH to secure_path.
What I'd do โ
sudo grep secure_path /etc/sudoers
sudo env | grep PATHUse absolute paths in scripts, or install tools into a directory in secure_path (/usr/local/bin).
Why โ secure_path stops a user-controlled PATH from tricking root into running a malicious binary.
Interview tip โ Don't "fix" it with sudo env PATH=$PATH; that defeats the protection.
Q95 Your team wants scripts that work on both Ubuntu and RHEL hosts. How do you detect the distro reliably?
Intermediate
Situation read โ Use /etc/os-release, the standard.
What I'd do โ
. /etc/os-release
case "$ID" in
ubuntu|debian) pkg="apt-get install -y" ;;
rhel|rocky|almalinux|centos|fedora) pkg="dnf install -y" ;;
*) case "$ID_LIKE" in *rhel*|*fedora*) pkg="dnf install -y";; *debian*) pkg="apt-get install -y";; esac ;;
esacWhy โ /etc/os-release exists on every systemd distro; ID_LIKE covers derivatives.
Interview tip โ Say past a few branches you'd let Ansible facts (ansible_os_family) handle it.
Q96 A cron job runs a script that calls rsync to another host over SSH, but in cron it hangs forever. What's going on and how do you design it properly?
Intermediate
rsync to another host over SSH, but in cron it hangs forever. What's going on and how do you design it properly?Situation read โ No SSH agent and no TTY in cron; SSH is waiting for a password or host key confirmation.
What I'd do โ
- Use a dedicated key without a passphrase, restricted on the remote side (
command=,from=). - Pre-populate
known_hosts. - Make SSH fail fast:
rsync -a -e "ssh -i /home/sync/.ssh/id_ed25519 -o BatchMode=yes -o ConnectTimeout=10" /data/ sync@backup:/data/- Wrap with
timeout 2hso it can't hang forever.
Why โ BatchMode=yes turns a hidden prompt into an immediate error you can see in logs.
Interview tip โ Mention timeout as a general safety net for every scheduled job.
Q97 You need to rotate a custom application's log every hour, not daily. How?
Advanced
Situation read โ logrotate runs daily by default; it needs an hourly trigger.
What I'd do โ
- Config
/etc/logrotate.hourly.d/app:
/var/log/app/app.log {
hourly
rotate 48
compress
missingok
postrotate
systemctl kill -s HUP app.service
endscript
}- A timer or
/etc/cron.hourly/logrotate-hourlyrunninglogrotate /etc/logrotate.hourly.d/app. - Test with
logrotate -d(debug) and-f(force).
Why โ The hourly directive only works if logrotate itself is invoked every hour.
Interview tip โ Mention that postrotate signalling is safer than copytruncate, which can lose lines.
Q98 Ops asks for a script that waits until a remote service is up before continuing a deployment. How do you write it?
Beginner
Situation read โ Retry loop with a timeout.
What I'd do โ
for i in $(seq 1 30); do
if curl -fsS -o /dev/null --max-time 3 http://10.0.1.20:8080/healthz; then
echo "up after $i tries"; exit 0
fi
sleep 5
done
echo "service not ready after 150s" >&2; exit 1Why โ A bounded loop avoids hanging a pipeline forever and gives a clear failure.
Interview tip โ timeout 150 bash -c 'until curl -fs ...; do sleep 5; done' is a compact alternative.
Q99 Your team keeps writing the same server bootstrap steps by hand. How would you automate first-boot configuration for new cloud VMs?
Advanced
Situation read โ Use cloud-init plus config management, and bake images.
What I'd do โ
#cloud-config
users:
- name: ops
groups: wheel
ssh_authorized_keys: [ "ssh-ed25519 AAAA... ops" ]
package_update: true
packages: [chrony, auditd, amazon-cloudwatch-agent]
runcmd:
- [ systemctl, enable, --now, chronyd ]
- [ sh, -c, "curl -fsSL https://config.internal/bootstrap.sh | bash" ]Bake the slow parts into a golden image with Packer; let cloud-init do only host-specific bits.
Why โ Faster boot, consistent results, fewer moving parts at scale.
Interview tip โ Check cloud-init status --long and /var/log/cloud-init-output.log when it goes wrong.
Q100 A scheduled job must only run if the previous job in a chain succeeded. How do you build job dependencies on a single host?
Advanced
Situation read โ Chain with systemd dependencies instead of guessing times.
What I'd do โ
extract.service(oneshot) with a timer.transform.servicewith:
[Unit]
Requires=extract.service
After=extract.service- Or in
extract.service:ExecStartPost=/usr/bin/systemctl start --no-block transform.service(only runs on success), plusOnFailure=alert@%n.service.
Why โ Time-based chains ("extract at 1:00, transform at 2:00") break the first time extract runs long.
Interview tip โ Above a few steps, say you'd move it to Airflow or a CI pipeline for visibility.
Networking, SSH and remote access
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q101 A key belonging to a departed engineer may be in authorized_keys on 300 servers. How do you rotate SSH keys across the fleet?
Intermediate
authorized_keys on 300 servers. How do you rotate SSH keys across the fleet?Situation read โ Add new keys first, verify, then remove old ones, so nobody is locked out.
What I'd do โ
- Generate new keys:
ssh-keygen -t ed25519 -C "ops-2026-11" -f ~/.ssh/ops_2026. - Push them with Ansible:
- ansible.posix.authorized_key:
user: ops
key: "{{ lookup('file', 'keys/ops_2026.pub') }}"
state: present- Test login with the new key on every host (
ansible all -m ping --private-key ~/.ssh/ops_2026). - Remove old keys with
state: absent, or manage the whole file withexclusive: true. - Grep the fleet for unknown keys and investigate.
Why โ Add-verify-remove avoids lockouts; exclusive makes the file match your source of truth.
Interview tip โ End with "and this is why we moved to SSH certificates with short TTLs".
Q102 You need to reach a database on a private subnet from your laptop through a bastion. How?
Beginner
Situation read โ SSH jump host plus local port forwarding.
What I'd do โ
ssh -J [email protected] -L 5433:db.internal:5432 [email protected] -N
psql -h localhost -p 5433 -U appOr permanently in ~/.ssh/config:
Host app01
HostName app01.internal
User ops
ProxyJump bastion.example.com
LocalForward 5433 db.internal:5432Why โ -J/ProxyJump tunnels the SSH connection through the bastion end-to-end; -L forwards a local port to the target.
Interview tip โ Mention that in AWS you'd often use SSM Session Manager port forwarding instead of a bastion.
Q103 Your security team wants SSH hardened on all servers. What changes do you make?
Beginner
Situation read โ Disable weak paths, limit who can log in.
What I'd do โ
/etc/ssh/sshd_config.d/10-hardening.conf:
PermitRootLogin no
PasswordAuthentication no
KbdInteractiveAuthentication no
PubkeyAuthentication yes
AllowGroups ssh-users
MaxAuthTries 3
LoginGraceTime 30
X11Forwarding noThen sudo sshd -t && sudo systemctl reload sshd, and test from a second session before closing the first.
Why โ Keys plus no root plus a group allowlist removes the most common brute-force and misuse paths.
Interview tip โ Always keep an existing session open while changing sshd; that's the lockout insurance.
Q104 A new server needs a static IP, gateway and DNS on RHEL 9. How do you configure it persistently?
Beginner
Situation read โ NetworkManager via nmcli.
What I'd do โ
nmcli con show
sudo nmcli con mod "System eth0" ipv4.method manual \
ipv4.addresses 10.0.1.25/24 ipv4.gateway 10.0.1.1 \
ipv4.dns "10.0.0.2 10.0.0.3" ipv4.dns-search example.internal
sudo nmcli con up "System eth0"
ip addr show eth0; ip route; resolvectl status 2>/dev/null || cat /etc/resolv.confWhy โ Edits through nmcli persist in the connection profile; editing /etc/resolv.conf directly gets overwritten.
Interview tip โ On Ubuntu say Netplan (/etc/netplan/*.yaml + netplan try), which rolls back if you lose connectivity.
Q105 You're changing the network config of a remote server over SSH and could lose access. How do you protect yourself?
Intermediate
Situation read โ Have an automatic rollback.
What I'd do โ
- Ubuntu:
sudo netplan try --timeout 120reverts unless you confirm. - Generic: schedule a revert before applying:
sudo cp /etc/nftables.conf /root/nftables.conf.bak
echo "cp /root/nftables.conf.bak /etc/nftables.conf && systemctl restart nftables" | sudo at now + 5 minutes
# apply change, test, then:
sudo atrm <job>- Make sure out-of-band console access works (cloud serial console, iDRAC/iLO).
Why โ If you lose the connection, the revert runs without you.
Interview tip โ Run changes inside tmux so a dropped SSH session doesn't kill a half-finished command.
Q106 A web server should accept HTTP/HTTPS from anywhere but SSH only from the office. Configure the firewall.
Beginner
Situation read โ Host firewall with an allowlist for SSH.
What I'd do โ firewalld:
sudo firewall-cmd --permanent --add-service={http,https}
sudo firewall-cmd --permanent --remove-service=ssh
sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="203.0.113.0/24" service name="ssh" accept'
sudo firewall-cmd --reload && sudo firewall-cmd --list-allufw: ufw allow 80,443/tcp && ufw allow from 203.0.113.0/24 to any port 22 proto tcp && ufw enable.
Why โ Narrow SSH exposure removes most brute-force noise.
Interview tip โ In the cloud, do the same in the security group and keep the host firewall as a second layer.
Q107 Your app servers need to reach the internet for updates but must not be reachable from it. How do you set it up on a Linux gateway?
Intermediate
Situation read โ A NAT gateway with forwarding and masquerade.
What I'd do โ
echo 'net.ipv4.ip_forward = 1' | sudo tee /etc/sysctl.d/90-forward.conf && sudo sysctl --system
sudo nft add table ip nat
sudo nft add chain ip nat postrouting '{ type nat hook postrouting priority 100; }'
sudo nft add rule ip nat postrouting oifname "eth0" ip saddr 10.0.2.0/24 masqueradeAdd forward rules that allow 10.0.2.0/24 -> eth0 and only established/related traffic back. Save with nft list ruleset > /etc/nftables.conf.
Why โ Outbound connections are translated; unsolicited inbound has no NAT mapping and is dropped.
Interview tip โ In AWS, say you'd use a managed NAT Gateway rather than run this yourself.
Q108 You need a server to have two network interfaces bonded for redundancy. How do you configure it?
Intermediate
Situation read โ Link bonding (active-backup unless the switch supports LACP).
What I'd do โ
sudo nmcli con add type bond con-name bond0 ifname bond0 bond.options "mode=active-backup,miimon=100"
sudo nmcli con add type ethernet slave-type bond con-name bond0-p1 ifname eno1 master bond0
sudo nmcli con add type ethernet slave-type bond con-name bond0-p2 ifname eno2 master bond0
sudo nmcli con mod bond0 ipv4.method manual ipv4.addresses 10.0.1.30/24 ipv4.gateway 10.0.1.1
sudo nmcli con up bond0
cat /proc/net/bonding/bond0Why โ active-backup needs no switch config; mode=802.3ad (LACP) gives aggregate bandwidth but needs switch support.
Interview tip โ Test failover by pulling one cable or ip link set eno1 down.
Q109 A developer needs to access an internal web UI on a remote server that only listens on 127.0.0.1:3000. How?
Beginner
Situation read โ SSH local port forward to localhost on the remote side.
What I'd do โ
ssh -L 3000:127.0.0.1:3000 dev@server01 -N
# then open http://localhost:3000 locallyWhy โ The service stays unexposed; access is only through authenticated SSH.
Interview tip โ Mention -D 1080 (dynamic SOCKS proxy) when you need many internal services at once.
Q110 You need to copy a 500 GB directory between two servers on a 1 Gbps link as fast as possible. What do you use?
Intermediate
Situation read โ Throughput and resumability matter.
What I'd do โ
rsync -aHAX --info=progress2 --partial -e "ssh -T -c [email protected] -o Compression=no" /data/ dst:/data/For many small files, parallelise: ls /data | xargs -P4 -I{} rsync -aHAX /data/{} dst:/data/. On a trusted network, tar | mbuffer | nc avoids encryption overhead.
Why โ rsync resumes and only sends differences; a fast AES-GCM cipher with hardware support keeps CPU from becoming the bottleneck.
Interview tip โ Calculate first: 500 GB at ~110 MB/s is roughly 80 minutes, so set expectations.
Q111 Your app needs to resolve internal names like db.internal that aren't in public DNS. What options do you have on the host?
Intermediate
db.internal that aren't in public DNS. What options do you have on the host?Situation read โ Point the resolver at internal DNS, or use split DNS.
What I'd do โ
- Best: configure the internal DNS servers via DHCP or NetworkManager (
ipv4.dns). - With systemd-resolved, route only the internal domain to internal DNS:
sudo resolvectl dns eth1 10.0.0.2
sudo resolvectl domain eth1 '~internal'(persist in NetworkManager or a .network file).
3. Quick fix for one or two hosts: /etc/hosts.
Why โ Split DNS sends *.internal to internal servers and everything else to the normal resolver.
Interview tip โ Mention /etc/nsswitch.conf controls whether /etc/hosts or DNS is consulted first.
Q112 You must open SSH on a non-standard port 2222 on a RHEL server with SELinux enforcing. What steps are needed?
Intermediate
Situation read โ sshd config, SELinux port label and firewall all need changing.
What I'd do โ
sudo semanage port -a -t ssh_port_t -p tcp 2222
echo 'Port 2222' | sudo tee /etc/ssh/sshd_config.d/20-port.conf
sudo firewall-cmd --permanent --add-port=2222/tcp && sudo firewall-cmd --reload
sudo sshd -t && sudo systemctl restart sshd
ss -tlnp | grep 2222Why โ SELinux only lets sshd bind to ports labelled ssh_port_t; without it, sshd fails to start.
Interview tip โ Say a non-standard port reduces log noise but isn't real security.
Q113 Users connecting to a new server get "WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED". The server was rebuilt. How do you handle this at scale?
Advanced
Situation read โ New host keys; you need a trusted way to distribute them.
What I'd do โ
- Confirm the rebuild is real (out-of-band check of the fingerprint:
ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pubon the console). - Remove the stale entry:
ssh-keygen -R host.example.com. - Long term, sign host keys with an SSH CA and have clients trust it:
# client ~/.ssh/known_hosts
@cert-authority *.example.com ssh-ed25519 AAAA...CAServers use HostCertificate /etc/ssh/ssh_host_ed25519_key-cert.pub.
Why โ With host certificates, rebuilt servers just get a new signed cert and clients never see warnings or need TOFU.
Interview tip โ Never tell people to use StrictHostKeyChecking=no; that's exactly how MITM gets through.
Q114 You need to measure real network throughput between two data centre servers before a migration. How?
Beginner
Situation read โ Measure bandwidth, latency and loss.
What I'd do โ
# on server B
iperf3 -s
# on server A
iperf3 -c serverB -t 30 -P 4
iperf3 -c serverB -u -b 500M # UDP, shows loss and jitter
mtr -rwc 100 serverBWhy โ -P 4 uses parallel streams, which shows what the link can do when one TCP stream is limited by latency.
Interview tip โ Mention the bandwidth-delay product; high-latency links need bigger TCP windows.
Q115 A service must be reachable on a virtual IP that fails over between two Linux load balancers. How?
Advanced
Situation read โ VRRP with keepalived.
What I'd do โ
/etc/keepalived/keepalived.conf on the primary:
vrrp_script chk_haproxy {
script "/usr/bin/systemctl is-active --quiet haproxy"
interval 2
}
vrrp_instance VI_1 {
state MASTER
interface eth0
virtual_router_id 51
priority 150
advert_int 1
authentication { auth_type PASS auth_pass s3cr3t }
virtual_ipaddress { 10.0.1.100/24 }
track_script { chk_haproxy }
}Backup node: state BACKUP, priority 100. Allow VRRP (protocol 112) in the firewall.
Why โ If HAProxy dies, the priority drops and the VIP moves; neighbours learn the new MAC via gratuitous ARP.
Interview tip โ In most clouds VRRP multicast doesn't work, so use the cloud LB or an API-driven failover.
Q116 You need to capture traffic on a server to prove whether a client's requests are even arriving. How?
Intermediate
Situation read โ tcpdump with a tight filter.
What I'd do โ
sudo tcpdump -i any -nn 'tcp port 8080 and host 198.51.100.7' -c 200
sudo tcpdump -i eth0 -nn -s0 -w /tmp/cap.pcap 'port 8080' # open in Wireshark laterLook for SYN without SYN-ACK (app or firewall), or SYN followed by RST (nothing listening).
Why โ Packets on the wire are the ground truth when app logs and the client disagree.
Interview tip โ Filter tightly on busy servers or the capture itself causes load.
Q117 Your team uses password-protected SSH keys but automation needs to SSH without prompts. How do you balance the two?
Intermediate
Situation read โ Humans and machines need different keys.
What I'd do โ
- Humans: passphrase-protected keys with
ssh-agent, or FIDO2 keys (ssh-keygen -t ed25519-sk). - Automation: separate key per system, no passphrase, stored in a secret manager, restricted on the server:
from="10.0.5.0/24",command="/usr/local/bin/backup-receive",no-pty,no-port-forwarding ssh-ed25519 AAAA... ci-backup- Rotate machine keys on a schedule.
Why โ A leaked automation key can only do one thing from one network.
Interview tip โ Never reuse a person's key in CI.
Q118 You need to forward port 80 on a Linux host to a container or VM on 10.0.3.5:8080. How?
Advanced
Situation read โ DNAT plus forwarding.
What I'd do โ
sudo sysctl -w net.ipv4.ip_forward=1
sudo nft add table ip nat
sudo nft add chain ip nat prerouting '{ type nat hook prerouting priority -100; }'
sudo nft add rule ip nat prerouting iifname "eth0" tcp dport 80 dnat to 10.0.3.5:8080
sudo nft add chain ip nat postrouting '{ type nat hook postrouting priority 100; }'
sudo nft add rule ip nat postrouting ip daddr 10.0.3.5 masqueradePersist in /etc/nftables.conf and make ip_forward permanent in /etc/sysctl.d/.
Why โ DNAT rewrites the destination; masquerade makes return traffic come back through this host.
Interview tip โ Mention that locally generated traffic hits the output hook, not prerouting, so testing from the same host needs an extra rule.
Q119 Large file uploads through a VPN tunnel hang while small requests work. You're asked to fix it on the Linux router. What do you do?
Advanced
Situation read โ Classic MTU/PMTUD problem; tunnel overhead shrinks the usable MTU.
What I'd do โ
- Confirm:
ping -M do -s 1472 remotefails, a smaller size works. - Clamp TCP MSS on the router:
sudo nft add rule inet filter forward tcp flags syn tcp option maxseg size set rt mtu- Or lower the tunnel interface MTU (e.g. 1400) and make sure ICMP "fragmentation needed" isn't blocked.
Why โ Big packets exceed the tunnel MTU and get dropped silently when ICMP is filtered.
Interview tip โ "Small works, big hangs" should immediately make you think MTU.
Q120 Your SSH sessions to a remote server drop after a few minutes idle through a corporate firewall. How do you fix it?
Beginner
Situation read โ A stateful firewall times out idle connections.
What I'd do โ
Client side ~/.ssh/config:
Host *
ServerAliveInterval 60
ServerAliveCountMax 3Or server side: ClientAliveInterval 60.
Why โ Keepalive packets keep the connection entry alive in the firewall's state table.
Interview tip โ Use tmux or mosh for flaky links so your work survives drops.
Q121 You need a quick internal HTTP proxy so isolated hosts can download packages. What would you set up?
Intermediate
Situation read โ Forward proxy with an allowlist.
What I'd do โ
- Install Squid on a host with internet; in
squid.conf:
acl internal src 10.0.0.0/8
acl repos dstdomain .ubuntu.com .rockylinux.org .docker.io
http_access allow internal repos
http_access deny all
http_port 3128- On clients:
proxy=http://proxy.internal:3128in/etc/dnf/dnf.conforAcquire::http::Proxy "http://proxy.internal:3128";in apt config.
Why โ You control and log egress without giving hosts full internet.
Interview tip โ For scale, a local mirror or Artifactory/Nexus proxy repo is better than a generic proxy.
Q122 You need SSH access to a server behind NAT with no inbound ports open. How?
Advanced
Situation read โ The server must call out; use a reverse tunnel or an agent.
What I'd do โ
- Reverse tunnel from the server to a relay:
autossh -M 0 -N -o ServerAliveInterval=30 -R 2222:localhost:22 [email protected]Then from the relay: ssh -p 2222 user@localhost.
2. Run it as a systemd service so it restarts.
3. Production-grade: an outbound-only agent (AWS SSM, Teleport, Tailscale).
Why โ NAT allows outbound connections; the tunnel carries traffic back in.
Interview tip โ Mention locking down the relay with GatewayPorts no so the forwarded port isn't public.
Q123 A team wants to know who is logged in and from where on a server right now and historically. Which commands?
Beginner
Situation read โ Session accounting files plus auth logs.
What I'd do โ
w # current sessions and what they're running
who -a
last -F -n 20 # history from /var/log/wtmp
lastb | head # failed logins from /var/log/btmp
journalctl -u sshd --since today | grep AcceptedWhy โ wtmp holds logins, btmp failed attempts and the journal has the key fingerprint used.
Interview tip โ Note that an attacker with root can edit these files, so ship them off-box.
Q124 Your application opens thousands of outbound connections per second to an API and starts failing with "Cannot assign requested address". How do you tune the host?
Advanced
Situation read โ Ephemeral port exhaustion from many short-lived connections in TIME_WAIT.
What I'd do โ
- Confirm:
ss -tan state time-wait | wc -landsysctl net.ipv4.ip_local_port_range. - Fix in the app first: use connection pooling and keep-alive.
- Tune:
sudo sysctl -w net.ipv4.ip_local_port_range="10240 65535"
sudo sysctl -w net.ipv4.tcp_tw_reuse=1- Spread across more destination IPs or source IPs if needed.
Why โ Each connection needs a unique 4-tuple; with one destination IP:port you only have the ephemeral port range to vary.
Interview tip โ Never mention tcp_tw_recycle; it was removed in Linux 4.12 because it broke NAT clients.
Q125 You must make sure a server's hostname and FQDN are set correctly before joining it to a domain. How?
Beginner
Situation read โ Static hostname plus resolvable FQDN.
What I'd do โ
sudo hostnamectl set-hostname app01.corp.example.com
hostnamectl
hostname -f
getent hosts app01.corp.example.comAdd a /etc/hosts entry if DNS isn't set up yet. On cloud images, set preserve_hostname: true in cloud-init so it isn't reset.
Why โ Kerberos and many domain tools fail if the FQDN doesn't resolve.
Interview tip โ Cloud-init resetting the hostname on reboot is a common surprise.
Security, hardening and incident response
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q126 Monitoring shows a web server making outbound connections to an unknown IP on port 4444 at 2 AM. You suspect it is compromised. What do you do?
Advanced
Situation read โ Contain, preserve evidence, then investigate. Don't "clean" a live box and put it back.
What I'd do โ
- Contain: pull it out of the load balancer and restrict network at the security group/firewall to your forensic IPs only. Don't power it off yet (memory is evidence).
- Capture volatile data:
ss -tanp > /tmp/ir/conns.txt
ps auxwwf > /tmp/ir/ps.txt
ls -l /proc/*/exe 2>/dev/null | grep deleted > /tmp/ir/deleted-exe.txt
last -F > /tmp/ir/last.txt- Snapshot the disk (EBS snapshot) for offline forensics.
- Check persistence: crontabs, systemd units,
~/.ssh/authorized_keys,/etc/ld.so.preload, new users. - Rebuild from a known-good image, rotate every credential the host had, and patch the entry point.
Why โ You can't trust a compromised kernel or binaries; rebuilding is the only clean state.
Interview tip โ Say "isolate, preserve, investigate, rebuild, rotate", and that you'd involve the security team immediately.
Q127 After the compromise you need to find how the attacker got in. Where do you look?
Advanced
Situation read โ Timeline reconstruction from logs and the disk snapshot.
What I'd do โ
- Auth logs:
grep -E 'Accepted|Failed' /var/log/secure*(orauth.log), especially unusual IPs or keys. - Web logs around the first bad timestamp: strange POSTs, webshell paths,
../traversal,${jndi:. - Recently modified files on the mounted snapshot:
find /mnt/evidence -xdev -newermt "2026-11-08 00:00" ! -newermt "2026-11-09 03:00" -type f -ls- Package integrity:
rpm -Vaordebsums -cagainst the snapshot root. - Audit logs:
ausearch -ts 11/08/2026 -k exec.
Why โ The first malicious event tells you the vulnerability to fix fleet-wide.
Interview tip โ Use central logs as the source of truth, since local ones may have been tampered with.
Q128 Your CISO asks you to harden a fresh Linux server baseline. What's on your list?
Intermediate
Situation read โ Follow a benchmark and automate it.
What I'd do โ
- Patch and enable automatic security updates.
- SSH: keys only, no root, allowlisted groups.
- Remove unneeded packages and services (
systemctl list-unit-files --state=enabled). - Host firewall default-deny inbound.
- SELinux/AppArmor enforcing.
- auditd plus log forwarding; time sync with chrony.
- Mount options (
nodev,nosuid,noexecon/tmp), sysctl hardening. - Scan with OpenSCAP:
oscap xccdf eval --profile cis --report report.html /usr/share/xml/scap/ssg/content/ssg-rhel9-ds.xml.
Why โ CIS gives an auditable standard; OpenSCAP proves compliance.
Interview tip โ Say you bake the hardened baseline into the golden image, not apply it by hand.
Q129 A developer says "SELinux keeps breaking my app, can we just disable it?" How do you respond and what do you do?
Intermediate
Situation read โ Fix the policy issue, don't remove the protection.
What I'd do โ
- Find the denial:
sudo ausearch -m AVC -ts recent
sudo sealert -a /var/log/audit/audit.log # setroubleshoot- Usually it's a label or boolean:
restorecon -Rv /srv/app,semanage fcontext -a -t httpd_sys_content_t '/srv/app(/.*)?',setsebool -P httpd_can_network_connect on. - Only if nothing fits, build a small local module:
audit2allow -M myappand review it before loading. - If needed during debugging, make only that domain permissive:
semanage permissive -a httpd_t.
Why โ SELinux contains exploits; most "breakage" is a missing label after files were moved.
Interview tip โ "setenforce 0 is a diagnostic, not a fix" is the line to say.
Q130 You need to know when anyone modifies /etc/sudoers, /etc/passwd or SSH config. How?
Intermediate
/etc/sudoers, /etc/passwd or SSH config. How?Situation read โ File watch rules with auditd, shipped centrally.
What I'd do โ
/etc/audit/rules.d/50-identity.rules:
-w /etc/passwd -p wa -k identity
-w /etc/shadow -p wa -k identity
-w /etc/sudoers -p wa -k sudoers
-w /etc/sudoers.d/ -p wa -k sudoers
-w /etc/ssh/sshd_config -p wa -k sshdLoad with sudo augenrules --load, query with ausearch -k sudoers -i.
Why โ auditd records who (auid survives sudo), when and with which process.
Interview tip โ Mention auid (login UID), which shows the original user even after sudo su -.
Q131 A critical OpenSSL CVE is announced. How do you find and patch affected servers quickly?
Intermediate
Situation read โ Inventory, patch, restart the right processes.
What I'd do โ
- Find versions fleet-wide:
ansible all -m shell -a "rpm -q openssl || dpkg -l openssl". - Patch:
dnf update openssl/apt-get install --only-upgrade openssl libssl3. - Find processes still using the old library:
sudo lsof -n | grep -E 'libssl.*(deleted)'
sudo needs-restarting -s # RHEL
sudo needrestart -r l # Debian/Ubuntu- Restart those services or reboot.
- Check containers and statically linked binaries separately.
Why โ Updating the package doesn't fix processes that already loaded the old library into memory.
Interview tip โ The "(deleted)" library trick shows real experience.
Q132 How do you make sure only signed, approved packages can be installed on your servers?
Intermediate
Situation read โ GPG verification plus controlled repositories.
What I'd do โ
- Keep
gpgcheck=1(andrepo_gpgcheck=1where supported) in every.repofile; for apt, usesigned-by=keyrings. - Point servers only at an internal mirror (Satellite, Pulp, Artifactory) with approved content.
- Block direct internet egress from servers.
- Alert on
rpm -qa --qf '%{NAME} %{SIGPGP:pgpsig}\n'showing unsigned packages.
Why โ Signature checks stop tampered packages; internal mirrors control what is approved.
Interview tip โ Mention apt's move away from apt-key to per-repo signed-by keyrings.
Q133 A pen test reports your servers accept weak SSH ciphers and old key exchange algorithms. How do you fix it?
Intermediate
Situation read โ Restrict algorithms in sshd or system crypto policy.
What I'd do โ
- RHEL:
sudo update-crypto-policies --set FUTURE(or a custom policy module), then restart sshd. - Others, in an sshd drop-in:
KexAlgorithms [email protected],curve25519-sha256
Ciphers [email protected],[email protected],[email protected]
MACs [email protected],[email protected]
HostKeyAlgorithms ssh-ed25519,rsa-sha2-512- Verify:
ssh -Q kexand scan withssh-audit host.
Why โ Removing CBC ciphers, SHA-1 MACs and weak DH groups closes the findings.
Interview tip โ Check old clients (legacy Java libraries, network gear) before rollout.
Q134 You find a crypto-miner using 100% CPU under the www-data user. Beyond killing it, what do you do?
Advanced
www-data user. Beyond killing it, what do you do?Situation read โ The web app was exploited; the miner is just the symptom.
What I'd do โ
- Capture
ps,ls -l /proc/<PID>/exe,cat /proc/<PID>/cmdline,ss -tnpbefore killing. - Find persistence:
crontab -l -u www-data,/tmp,/var/tmp,/dev/shm, systemd user units,.bashrc. - Find the entry point in the web logs (RCE, upload of a webshell).
- Rebuild the server, patch the app, rotate secrets the app could read.
- Add prevention:
noexecon/tmpand/dev/shm, egress filtering, and a systemd sandbox for the web service.
Why โ If you only kill the process, the cron entry restarts it in a minute.
Interview tip โ Mention egress restriction; miners and reverse shells need outbound access.
Q135 Compliance requires that every server's file system be checked for unexpected changes daily. What do you implement?
Intermediate
Situation read โ File integrity monitoring.
What I'd do โ
sudo dnf install -y aide
sudo aide --init
sudo mv /var/lib/aide/aide.db.new.gz /var/lib/aide/aide.db.gz
sudo aide --checkSchedule aide --check daily with a timer, send reports centrally, and re-baseline after approved changes (aide --update).
Why โ AIDE hashes binaries and configs and reports differences.
Interview tip โ Store the baseline DB off-host or read-only, or an attacker just updates it.
Q136 You need to restrict which kernel modules can load, for example blocking USB storage on servers. How?
Beginner
Situation read โ modprobe blacklist plus install override.
What I'd do โ
/etc/modprobe.d/disable-usb-storage.conf:
blacklist usb-storage
install usb-storage /bin/falseUnload if loaded: sudo modprobe -r usb-storage; rebuild initramfs if needed; check with lsmod | grep usb_storage.
Why โ blacklist alone only stops auto-loading by alias; install ... /bin/false blocks explicit loads too.
Interview tip โ Mention CIS also recommends disabling rare filesystems like cramfs and udf this way.
Q137 An auditor asks you to prove which ports are open on a server and why. How do you produce that?
Beginner
Situation read โ Show listening sockets and map them to services and firewall rules.
What I'd do โ
sudo ss -tulpn
sudo firewall-cmd --list-all # or: sudo nft list ruleset / sudo ufw status verbose
nmap -sT -p- server01 # from another host, what's actually reachableDocument each port with its owning service and business reason; close anything without one.
Why โ ss shows what listens; the external nmap shows what is exposed after firewalls.
Interview tip โ Distinguish "listening on 127.0.0.1" from "listening on 0.0.0.0".
Q138 A developer accidentally committed a private SSH key used on production servers to a public GitHub repo. What do you do?
Intermediate
Situation read โ Treat the key as compromised immediately; deleting the commit isn't enough.
What I'd do โ
- Remove the public key from every
authorized_keysnow (Ansibleauthorized_key state=absent). - Issue a new key pair for the legitimate use.
- Check auth logs for that key's fingerprint from unknown IPs (
ssh-keygen -lf key.pub, then grep the fingerprint in logs withLogLevel VERBOSE). - Purge from git history (
git filter-repo) and enable secret scanning / push protection.
Why โ Bots scrape GitHub for keys within minutes.
Interview tip โ "Revoke first, clean up history second."
Q139 You need to apply kernel network hardening settings to all servers. Which sysctls and how?
Intermediate
Situation read โ Persistent sysctl drop-in.
What I'd do โ
/etc/sysctl.d/60-net-hardening.conf:
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.icmp_echo_ignore_broadcasts = 1
net.ipv4.tcp_syncookies = 1
net.ipv4.conf.all.log_martians = 1
kernel.kptr_restrict = 2
kernel.dmesg_restrict = 1Apply with sudo sysctl --system.
Why โ These stop spoofing, ICMP redirect attacks and SYN floods, and hide kernel pointers.
Interview tip โ Don't disable ip_forward on Kubernetes nodes or routers; know your host's role.
Q140 You need to give a vendor temporary root-level access to debug an appliance VM for one day. How do you control it?
Advanced
Situation read โ Time-boxed, recorded, revocable access.
What I'd do โ
- Create a user with an expiry:
useradd -e 2026-11-10 vendor1. - Grant sudo only via a dated drop-in and remove it with an
atjob:echo "rm /etc/sudoers.d/vendor1; usermod -L vendor1" | at 18:00 tomorrow. - Enable session recording (
tlog, sudolog_output, or bastion recording). - Allow their source IP only on the firewall.
- Review recordings afterwards and rotate any secrets they could see.
Why โ Access that removes itself can't be forgotten.
Interview tip โ Better: SSH certificates with an 8-hour validity, issued just for them.
Q141 How do you protect a Linux server from SSH brute-force attempts flooding the logs?
Beginner
Situation read โ Reduce exposure, then rate-limit.
What I'd do โ
- Disable password auth (brute force becomes pointless).
- Restrict SSH by source IP in the firewall or security group.
- Install fail2ban:
# /etc/fail2ban/jail.local
[sshd]
enabled = true
maxretry = 5
bantime = 1hsystemctl enable --now fail2ban; check fail2ban-client status sshd.
Why โ Keys-only stops the attack from ever succeeding; fail2ban cuts the noise.
Interview tip โ Say exposure reduction (no public SSH, use SSM/bastion) beats fail2ban.
Q142 A web app runs as www-data and you want it unable to read anything outside /var/www, even if exploited. What options do you have?
Advanced
www-data and you want it unable to read anything outside /var/www, even if exploited. What options do you have?Situation read โ Mandatory access control or systemd sandboxing.
What I'd do โ
- systemd:
ProtectSystem=strict,ProtectHome=yes,ReadWritePaths=/var/www/uploads,TemporaryFileSystem=/etc:rowithBindReadOnlyPaths=for needed files, orInaccessiblePaths=/etc/ssh /root. - SELinux: keep the default
httpd_tdomain and label only allowed contenthttpd_sys_content_t. - AppArmor (Ubuntu): profile in
/etc/apparmor.d/with/var/www/** r,andaa-enforce.
Why โ Even with code execution, the process is fenced by the kernel.
Interview tip โ Mention starting AppArmor profiles in complain mode (aa-complain) and tuning from logs.
Q143 Your organisation must ensure that root's login and every privileged command is attributable. What design do you propose?
Intermediate
Situation read โ No direct root logins; personal accounts plus sudo plus audit.
What I'd do โ
PermitRootLogin no, root password locked or vaulted.- Personal accounts from central identity; sudo via groups.
Defaults log_outputand auditd rules onexecvewithauid>=1000.pam_loginuidso the auid survivessudo su.- Forward everything to a SIEM with immutable storage.
Why โ Every root action maps back to a human.
Interview tip โ Mention that auid is set at login and can't be changed by the user afterwards.
Q144 You must scan all servers for known-vulnerable packages weekly. What do you use?
Beginner
Situation read โ Automated vulnerability scanning.
What I'd do โ
- RHEL:
dnf updateinfo list --securityor OpenSCAP with OVAL content. - Ubuntu:
pro security-statusor OVAL viaoscap. - Fleet tools: AWS Inspector, Wazuh, Qualys, or Trivy for root filesystems (
trivy rootfs /). Report to a dashboard with SLA by severity (critical in 7 days, etc.).
Why โ Patching without measurement drifts; scanning gives an auditable backlog.
Interview tip โ Mention prioritising by exploitability (CISA KEV list), not just CVSS score.
Q145 A server holds secrets in /etc/app/config.yml readable by everyone. How do you fix and prevent this?
Beginner
/etc/app/config.yml readable by everyone. How do you fix and prevent this?Situation read โ Tighten permissions now, move secrets out long term.
What I'd do โ
sudo chown root:app /etc/app/config.yml
sudo chmod 640 /etc/app/config.yml
sudo find /etc -type f -perm -o+r -name '*.yml' -exec grep -l -i 'password' {} +Rotate the exposed secrets, then move them to Vault or a cloud secret manager and enforce modes in config management.
Why โ Any local user or exploited service could read world-readable secrets.
Interview tip โ Always rotate after exposure; fixing permissions doesn't un-leak a secret.
Q146 Your team must find all SUID/SGID binaries on servers and remove unnecessary ones. How?
Intermediate
Situation read โ SUID binaries are privilege escalation targets.
What I'd do โ
sudo find / -xdev \( -perm -4000 -o -perm -2000 \) -type f -exec ls -l {} \; 2>/dev/nullCompare against a known-good baseline per distro. Remove SUID where not needed: chmod u-s /usr/bin/<tool>. Make sure nothing suid lives in /home, /tmp or /opt from unknown sources, and mount those with nosuid.
Why โ A new SUID root binary in an odd place is a classic backdoor.
Interview tip โ Mention GTFOBins as the reference for abusable binaries.
Q147 Ransomware hit a file server and encrypted shares. As the Linux admin, how do you recover?
Advanced
Situation read โ Contain, identify scope, restore from clean backups, close the entry point.
What I'd do โ
- Disconnect the share and the infected clients; stop Samba/NFS.
- Identify the start time from file mtimes and logs.
- Verify backups/snapshots are clean and from before that time (immutable or offline copies).
- Rebuild the server if it was compromised itself, restore data, rescan.
- Rotate credentials and fix the access path (often a compromised user's SMB credentials).
Why โ Restoring onto an infected host or from infected backups just re-encrypts.
Interview tip โ Mention immutable backups (S3 Object Lock, read-only snapshots) as the real defence.
Q148 How would you securely wipe a decommissioned server's disks?
Intermediate
Situation read โ Depends on media and encryption.
What I'd do โ
- If disks were LUKS-encrypted: destroy the key slots:
cryptsetup luksErase /dev/sdb(crypto-erase). - SSD/NVMe: use the drive's secure erase:
nvme format /dev/nvme0n1 --ses=1orblkdiscard --securewhere supported. - HDD:
shred -n 1 -z /dev/sdbordd if=/dev/zero. - Document serial numbers and the method for audit.
Why โ Overwriting doesn't reliably reach all SSD cells because of wear levelling; crypto-erase or firmware erase does.
Interview tip โ Cloud volumes are crypto-erased by the provider when deleted.
Q149 A user reports their account was used to log in from another country. How do you investigate?
Intermediate
Situation read โ Possible credential or key theft.
What I'd do โ
- Lock the account and kill sessions:
usermod -L user; pkill -u user. - Check logins:
last -F -i user,journalctl _COMM=sshd | grep userfor IP and key fingerprint. - Review
.bash_history,authorized_keys(new keys?), crontab and files they touched. - Rotate their keys/passwords and check other systems they access.
- Add MFA or geo/IP restrictions.
Why โ The fingerprint tells you which key was used, which narrows down where it leaked.
Interview tip โ LogLevel VERBOSE in sshd is what makes fingerprints appear in logs.
Q150 You need to prove to auditors that your servers meet CIS Level 1. How do you produce evidence repeatedly?
Advanced
Situation read โ Automated scanning and remediation as code.
What I'd do โ
- Scan with OpenSCAP and the SCAP Security Guide profile, saving reports:
oscap xccdf eval --profile xccdf_org.ssgproject.content_profile_cis_server_l1 \
--results results.xml --report report.html /usr/share/xml/scap/ssg/content/ssg-rhel9-ds.xml- Remediate using the generated Ansible playbook (
oscap xccdf generate fix --fix-type ansible). - Bake compliance into the golden image and run scans on a schedule, storing reports centrally.
- Document justified exceptions.
Why โ Auditors want consistent, timestamped evidence, not screenshots.
Interview tip โ Mention that some CIS controls break apps, so you test and record exceptions rather than applying blindly.
Packages, kernel and boot
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q151 You must upgrade the kernel on 50 production servers and be able to roll back if the new kernel misbehaves. Plan it.
Advanced
Situation read โ Kernels install side by side, so rollback is choosing the old one at boot. The risk is in the reboot itself.
What I'd do โ
- Test the new kernel on staging and a canary host for a few days.
- Make sure old kernels are kept:
installonly_limit=3in/etc/dnf/dnf.conf(apt keeps the previous one by default). - Roll out in batches: drain the host,
dnf update kernel/apt install linux-image-..., reboot, checkuname -r, health checks, re-add to the LB. - Rollback on a host:
sudo grubby --info=ALL | grep -E '^(index|kernel)'
sudo grubby --set-default /boot/vmlinuz-<old-version>
sudo reboot- Have console access ready in case the new kernel doesn't boot at all; pick the old entry from the GRUB menu.
Why โ Batches limit the blast radius; keeping old kernels makes rollback a reboot, not a reinstall.
Interview tip โ Mention grub2-reboot <entry> for a one-time boot into the new kernel, falling back automatically on the next reboot if it hangs and gets power-cycled.
Q152 You need to pin a package version so routine updates don't upgrade it (e.g. Docker or PostgreSQL). How?
Beginner
Situation read โ Version locking per package manager.
What I'd do โ
- RHEL:
sudo dnf install 'dnf-command(versionlock)'thensudo dnf versionlock add docker-ce(dnf versionlock list,deleteto remove). - Debian/Ubuntu:
sudo apt-mark hold docker-ce(apt-mark showhold,unhold).
Why โ Uncontrolled major upgrades of stateful software cause outages.
Interview tip โ Remember to unhold for security patches; a forgotten hold is technical debt.
Q153 A package update broke an application. How do you roll it back?
Intermediate
Situation read โ Downgrade to the previous version.
What I'd do โ
- RHEL:
sudo dnf history list
sudo dnf history info <ID>
sudo dnf history undo <ID>
# or: sudo dnf downgrade nginx-1.24.0-1.el9- Debian/Ubuntu:
apt list -a nginxthensudo apt install nginx=1.24.0-2ubuntu1, thenapt-mark hold nginx.
Why โ dnf history undo reverses the whole transaction including dependencies.
Interview tip โ The previous version must still be in the repo or cache, which is why internal mirrors keep old versions.
Q154 Your servers can't reach the internet but need packages. How do you provide repositories?
Intermediate
Situation read โ Internal mirror.
What I'd do โ
- On a host with internet, sync repos:
dnf reposync --repoid=baseos --download-metadata -p /srv/repos(orapt-mirror/aptlyfor Debian). - Serve
/srv/reposwith nginx. - Point clients at it in
/etc/yum.repos.d/internal.repowithgpgcheck=1. - Schedule syncs and keep dated snapshots for reproducibility.
Why โ Faster, controlled, works offline, and lets you freeze a known-good repo state.
Interview tip โ Mention Pulp, Satellite, Artifactory or Nexus as production-grade options.
Q155 You need to compile and install software from source on a server that also uses packages. How do you avoid making a mess?
Intermediate
Situation read โ Keep source builds separate from package-managed paths.
What I'd do โ
- Build in a separate directory and install to
/opt/<name>-<version>with./configure --prefix=/opt/tool-2.1. - Symlink
/opt/tool -> /opt/tool-2.1for easy upgrades. - Better: package it (
fpm,rpmbuild) so it can be removed cleanly and deployed via repo. - Don't install compilers on production; build in CI or a build container.
Why โ make install into /usr collides with package files and can't be cleanly uninstalled.
Interview tip โ Mention checkinstall or fpm for quick packaging.
Q156 You need to change kernel boot parameters (e.g. add transparent_hugepage=never) persistently. How?
Intermediate
transparent_hugepage=never) persistently. How?Situation read โ Edit the kernel command line and regenerate the bootloader config.
What I'd do โ
- RHEL 8/9:
sudo grubby --update-kernel=ALL --args="transparent_hugepage=never". - Debian/Ubuntu: add to
GRUB_CMDLINE_LINUXin/etc/default/gruband runsudo update-grub. - Reboot, verify with
cat /proc/cmdlineandcat /sys/kernel/mm/transparent_hugepage/enabled.
Why โ Some settings must be applied at boot; editing grub.cfg directly gets overwritten.
Interview tip โ Explain why DBs like MongoDB/Redis recommend disabling THP (latency spikes from compaction).
Q157 A server must apply kernel security patches without rebooting. What are your options?
Advanced
Situation read โ Live patching.
What I'd do โ
- RHEL:
kpatch(dnf install kpatch-patch-$(uname -r | ...),kpatch list). - Ubuntu: Livepatch via
pro enable livepatch,canonical-livepatch status. - Still plan regular reboots, because live patches cover only selected critical fixes.
Why โ Live patching replaces vulnerable functions in the running kernel, buying time until a maintenance window.
Interview tip โ The senior answer: design for reboots (redundancy, draining) so you don't depend on live patching.
Q158 You need to upgrade a server from RHEL 8 to RHEL 9 (or Ubuntu 22.04 to 24.04). In-place or rebuild? Plan it.
Advanced
Situation read โ Major upgrades are risky; rebuilding is often cleaner.
What I'd do โ
- Preferred: build a new RHEL 9 server from code (Terraform + Ansible), migrate data, swap traffic.
- If in-place is required:
- RHEL:
leapp preupgrade, fix inhibitors in/var/log/leapp/leapp-report.txt, thenleapp upgradeand reboot. - Ubuntu:
sudo do-release-upgradeafter full update.
- RHEL:
- Snapshot the disk before starting; test on a clone first.
- Verify services, SELinux contexts and custom repos after.
Why โ Rebuilds give a clean, reproducible host; in-place carries old cruft but keeps the IP and identity.
Interview tip โ Saying "snapshot first, test on a clone" is what interviewers want.
Q159 A new server must load a third-party kernel module (e.g. a storage driver) on boot. How?
Beginner
Situation read โ Install the module package, configure autoload.
What I'd do โ
sudo modprobe vendor_drv
lsmod | grep vendor_drv
echo vendor_drv | sudo tee /etc/modules-load.d/vendor_drv.conf
echo 'options vendor_drv queue_depth=64' | sudo tee /etc/modprobe.d/vendor_drv.confPrefer DKMS or kmod packages so the module rebuilds for new kernels.
Why โ /etc/modules-load.d/ is read by systemd-modules-load at boot.
Interview tip โ With Secure Boot, unsigned modules won't load; mention MOK signing.
Q160 You must make sure a server boots into text mode only, no GUI, and reduce boot time. How?
Beginner
Situation read โ Change the default systemd target and find slow units.
What I'd do โ
sudo systemctl set-default multi-user.target
systemctl get-default
systemd-analyze
systemd-analyze blame | head -20
systemd-analyze critical-chainDisable unneeded units with systemctl disable --now <unit>.
Why โ Targets replaced runlevels; multi-user.target is the old runlevel 3.
Interview tip โ NetworkManager-wait-online and cloud-init are common slow units.
Q161 You've forgotten the root password of a VM with console access only. How do you regain access?
Intermediate
Situation read โ Interrupt boot and get a shell before login.
What I'd do โ
- At GRUB press
e, appendrd.break(RHEL) orinit=/bin/bash(others) to thelinuxline, boot withCtrl+x. - RHEL with
rd.break:
mount -o remount,rw /sysroot
chroot /sysroot
passwd root
touch /.autorelabel # SELinux relabel
exit; exit- With
init=/bin/bash:mount -o remount,rw /,passwd, thenexec /sbin/init.
Why โ The .autorelabel step fixes the SELinux label on /etc/shadow, or nobody can log in.
Interview tip โ Mention that this is why physical/console access equals root, and GRUB passwords exist.
Q162 A cloud instance won't boot after a change and you only have the cloud console. How do you repair it?
Advanced
Situation read โ Use the serial console, or mount the root volume on a rescue instance.
What I'd do โ
- Read the boot log: EC2 "Get system log" / serial console.
- If serial console access works, boot to rescue/emergency and fix there.
- Otherwise: stop the instance, detach the root volume, attach to a rescue instance in the same AZ:
lsblk
sudo mount -o nouuid /dev/nvme1n1p1 /mnt/rescue # nouuid for XFS clones
sudo vi /mnt/rescue/etc/fstab # fix the bad change
sudo umount /mnt/rescue- Reattach as root device and start.
Why โ You can't use GRUB interactively without a console, so you fix the filesystem from another machine.
Interview tip โ Snapshot the volume before touching it.
Q163 You need to rebuild the initramfs after adding a storage driver required for boot. How?
Intermediate
Situation read โ Boot-critical drivers must be in the initramfs.
What I'd do โ
- RHEL:
echo 'add_drivers+=" vendor_drv "' | sudo tee /etc/dracut.conf.d/vendor.confthensudo dracut -f --kver $(uname -r). - Debian/Ubuntu: add
vendor_drvto/etc/initramfs-tools/modulesthensudo update-initramfs -u -k all. - Check:
lsinitrd | grep vendor_drvorlsinitramfs /boot/initrd.img-$(uname -r) | grep vendor_drv.
Why โ If the root disk driver isn't in the initramfs, the kernel can't find root and drops to a dracut shell.
Interview tip โ Also needed when moving a VM to hardware with different storage controllers.
Q164 You want to keep /boot from filling with old kernels. How do you manage that?
Beginner
/boot from filling with old kernels. How do you manage that?Situation read โ Limit installed kernels.
What I'd do โ
- RHEL:
installonly_limit=3in/etc/dnf/dnf.conf, clean up withsudo dnf remove --oldinstallonly --setopt installonly_limit=2 kernel. - Ubuntu:
sudo apt autoremove --purge. - Check usage:
df -h /bootandrpm -q kernel/dpkg -l 'linux-image*'.
Why โ A full /boot makes the next kernel install fail half-way.
Interview tip โ Never remove the running kernel (uname -r).
Q165 You need to find which package owns a file, and which files a package installed. How?
Beginner
Situation read โ Package database queries.
What I'd do โ
rpm -qf /usr/sbin/sshd # owner (RHEL)
rpm -ql openssh-server # files
dnf provides '*/bin/dig' # which package would provide it
dpkg -S /usr/sbin/sshd # owner (Debian)
dpkg -L openssh-server
apt-file search bin/digWhy โ Essential when you need to reinstall a damaged file or find what provides a missing command.
Interview tip โ rpm -V pkg / debsums pkg verify the files against the package checksums.
Q166 A developer needs a newer Python than the distro offers, without breaking system tools. What do you do?
Intermediate
Situation read โ Never replace the system Python.
What I'd do โ
- RHEL 9: install AppStream versions side by side:
dnf install python3.12. - Ubuntu: deadsnakes PPA or
uv python install 3.13. - Use virtual environments per app (
python3.12 -m venv /opt/app/venv). - Or ship the app in a container.
Why โ Tools like dnf and many system scripts depend on the platform Python; overwriting /usr/bin/python3 breaks them.
Interview tip โ Mention PEP 668 "externally managed environment" errors on new distros and that they're intentional.
Q167 You need to tune kernel parameters for a high-traffic web server. Which ones and why?
Advanced
Situation read โ Connection backlog, file handles and buffers.
What I'd do โ
/etc/sysctl.d/70-web.conf:
net.core.somaxconn = 4096
net.ipv4.tcp_max_syn_backlog = 8192
net.ipv4.ip_local_port_range = 10240 65535
net.ipv4.tcp_fin_timeout = 15
net.core.netdev_max_backlog = 16384
fs.file-max = 2097152
net.ipv4.tcp_congestion_control = bbrPlus LimitNOFILE= in the service unit and the app's own listen backlog. Apply with sysctl --system and measure before and after.
Why โ Defaults suit general workloads; bursts overflow small backlogs and drop SYNs.
Interview tip โ Say "measure first" (nstat, ss -s, listen queue overflows in netstat -s), never copy-paste tuning blindly.
Q168 You need to install a set of security tools on 100 servers with mixed distros consistently. How?
Intermediate
Situation read โ Config management with distro-aware package lists.
What I'd do โ
- hosts: all
become: true
tasks:
- ansible.builtin.package:
name: "{{ item }}"
state: present
loop: "{{ sec_packages[ansible_os_family] }}"
vars:
sec_packages:
RedHat: [audit, aide, fail2ban]
Debian: [auditd, aide, fail2ban]Why โ Package names differ across families (audit vs auditd); the generic package module picks the right manager.
Interview tip โ Mention idempotence: run it twice, second run reports no changes.
Q169 A server shows "kernel: BUG" and occasional hangs. You want a crash dump next time it happens. How?
Advanced
Situation read โ Configure kdump to capture vmcore on panic.
What I'd do โ
sudo dnf install -y kexec-tools
sudo grubby --update-kernel=ALL --args="crashkernel=auto" # or an explicit size like 512M
sudo systemctl enable --now kdump
sudo kdumpctl statusAlso panic on soft lockups/hung tasks so they produce dumps: kernel.softlockup_panic=1, kernel.hung_task_panic=1 (carefully). Analyse with crash and debuginfo, or send to the vendor.
Why โ Without a vmcore you're guessing; with it, support can find the faulty driver.
Interview tip โ Test it in a lab with echo c > /proc/sysrq-trigger, never on production.
Q170 You need to install packages on a server temporarily for debugging, and remove them all afterwards. How do you keep it clean?
Intermediate
Situation read โ Track the transaction so you can undo it.
What I'd do โ
- RHEL: install, then
dnf history undo last(or the transaction ID) when done. - Ubuntu:
apt install strace tcpdump, thenapt purge strace tcpdump && apt autoremove. - Best: use a debug container sharing namespaces (
nsenter, ortoolboxon Fedora/RHEL) so the host stays clean.
Why โ Debug tools left on production widen the attack surface and drift from the baseline.
Interview tip โ Mention immutable hosts where you never install anything, only redeploy.
Q171 You must ensure a server boots with Secure Boot enabled and still loads your custom kernel module. How?
Advanced
Situation read โ Sign the module with a key enrolled in MOK.
What I'd do โ
openssl req -new -x509 -newkey rsa:2048 -keyout MOK.priv -outform DER -out MOK.der -nodes -days 3650 -subj "/CN=Org Module Signing/"
sudo mokutil --import MOK.der # set a one-time password, reboot, enroll in MOK manager
sudo /usr/src/kernels/$(uname -r)/scripts/sign-file sha256 MOK.priv MOK.der vendor_drv.ko
mokutil --sb-stateDKMS can sign automatically with configured keys.
Why โ With Secure Boot, the kernel lockdown rejects unsigned modules ("Key was rejected by service").
Interview tip โ Keep the signing private key off the servers.
Q172 You need to schedule regular patch windows across 400 servers with minimal user impact. Design the process.
Advanced
Situation read โ Rings, automation, health checks, reporting.
What I'd do โ
- Group hosts: canary (5%), ring 1, ring 2, with HA pairs split across rings.
- Per host, an Ansible playbook with
serial: 10%: drain from LB, update, reboot if needed, wait for health checks, undrain. - Stop the rollout automatically when failures pass a threshold (
max_fail_percentage). - Freeze repos to a dated snapshot so every ring gets the same packages.
- Report compliance (patched/unpatched) to a dashboard.
Why โ Same packages everywhere, limited blast radius, automatic stop.
Interview tip โ Mentioning repo snapshots for consistency across rings sets you apart.
Q173 A newly installed service isn't enabled at boot on Debian but is on RHEL. Why might that be, and how do you standardise?
Beginner
Situation read โ Distro presets differ.
What I'd do โ
- Debian/Ubuntu usually enable and start services on install; RHEL doesn't, by preset policy.
- Check:
systemctl is-enabled svcandsystemctl preset svc. - Standardise in config management: always state
enabled: trueandstate: startedexplicitly.
Why โ Relying on distro defaults causes surprises after a reboot.
Interview tip โ Mention preset files under /usr/lib/systemd/system-preset/.
Q174 You need to roll back a whole server to its state before a risky change, not just one package. What can you use?
Advanced
Situation read โ Filesystem or volume snapshots.
What I'd do โ
- Cloud: snapshot the volume (or AMI) before the change; restore by creating a volume from it.
- LVM:
lvcreate -s -n root_pre -L 10G /dev/vg0/root; to roll back,lvconvert --merge /dev/vg0/root_preand reboot. - Btrfs/Snapper (SUSE, Fedora):
snapper create, thensnapper rollback. - For VMs: hypervisor snapshot, deleted after the change succeeds.
Why โ One step returns OS, config and packages to a known state.
Interview tip โ Snapshots aren't backups; delete them after the change because they hurt performance and fill.
Q175 You need to verify that no system binaries were tampered with after a suspected incident, without trusting the server's own tools. How?
Advanced
Situation read โ Verify against package checksums from a trusted environment.
What I'd do โ
- Snapshot the disk and mount it read-only on a clean forensic host.
- Verify using the clean host's
rpmagainst the evidence root:
sudo rpm --root /mnt/evidence -Va | grep -E '^..5' # checksum changedFor Debian: debsums -r /mnt/evidence -c or compare hashes with packages downloaded from the mirror.
3. Check /etc/ld.so.preload and loaded kernel modules in the memory capture.
Why โ A rootkit can make the compromised host's rpm and ls lie.
Interview tip โ Note that the package DB itself could be altered; downloaded packages from the official mirror are the true reference.
Migrations, performance and fleet operations
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q176 You must migrate 2 TB of application data from an old server to a new one with less than 5 minutes of downtime. How?
Intermediate
Situation read โ Copy most of the data while live, then a short final sync during a freeze.
What I'd do โ
- Initial copy while the app runs (may take hours):
rsync -aHAXS --numeric-ids --info=progress2 /srv/data/ new:/srv/data/- Repeat the same rsync a few times; each pass gets faster.
- Lower DNS TTL a day earlier.
- Maintenance window: stop the app, final
rsync ... --delete, start the app on the new server, switch DNS/LB. - Keep the old server read-only for rollback for a few days.
Why โ The final pass only moves what changed since the last pass, so downtime is minutes.
Interview tip โ Mention testing the cutover once end-to-end with a dry run (rsync -n) and measuring how long the final pass takes.
Q177 The new server has different UIDs for the same users than the old one. What breaks during migration and how do you handle it?
Intermediate
Situation read โ Files are owned by number; mismatched UIDs give files to the wrong user.
What I'd do โ
- Compare:
getent passwd appon both hosts. - Option A: create users on the new host with the same UIDs/GIDs before copying (
useradd -u 1050 -g 1050 app), then rsync with--numeric-ids. - Option B: copy and remap:
rsync --usermap=1050:2001 --groupmap=1050:2001or fix afterwards withfind / -xdev -uid 1050 -exec chown -h 2001 {} +.
Why โ Consistent UIDs across a fleet (from central identity) avoid this entirely.
Interview tip โ This is the same root cause as NFS ownership showing as nobody or wrong names.
Q178 A server is "slow" according to users. What is your first 60 seconds of investigation?
Beginner
Situation read โ Check the four resources quickly: CPU, memory, disk, network.
What I'd do โ
uptime # load trend
dmesg -T | tail # OOM, I/O errors
vmstat 1 5 # r, b, si/so, wa
mpstat -P ALL 1 3 # per-CPU
iostat -xz 1 3 # %util, await
free -h
sar -n DEV 1 3 # network throughput
top -cWhy โ This quickly tells you which resource is saturated, so you dig in the right place.
Interview tip โ Name the USE method (Utilisation, Saturation, Errors) for each resource.
Q179 Your team must capacity-plan for a server whose disk grows 4% per week. How do you predict when it fills?
Intermediate
Situation read โ Use historical metrics and alert on trends, not thresholds.
What I'd do โ
- Collect disk usage with node_exporter into Prometheus.
- Alert when the forecast says the disk will fill within a week:
predict_linear(node_filesystem_avail_bytes{mountpoint="/data"}[7d], 7*24*3600) < 0- Plan the expansion before the date, and investigate why growth is 4% weekly (retention?).
Why โ A fixed 90% threshold alerts too late on fast-growing disks and too early on stable ones.
Interview tip โ predict_linear is a great specific detail to mention.
Q180 You need to replace a physical server with a VM without changing its IP or hostname. Plan the cutover.
Intermediate
Situation read โ Build the new host with a temporary IP, then take over the identity.
What I'd do โ
- Build the VM with a temporary IP, install and configure via Ansible.
- Sync data (two-pass rsync).
- Window: stop services on the old server, final sync, shut the old server down (or change its IP).
- Reconfigure the VM with the original IP and hostname, restart networking.
- Clear stale ARP on the gateway if needed:
arping -U -I eth0 10.0.1.50(gratuitous ARP). - Run smoke tests; keep the old box powered off but intact.
Why โ Clients keep working without DNS or config changes.
Interview tip โ Mention SSH host keys: copy the old ones over or users get a "host key changed" warning.
Q181 Memory usage on a server shows 95% used but the app is fine. A manager is worried. How do you explain and verify?
Beginner
Situation read โ Linux uses free memory for page cache.
What I'd do โ
free -h # look at "available", not "free"
grep -E 'MemAvailable|Cached|Dirty' /proc/meminfo
vmstat 1 5 # si/so near 0 = no swapping pressureShow that "available" is large and swap activity is zero.
Why โ Cache is given back instantly when apps need it; unused RAM is wasted RAM.
Interview tip โ Mention PSI (cat /proc/pressure/memory) as the real signal of memory pressure.
Q182 You need to set up central logging for 200 Linux servers. Design it.
Intermediate
Situation read โ Agents on hosts, a pipeline, and a searchable store.
What I'd do โ
- Agent per host: Fluent Bit/Vector reading journald and
/var/log/*, or rsyslog forwarding over TLS:
*.* @@(o)logs.internal:6514- Buffer on disk at the agent so outages don't lose logs.
- Store in Loki, Elasticsearch/OpenSearch or a cloud service; retention per log class.
- Add labels: host, env, service.
- Alerts on key events (auth failures, OOM kills, disk errors).
Why โ Searchable history across hosts, and logs survive the host.
Interview tip โ Mention that @@ in rsyslog means TCP and @ means UDP.
Q183 A batch server is constantly swapping and the job is 10ร slower. What do you do?
Intermediate
Situation read โ The working set doesn't fit in RAM.
What I'd do โ
- Confirm:
vmstat 1(si/sohigh),sar -B(major faults),smem -s swaporgrep VmSwap /proc/*/status. - Short term: reduce concurrency or memory settings (JVM
-Xmx, worker count). - Lower
vm.swappiness(e.g. 10) if cache is pushing app pages out. - Long term: add RAM / bigger instance, or fix the job to stream data instead of loading it all.
Why โ Swapping replaces nanosecond memory access with millisecond disk access.
Interview tip โ Say you'd use cgroups (MemoryHigh) to isolate the batch job from other services.
Q184 You must benchmark a new storage volume before moving a database onto it. How?
Advanced
Situation read โ Measure IOPS, throughput and latency with a DB-like pattern.
What I'd do โ
fio --name=randrw --filename=/mnt/new/fio.test --size=10G --direct=1 \
--rw=randrw --rwmixread=70 --bs=8k --iodepth=32 --numjobs=4 \
--ioengine=libaio --runtime=120 --time_based --group_reporting
fio --name=seqread --filename=/mnt/new/fio.test --direct=1 --rw=read --bs=1M --iodepth=16 --runtime=60 --time_basedLook at IOPS, bandwidth and p99 latency (clat percentiles). Compare with the current volume using the same job.
Why โ --direct=1 bypasses the page cache so you measure the disk, not RAM.
Interview tip โ Note that cloud volumes may have burst credits; run long enough to see sustained performance.
Q185 A legacy server nobody understands must be documented before it is migrated. How do you discover what it does?
Intermediate
Situation read โ Inventory services, connections, jobs and data.
What I'd do โ
systemctl list-units --type=service --state=running
ss -tulpn # listening
ss -tnp state established # who it talks to
crontab -l; ls /etc/cron.d; systemctl list-timers
df -h; lsblk; cat /etc/fstab; showmount -e 2>/dev/null
rpm -qa --last | head -50 || ls -lt /var/lib/dpkg/info | head
ls -la /opt /srv /usr/local/binWatch connections over days (or flow logs) to catch weekly/monthly traffic.
Why โ Hidden cron jobs and rare inbound clients are what break after a migration.
Interview tip โ Mention leaving it powered off but intact for a while after cutover ("scream test").
Q186 You need to make 300 servers' configuration consistent and prevent drift. What approach do you propose?
Intermediate
Situation read โ Declarative configuration management with regular enforcement.
What I'd do โ
- Codify everything in Ansible roles in Git (users, packages, sysctl, sshd, agents).
- Run it on a schedule (AWX/Ansible Automation Platform, or
ansible-pullvia timer) in check mode to report drift, and apply mode to fix. - Changes go through pull requests and CI (
ansible-lint, Molecule tests). - Long term, immutable images: bake with Packer, replace instead of patching.
Why โ Hand-made changes get overwritten or flagged, so the fleet matches Git.
Interview tip โ Mention --check --diff to show exactly what would change.
Q187 An application has a memory leak and gets slower until restarted weekly. While devs fix it, how do you reduce impact?
Beginner
Situation read โ Contain the leak and restart in a controlled way.
What I'd do โ
- Cap memory with
MemoryMax=andRestart=on-failureso it restarts cleanly instead of pushing the host into swap. - Schedule a rolling restart across instances during low traffic (systemd timer running
systemctl restart app, one host at a time). - Graph RSS over time (
ps -o rss= -p PIDinto metrics) to give devs data.
Why โ Controlled restarts beat random OOM kills of other processes.
Interview tip โ Be clear it's a mitigation, not a fix; give devs heap dumps.
Q188 Your team wants to know which process is causing heavy disk I/O on a server. How?
Beginner
Situation read โ Per-process I/O accounting.
What I'd do โ
sudo iotop -oPa # only processes doing I/O, accumulated
pidstat -d 1 5 # kB_rd/s, kB_wr/s per process
sudo cat /proc/<PID>/ioWhy โ iostat shows the disk is busy; iotop and pidstat -d show who is making it busy.
Interview tip โ Mention that iotop needs CONFIG_TASK_IO_ACCOUNTING and root.
Q189 You need to measure where an application spends CPU time in production without restarting it. How?
Advanced
Situation read โ Sampling profiler with low overhead.
What I'd do โ
sudo perf top -p <PID>
sudo perf record -F 99 -g -p <PID> -- sleep 30
sudo perf report --stdio | head -50Generate a flame graph (perf script | stackcollapse-perf.pl | flamegraph.pl > out.svg). For runtimes: py-spy record -p PID, async-profiler for Java. eBPF tools: profile-bpfcc -F 99 30.
Why โ Sampling at 99 Hz has negligible overhead and shows hot code paths.
Interview tip โ Mention that missing symbols (no frame pointers / no debuginfo) make stacks unreadable.
Q190 A service must handle a 10ร traffic spike for a sale event next week. As the Linux admin, what do you prepare on the hosts?
Advanced
Situation read โ Remove host-level limits before they become the bottleneck.
What I'd do โ
- Load-test to find the first limit.
- Raise
LimitNOFILEfor the service,net.core.somaxconn,tcp_max_syn_backlog, ephemeral port range. - Check conntrack size if using NAT/firewalls:
net.netfilter.nf_conntrack_max. - Ensure log volume won't fill disks (rotate by size, ship off-host).
- Pre-scale instances and warm caches; confirm autoscaling and alerts.
Why โ Under 10ร load, kernel tables (fds, conntrack, backlog) overflow before CPU does.
Interview tip โ Conntrack table full ("nf_conntrack: table full, dropping packet") is a classic surprise at peak.
Q191 You need to give developers a reproducible Linux environment matching production for testing. What options do you propose?
Beginner
Situation read โ Same OS, same config, disposable.
What I'd do โ
- Containers from the same base image as production for app testing.
- Vagrant or cloud VMs built from the same Packer image and Ansible roles for OS-level testing.
- Ephemeral environments created from Terraform per branch.
Why โ "Works on my machine" usually means a different OS, library or config.
Interview tip โ Mention that the same Ansible code must build both prod and dev.
Q192 You need to decommission a server safely. What's your checklist?
Intermediate
Situation read โ Make sure nothing depends on it, then remove all traces.
What I'd do โ
- Check active connections over days (
ss -tn, flow logs) and DNS references. - Remove from LB, monitoring and backup jobs; stop services and leave powered off for a period (scream test).
- Take a final backup/snapshot as policy requires.
- Remove DNS records, config management inventory, firewall rules, certificates and secrets it used.
- Wipe disks or delete volumes; record it in the CMDB.
Why โ Orphaned DNS, firewall rules and credentials are security risks after the host is gone.
Interview tip โ Mention dangling DNS records leading to subdomain takeover.
Q193 Two servers must keep a directory in sync both ways for a simple active-active setup. What do you recommend?
Advanced
Situation read โ Bidirectional file sync is hard; conflicts are the main risk.
What I'd do โ
- Prefer removing the need: shared storage (NFS, EFS), object storage, or one writer.
- If files are rarely edited on both sides:
unisonwith a conflict policy, orlsyncdone-way per direction for separate subdirs. - For real active-active: a clustered filesystem (GlusterFS, CephFS) or DRBD with a cluster FS (complex).
Why โ Two rsync crons in opposite directions will eventually delete or overwrite new files.
Interview tip โ Saying "I'd avoid bidirectional sync" and explaining why is the senior answer.
Q194 You need to move a service from one data centre to the cloud with a database that can't have long downtime. Outline the Linux side.
Advanced
Situation read โ Replicate the data continuously and switch over at the end.
What I'd do โ
- Build cloud hosts from code; set up VPN or Direct Connect.
- Set up DB replication from the DC primary to a cloud replica (native streaming replication or AWS DMS).
- Sync static files with repeated rsync or
lsyncd. - Lower DNS TTL; run read traffic tests against the cloud.
- Cutover: stop writes, wait for replica lag to reach 0, promote the cloud replica, switch DNS, start apps.
- Keep reverse replication or the old primary as a rollback path.
Why โ Downtime becomes the time to promote and switch DNS, not the time to copy data.
Interview tip โ Mention verifying replica lag and checksums before promoting.
Q195 Your servers' clocks drift and logs from different hosts don't line up. How do you set up time sync properly?
Intermediate
Situation read โ chrony with reliable sources.
What I'd do โ
/etc/chrony.conf:
server 169.254.169.123 prefer iburst # AWS Time Sync (or your internal NTP)
pool 2.pool.ntp.org iburst
makestep 1.0 3
rtcsyncsystemctl enable --now chronyd, then check chronyc tracking and chronyc sources -v. Set every server to UTC: timedatectl set-timezone UTC.
Why โ Consistent time matters for log correlation, TLS, Kerberos and distributed databases.
Interview tip โ UTC on servers, local time only in dashboards.
Q196 A team wants containers on a Linux host but you need to keep the host OS minimal and stable. How do you set up the host?
Intermediate
Situation read โ Container host baseline.
What I'd do โ
- Minimal OS install (or a container-optimised OS such as Bottlerocket, Flatcar or Fedora CoreOS).
- Install only the runtime (containerd/Docker or Podman), monitoring and logging agents.
- Put
/var/lib/containerdor/var/lib/dockeron its own volume. - cgroup v2, SELinux/AppArmor enforcing,
user namespacesor rootless where possible. - Automate OS updates with reboots via a drain process.
Why โ Fewer packages mean fewer patches and less drift; separate storage stops image bloat filling root.
Interview tip โ Mention immutable OS options and why they suit container hosts.
Q197 You need to find which servers in the fleet still run an old OS version scheduled for end of life. How?
Beginner
Situation read โ Inventory from facts.
What I'd do โ
ansible all -m setup -a 'filter=ansible_distribution*' --tree /tmp/facts
ansible all -m shell -a 'grep -E "^(ID|VERSION_ID)=" /etc/os-release'Or query your CMDB, cloud inventory (SSM Inventory) or monitoring labels. Then build a migration plan per server with owners and dates.
Why โ EOL OS versions stop receiving security fixes.
Interview tip โ Mention specific dates you know, e.g. CentOS 7 EOL June 2024, Ubuntu 20.04 standard support ended May 2025.
Q198 You need to reduce boot-to-ready time for autoscaling instances from 6 minutes to under 1 minute. What do you change?
Advanced
Situation read โ Move work from boot time to image build time.
What I'd do โ
- Measure:
systemd-analyze blame,cloud-init analyze blame. - Bake packages, agents and app artefacts into the image with Packer; no
yum updateat boot. - Cloud-init only for instance-specific config (hostname, secrets fetch).
- Disable unneeded units; avoid
NetworkManager-wait-onlinedelays where possible. - Pre-warm: use warm pools (AWS ASG) for very fast scale-out.
Why โ Package installs and config runs at boot are the main delay.
Interview tip โ "Bake, don't fry" is a well-known phrase for this.
Q199 Your org wants to move from pets (hand-built servers) to cattle. What does that mean on Linux hosts and how do you start?
Intermediate
Situation read โ Servers become disposable and identical; state lives elsewhere.
What I'd do โ
- Externalise state: databases on managed services or dedicated volumes, logs shipped, files in object storage.
- Codify the OS: Packer images + Ansible + cloud-init.
- Deploy through autoscaling groups; replace instead of SSHing in to fix.
- Disable direct SSH by default; use SSM or break-glass only.
- Start with one stateless tier, prove it, expand.
Why โ Any host can die without data loss or a hero fixing it at 3 AM.
Interview tip โ Pick one service and describe the before/after; concrete beats theory.
Q200 After a major outage caused by a manual Linux change, management asks you to prevent a repeat. What do you put in place?
Intermediate
Situation read โ Process and tooling, not blame.
What I'd do โ
- Blameless postmortem with a timeline and contributing factors.
- All changes through code (Ansible/Terraform) with peer review and CI checks.
- Staged rollout (canary first) and automatic rollback.
- Restrict ad-hoc root via sudo rules and recorded sessions.
- Better monitoring for the failure mode that was missed, and runbooks.
Why โ Humans make mistakes; systems should make them hard to make and quick to detect.
Interview tip โ Use the word "blameless" and give a concrete action item.