Linux Notes
Linux Notes
1. Linux Distributions
A Linux distribution (or distro) is an operating system made from a collection of software based
on the Linux kernel. Distros differ in package management, default configurations, and target
audience.
1. Debian-based
o Debian: The foundation for Ubuntu, stable but slower updates.
o Ubuntu: User-friendly, commonly used for servers and desktops.
o Kali Linux: Security-focused, used for penetration testing.
2. Red Hat-based
o Red Hat Enterprise Linux (RHEL): Enterprise-grade, used in production.
o Fedora: Cutting-edge technology, upstream for RHEL.
o CentOS (Now Rocky Linux & AlmaLinux): Community-driven RHEL alternative.
3. Arch-based
o Arch Linux: Rolling release, minimalistic, user-configurable.
o Manjaro: User-friendly Arch variant.
4. Other Notable Distros
o openSUSE (SUSE-based, used in enterprises)
o Gentoo (Source-based, highly customizable)
o Slackware (One of the oldest distributions)
Directory Purpose
/ Root directory (everything starts here)
/bin Essential binaries (e.g., ls, cat, cp)
/sbin System binaries (e.g., shutdown, mount)
/etc System configuration files (/etc/passwd, /etc/fstab)
/var Variable data like logs (/var/log), spools (/var/spool)
Directory Purpose
/home User directories (/home/user1, /home/user2)
/usr User binaries and libraries (/usr/bin, /usr/lib)
/tmp Temporary files (cleared on reboot)
/opt Optional software (third-party applications)
/proc Virtual filesystem for system processes
/dev Device files (e.g., /dev/sda for disk, /dev/null)
1. Owner
2. Group
3. Others
Symbol Permission
r Read
Symbol Permission
w Write
x Execute
To check permissions:
ls -l file.txt
-rwxr-xr-- 1 user group 1234 Mar 14 12:34 file.txt
Changing Permissions
Changing Ownership
Command Action
hjkl Move left, down, up, right
Command Action
gg / G Go to beginning / end of file
w/b Move forward / backward one word
0/^/$ Start / first char / end of line
Editing in Vim
Command Action
i/a Insert / Append text
o/O Open new line below / above
dd / yy Delete / Copy line
p/P Paste below / above
:w → Save
:q → Quit
:wq or ZZ → Save & Quit
:q! → Quit without saving
Advanced Vim
Nano is simple.
Delete Lines
awk '/error/ {print $2}' log.txt → Print 2nd column if "error" found
awk '{sum+=$2} END {print sum}' file.txt → Sum of column 2
Next Steps
Want real-world exercises?
Want to dive deeper into scripting?
Want specific interview questions?
You're aiming for deep mastery of shell scripting and command-line tools, especially advanced
utilities like grep, find, xargs, cut, tr, and tee. Let’s break this down into an in-depth learning plan
that will make you interview-ready.
1. Bash Scripting Fundamentals
Before diving into advanced tools, you need to have strong fundamentals in Bash scripting.
Basic Syntax
Shebang (#!) → #!/bin/bash at the top tells the system which interpreter to use.
Comments → Use # to add comments in a script.
Executing a Script
chmod +x script.sh # Make it executable
./script.sh # Run the script
Variables
Conditionals
Common Operators:
Loops
for i in {1..5}; do
echo "Iteration $i"
done
while [ "$count" -lt 5 ]; do
echo "Count: $count"
((count++))
done
2. Process Management
Key Commands:
awk
sed
* * * * * command_to_run
│││││
│ │ │ │ └── Day of week (0 - 7) (Sunday = 0 or 7)
│ │ │ └──── Month (1 - 12)
│ │ └────── Day of month (1 - 31)
│ └──────── Hour (0 - 23)
└────────── Minute (0 - 59)
0 2 * * * /path/to/backup.sh
systemctl list-timers
Basic Search:
grep "error" logfile.txt
Case-insensitive:
grep -i "warning" logfile.txt
Recursive search in directories:
grep -r "TODO" /home/user/
Show line numbers:
grep -n "pattern" file.txt
Invert match (show lines that don’t match):
grep -v "DEBUG" logfile.txt
tr (Translate characters)
Example output:
# file: /etc/myfile
# owner: root
# group: root
user::rw-
user:john:r-- # John has read access
group::r--
mask::r--
other::---
Setting ACLs
A process has:
o Real UID (RUID): The user who started the process.
o Effective UID (EUID): The user whose permissions the process is using.
Example: Running a setuid binary (like passwd) temporarily elevates privileges.
SetUID (SUID): Allows a file to run with the privileges of the file owner.
chmod u+s /path/to/file
o Example: /usr/bin/passwd runs as root even when executed by a normal user.
SetGID (SGID): A file executes with the privileges of the group.
chmod g+s /path/to/file
o When applied to a directory, new files inherit the group.
Sticky Bit: Prevents users from deleting files they don’t own in a shared directory.
chmod +t /path/to/directory
o Used in /tmp.
Instead of full root privileges, Linux capabilities allow fine-grained control over process
permissions.
SELinux
Check status:
sestatus
List security contexts of files:
ls -Z /var/www/html/
Change security context:
chcon -t httpd_sys_content_t /var/www/html/index.html
Toggle enforcing mode:
setenforce 0 # Permissive mode
setenforce 1 # Enforcing mode
AppArmor
List profiles:
aa-status
Disable a profile:
aa-disable /etc/apparmor.d/usr.sbin.nginx
Conclusion
Mastering user management and permissions in Linux requires understanding: ✅User and
group management
✅Sudo and privilege escalation
✅Advanced ACLs for fine-grained control
✅Process ownership and security settings (SetUID, Capabilities)
✅Security contexts like SELinux and AppArmor
If you can confidently explain and apply these concepts, you’ll be ready to tackle any interview
question on Linux permissions and security! 🔹
You're aiming for an expert-level understanding of Linux file systems and storage
management—great goal! Let's break it down systematically, covering each topic in depth.
Key Concepts:
Commands:
RAID Levels:
Commands:
1. Create RAID 1 (mirroring):
2. mdadm --create --verbose /dev/md0 --level=1 --raid-devices=2 /dev/sdX /dev/sdY
3. Check RAID Status:
4. cat /proc/mdstat
Final Thoughts
Mastering these concepts will give you confidence in any Linux system administration
interview. If you need practice questions or hands-on exercises, let me know! 🔹
Got it! Let’s go really in-depth on Process & Resource Management, covering everything from
process handling and job scheduling to resource monitoring and logging. By the end of this, you
should be able to confidently answer any interview question on these topics.
1. Understanding Processes
A process is an instance of a running program. In Linux, processes are managed by the kernel
and have various states and attributes.
Viewing Processes
Killing Processes
System-Wide Monitoring
sar (System Activity Reporter): Collects and displays system resource usage.
o sar -u 1 5 → CPU usage every second for 5 times.
o sar -r 1 5 → Memory usage every second for 5 times.
4. Logging & Troubleshooting (journalctl, /var/log/)
Linux logs everything in system logs and journal logs.
Searching Logs
Intermediate Questions
Advanced Questions
9. How does journalctl work, and how do you filter logs for a specific service and time?
10. Explain the difference between at, cron, and batch scheduling.
11. If a system is running slowly, which tools would you use to diagnose the issue?
12. How do you configure log rotation for /var/log/ files?
This should give you a solid understanding of Process & Resource Management, making you
well-prepared for any interview question. Let me know if you need any further details! 🔹
The system is powered on, and the BIOS (Basic Input/Output System) or UEFI (Unified
Extensible Firmware Interface) initializes hardware components.
POST (Power-On Self Test) checks for basic hardware integrity.
If the system uses UEFI, the firmware directly loads the bootloader from the EFI
partition (/boot/efi).
If the system uses Legacy BIOS, it looks for the bootloader in the MBR (Master Boot
Record).
Command Description
systemctl list-units --type=service Show active services
systemctl status <service> Show service status
systemctl start <service> Start a service
systemctl stop <service> Stop a service
systemctl enable <service> Enable auto-start at boot
systemctl disable <service> Disable auto-start
systemctl restart <service> Restart a service
Command Description
journalctl -b Show logs from the current boot
journalctl -u <service> Show logs for a specific service
journalctl -k Show kernel logs
journalctl --since "2 hours ago" Show logs from the last 2 hours
5.1 sysctl
Example:
IP Configuration Commands
1.1. ip Command
ip is the modern replacement for ifconfig and is part of the iproute2 package.
2. Firewall Management
Firewalls control inbound and outbound traffic based on rules.
2.1. iptables
iptables is a powerful firewall tool used to filter and manipulate network packets.
2.2. firewalld
Start/enable:
systemctl start firewalld
systemctl enable firewalld
Open port 80 (HTTP):
firewall-cmd --add-port=80/tcp --permanent
firewall-cmd --reload
Enable UFW:
ufw enable
Allow SSH:
ufw allow ssh
Block an IP:
ufw deny from 192.168.1.100
Generate a key:
ssh-keygen -t rsa -b 4096
Copy the key:
ssh-copy-id user@remote_host
Disable password authentication:
PasswordAuthentication no
Install:
apt install fail2ban
Enable SSH protection:
nano /etc/fail2ban/jail.local
[sshd]
enabled = true
bantime = 600
maxretry = 3
Restart fail2ban:
systemctl restart fail2ban
Install:
apt install auditd
Monitor file changes:
auditctl -w /etc/passwd -p wa -k passwd_changes
View logs:
ausearch -k passwd_changes
This is a deep dive into Linux networking and security. Let me know if you want a specific
section expanded! 🔹
1. Package Management
A package manager is a tool that automates the process of installing, upgrading, configuring,
and removing software packages. Different Linux distributions use different package managers.
APT (Debian/Ubuntu)
3. Dependency Management
Dependencies are shared libraries or other programs that software requires to run.
Checking Dependencies
Final Notes
Mastering package management and compilation from source is key for Linux administration.
Practicing ldd, strace, and compiling real-world applications will make you an expert. Would you
like any hands-on exercises or a mock interview?
Alright! Let's go deep into Virtualization & Containerization in Linux, covering every aspect in a
way that prepares you for any interview. We'll break it down systematically with detailed
explanations, commands, architecture insights, and potential interview questions.
1. Virtualization in Linux
Virtualization allows multiple operating systems (guests) to run on a single physical machine
(host). It's achieved using hypervisors that abstract hardware resources.
Types of Virtualization
Type Description Examples
Turns the Linux kernel into a hypervisor using the /dev/kvm module.
Utilizes hardware virtualization (Intel VT-x, AMD-V).
Works with QEMU for full emulation.
Managed using libvirt (via virsh & virt-manager).
Output:
Debian/Ubuntu:
RHEL/CentOS:
KVM Networking
sudo nmcli connection add type bridge ifname br0 con-name br0
1.3 VirtualBox
A Type-2 hypervisor (runs on top of an OS).
Features Snapshots, Bridged Networking, Shared Folders.
Uses Guest Additions for better performance.
1.4 VMware
Workstation Pro (desktop) & ESXi (enterprise).
Uses VMware Tools for performance optimization.
2. Containerization in Linux
Containers provide process-level isolation by sharing the same OS kernel but keeping
applications isolated.
2.1 Docker
Docker is the most popular container runtime.
Install Docker
Run a container:
docker run -d --name mynginx -p 8080:80 nginx
List running containers:
docker ps
Stop and remove a container:
docker stop mynginx && docker rm mynginx
Pull an image:
docker pull ubuntu:latest
Docker Storage
Install Podman
Run a Container
3. Kubernetes (K8s)
LXC (Linux Containers) is OS-level virtualization that behaves like full Linux systems.
Install LXD
sudo apt install lxd -y
lxd init
KVM
Docker
Kubernetes
🔹 If you want real-world scenarios, I can guide you through advanced networking, persistent
storage, or CI/CD pipelines with Kubernetes! Let me know how deep you want to go.
Got it! Let's break down each of these advanced security and hardening techniques in-depth so
you can confidently answer any interview question.
Developed by the NSA, SELinux provides granular control over system processes and files
through labeling and policy enforcement.
Modes of Operation:
o Enforcing: Policies are actively applied (default on many distributions like RHEL).
o Permissive: Logs policy violations but doesn’t enforce them (useful for
debugging).
o Disabled: SELinux is turned off (not recommended for security-critical
environments).
Key Concepts:
o Security Contexts: Every file, process, and user has a security context (e.g.,
user_u:role_r:type_t).
o Policy Rules: Define how subjects (users/processes) can interact with objects
(files/directories).
o Booleans: Toggle specific policy settings without changing the policy file
(getsebool -a).
o Tools:
semanage: Manages SELinux policies.
restorecon: Restores default SELinux contexts.
audit2allow: Converts denied actions into policy rules.
Example:
ls -Z /var/www/html/index.html
Output:
unconfined_u:object_r:httpd_sys_content_t:s0
This means Apache (httpd_t) can read this file due to the httpd_sys_content_t label.
Key Features:
o Uses profile files (/etc/apparmor.d/) to enforce security policies.
o Profiles define which files and capabilities a process can access.
o Less granular than SELinux but easier to configure.
Common Commands:
o aa-status: Check the status of AppArmor.
o aa-enforce /path/to/profile: Enforce a profile.
o aa-complain /path/to/profile: Switch to permissive mode.
Example Profile (/etc/apparmor.d/usr.sbin.nginx):
/usr/sbin/nginx {
include <abstractions/base>
/var/www/html/ r,
/var/www/html/* r,
/usr/sbin/nginx ix,
}
Comparison:
| Feature | SELinux | AppArmor | |---------------|--------|---------| | Complexity | High |
Lower | | Flexibility | High | Moderate | | Granularity | Process/File | Process-Level | |
Ease of Use | Complex | Easier |
Syntax:
scp file.txt user@remote:/path/
scp -r directory/ user@remote:/path/
Encrypt a file:
gpg -c secret.txt
Decrypt a file:
gpg secret.txt.gpg
OpenSSL
Restrict applications:
firejail --private firefox
chroot
bubblewrap
Summary Table
Security Tool Purpose
SELinux Granular MAC enforcement
AppArmor Profile-based security
auditd Logs security-relevant events
AIDE Detects unauthorized file changes
scp Secure file transfer
rsync Efficient remote sync
sftp Interactive secure file transfer
GPG File encryption
OpenSSL Cryptographic toolkit
LUKS Full disk encryption
Firejail Application sandboxing
chroot Process isolation
bubblewrap Lightweight sandboxing
Final Thoughts
This should give you a solid foundation in Linux security hardening! If you need real-world
examples, deeper troubleshooting, or practice interview questions, let me know! 🔹
Got it! Let's go deep into Linux kernel internals and device drivers. Here's how I'll break it down
for you:
Apply a patch:
patch -p1 < my_patch.diff
Generate a patch:
diff -u original.c modified.c > my_patch.diff
/proc
Example:
cat /proc/cpuinfo | grep "model name"
/sys
Example:
cat /sys/class/net/eth0/address
lsmod
Loading a Module
modprobe module_name
or
insmod module_name.ko
Unloading a Module
rmmod module_name
#include <linux/module.h>
#include <linux/kernel.h>
MODULE_LICENSE("GPL");
MODULE_AUTHOR("You");
MODULE_DESCRIPTION("A simple kernel module");
Create a Makefile:
obj-m += hello.o
KDIR := /lib/modules/$(shell uname -r)/build
all:
make -C $(KDIR) M=$(PWD) modules
Compile:
make
This is just the start! Do you want more in-depth explanations on any of these?
Performance tuning and optimization is a crucial skill, especially for system administrators,
DevOps engineers, and software developers working with high-performance applications. I'll
break this down into three major categories:
1. System Profiling
2. Disk and I/O Performance Tuning
3. Memory Management and Tuning
Each section will cover the tools, their usage, and how to interpret results effectively.
1. System Profiling
System profiling involves monitoring the performance of various system components, such as
CPU, memory, disk, and network. Some essential tools include:
What is perf?
perf is a powerful Linux profiling tool used for analyzing CPU usage, identifying performance
bottlenecks, and measuring function execution times.
Installation
Basic Usage
This lists all the hardware and software events that can be monitored.
Advanced Usage
What is strace?
strace is used to trace system calls made by a process. It’s useful for debugging performance
issues.
Basic Usage
Interpreting Results
High open() calls? → Too many file accesses, optimize disk I/O.
High read()/write() calls? → Possible inefficient data handling.
Frequent poll() or select() calls? → Bottlenecks in I/O-wait operations.
What is lsof?
What is iostat?
iostat helps monitor disk usage, I/O wait times, and throughput.
Installation
Basic Usage
iostat -x 1 5
Interpreting Results
What is fio?
Installation
Basic Usage
Key Metrics
Basic Usage
free -m
Key Issues
What is vmstat?
Basic Usage
vmstat 1 5
Key Metrics
swapon --summary
sudo swapoff -a
Tune swappiness
Summary
Tool Purpose
perf CPU profiling
strace System call tracing
lsof List open files
iostat Disk performance monitoring
fio Disk benchmarking
free Memory usage monitoring
vmstat Virtual memory statistics
swapoff Disable swap
This is just the start. Mastering these tools involves continuous practice—try running them in
real scenarios, analyze the outputs, and optimize accordingly.
Let me know if you want mock interview questions on this! 🔹