Linux Chapter With TOC OCR
Linux Chapter With TOC OCR
Minix, developed by
Andrew Tanenbaum
1987
1969 1987
Unix was created Linus Torvalds,
at Bell Labs by
built Linux as a
Dennis Ritchie
and Ken personal project.
Thompson
Why Linux Rocks
● The GNU Project championed the idea of free software (freedom, not price).
● Created the GPL (GNU General Public License) to ensure software freedom.
● Inspired the open-source movement, which drives modern software
development.
What Makes Linux Tick? Think of it Like a Restaurant
What happen once you push the Power button to turn on your computer?
● Deep dive into the init process: What it is, how it works, and why it matters.
● Understanding systemd, the modern init replacement.
Introduction to the init Process
SysV init: Works by using runlevels to control which services start at boot. Each
runlevel represents a different system state (e.g., multi-user mode, single-user mode).
Init scripts: In SysV init, scripts located in /etc/init.d/ or /etc/rc.d/ define which
services start.
Runlevels:
● Runlevel 0: Halt (shuts down the system)
● Runlevel 1: Single-user mode (for system maintenance)
● Runlevel 3: Multi-user mode (text-based login)
● Runlevel 5: Multi-user mode (graphical login)
● Runlevel 6: Reboot
Systemd vs SysV Init: Modern Targets vs Traditional Runlevels
Systemd (Modern)
● Replaces runlevels with target units.
Example Targets:
○ multi-user.target: Multi-user mode.
○ graphical.target: Graphical mode.
Key Improvement
● Targets are more descriptive and flexible, enabling faster boot times and custom
system states.
Systemd vs SysV
SysV Runlevel systemd Target Description
Replaces older init systems like SysV init to manage services, processes, and
system boot.
Example commands:
Examples:
systemd uses journald to manage logs for services and system processes.
Example commands:
● useradd abe
● usermod -aG sudo abe
● userdel -r abe
Group Management
Diagram ✅
Understanding File Permissions
Every file has read (r), write (w), and execute (x) permissions.
Example:
● rwxr-xr-- means:
○ rwx for the owner.
○ r-x for the group.
○ r-- for others.
Changing Permissions and Ownership
Example:
● Setuid (chmod u+s): Executes the file with the permissions of the file owner.
● Setgid (chmod g+s): Files created in a directory inherit the group of the
directory.
● Sticky Bit (chmod +t): Only the owner can delete or modify files in a directory.
Diagram ✅
Managing Privileges with sudo
Commands:
1. user: The specific user account or group you’re granting sudo permissions to.
2. The first "ALL":
○ Meaning: This means that the user can run commands on all hosts (useful in
multi-host setups). If you’re only administering a single machine, this means "all
commands on this machine."
3. The (ALL:ALL) part:
○ The first "ALL" (inside the parentheses): This represents the target user. It means
the user can execute commands as any user on the system (including root).
○ The second "ALL" (inside the parentheses): This represents the target group. It
means the user can execute commands as any group.
4. The last "ALL":
○ Meaning: This means that the user can run all commands (as opposed to
specifying particular commands).
File Systems
and Storage
Management
Understanding Linux File Systems
A file system manages how data is stored and retrieved from a disk.
It starts with the root / directory, which contains other key directories like
/bin, /etc, /var, etc.
Diagram ✅
Managing Swap Space
Swap ????
Common tools:
Best practice: Regularly monitor and clean up disk space to avoid downtime.
File System Troubleshooting
What is LVM?
Diagram ✅
Setting Up and Managing LVM
● Example commands:
○ pvcreate /dev/sda1: Create a physical volume.
○ vgcreate myvg /dev/sda1: Create a volume group.
○ lvcreate -L 10G -n mylv myvg: Create a logical volume.
○ mkfs.ext4 /dev/myvg/mylv: Format the logical volume with a file system.
○ mount /dev/myvg/mylv /mnt: Mount the logical volume.
● Resizing logical volumes:
○ lvextend -L +5G /dev/myvg/mylv: Increase the size of the logical volume.
○ resize2fs /dev/myvg/mylv: Resize the file system to match the logical
volume.
Monitoring LVM
Diagram ✅
Managing Process Priorities with nice and
renice
Example commands:
Diagram ✅
Monitoring Processes with top and htop
Diagram ✅
Top, detail …
top, go deep to resources
Managing Processes with ps and kill
● ps: Lists processes running on the system. Use it to get details about
processes.
○ ps aux: List all running processes with details.
● kill: Sends signals to terminate or control processes.
○ kill -9 PID: Forcefully terminate a process.
● Key Concepts:
○ PID: Process ID, used to manage specific processes.
○ Signals: Control how processes are managed, such as termination
(SIGKILL) or stopping (SIGSTOP).
Diagram ✅
Managing Services with systemd
Diagram ✅
Summary of Process Management and
Monitoring
Best Practice: Monitor critical processes regularly and use tools like strace and
lsof during incident response to pinpoint problems.
Shell Scripting
Introduction to Shell Scripting
Defining a variable:
● my_var="Hello, World!"
● Accessing the variable: echo $my_var
Example:
name="Abe"
echo "Hello, $name!"
Diagram ✅
Conditionals in Shell Scripts
What is an if statement?:
if [ condition ]; then
# Commands to execute if condition is true
else
# Commands to execute if condition is false
fi
Understanding “if” Statements
Common conditions:
● Check if a file exists: [ -e /path/to/file ]
● Compare numbers: [ $var -eq 5 ]
● String comparisons: [ "$var" = "Hello" ]
Real-world Example:
● A script that checks if a directory exists before creating it:
if [ -d "/backup" ]; then
echo "Backup directory exists."
else
mkdir /backup
echo "Backup directory created."
fi
Loops in Shell Scripts
Understanding “for” Loops in Shell Scripting
● A for loop iterates over a list of items and executes commands for each
item.
● The basic structure is:
Real-world Example:
This loop iterates over each .log file in the /var/log directory and compresses it.
Understanding “while” Loops in Shell Scripting
while [ condition ]; do
# Commands to execute
done
Understanding “while” Loops in Shell Scripting
Real-world Example:
counter=1
while [ $counter -le 5 ]; do
echo "Counter: $counter"
((counter++))
done
Understanding “while” Loops in Shell Scripting
What is cron?:
What is crontab?:
● crontab is the cron table where you define the schedule for cron jobs.
● crontab file contains a list of cron jobs and their schedules for a user or
system.
Scheduling Jobs with Cron
● User crontabs: Each user can have their own crontab file, edited with
crontab -e. These are stored in /var/spool/cron/crontabs (exact location
may vary depending on the distribution).
● System-wide crontab: Located at /etc/crontab, this file is used for
scheduling system-wide tasks.
● Other cron directories:
○ /etc/cron.hourly, /etc/cron.daily, /etc/cron.weekly, and
/etc/cron.monthly allow for scheduling scripts to run at hourly, daily,
weekly, or monthly intervals.
Crontab Syntax:
● * * * * * /path/to/script.sh
○ Minute (0-59)
○ Hour (0-23)
○ Day of the Month (1-31)
○ Month (1-12)
○ Day of the Week (0-7, where 0 and 7 are both Sunday)
● Example: Run a backup script daily at midnight:
○ 0 0 * * * /home/user/backup.sh
Managing crontab:
● Edit crontab: crontab -e
● View crontab: crontab -l
● Remove crontab: crontab -r
Scheduling Jobs with Cron
Each user has their own crontab file, where scheduled jobs are defined.
Crontab format:
0 0 * * * /home/user/backup.sh
Yeah … still Cron … but last one!
○ User crontabs are specific to each user and are edited using crontab -e. These
tasks run with the user's permissions.
○ System-wide crontab (/etc/crontab) can include tasks that affect the whole
system and specify the user who should run the command.
3. Crontab Management:
○ Using crontab -e to edit the crontab file is safer than manually editing the file in
/var/spool/cron/crontabs.
○ The cron directories (/etc/cron.*) are often used for simple scripts that should
run on a regular basis without needing to edit the crontab file directly.
I lied … this is the last one :)
Reminder:
● Automate those repetitive tasks and make your life easier—just set it and
let cron handle the rest!
Scheduling One-Time Jobs with “at”
Example:
at 3:00 PM tomorrow
at> /path/to/script.sh
Use cases: Running tasks later without having them repeat, e.g., restarting a server, running maintenance scripts.
Why It Matters:
● CPU Utilization
● Memory Usage
● Disk I/O
● System Limits
Monitoring CPU and Memory with “top” and “free”
top:
free:
● Displays total, used, free, and available RAM and swap space.
● Example: free -h gives a human-readable summary of memory usage.
Monitoring Disk I/O with “iostat”
iostat:
● Part of the sysstat package, it helps monitor disk I/O and CPU
performance.
● Provides statistics on disk reads/writes and CPU load.
● Example: iostat -x 5 provides extended I/O stats every 5 seconds.
Key Metrics:
vmstat:
● Reports information about processes, memory, paging, block I/O, and CPU
activity.
● Example: vmstat 5 displays system stats every 5 seconds.
● Key metrics:
○ r: Number of runnable processes (CPU queue length).
○ si/so: Swap-in and swap-out rates.
○ us/sy/id: CPU time spent in user/system/idle.
System Resource Monitoring with “vmstat”
and “sar”
sar:
Load Average:
CPU Utilization:
Diagram ✅
Understanding ulimit
What is ulimit?
● ulimit is a shell command that allows you to control user-level resource limits on a
Linux system.
● These limits are essential for preventing resource exhaustion, such as excessive
CPU usage or too many open files, which can degrade system performance.
Basically it shows the max size/number of buffer size, core files, scheduling priority, file
locks, threads ...
Understanding ulimit
Hands-On Example: Adjust the open file limit and apply it:
● fs.file-max: Sets the maximum number of file handles the kernel can allocate.
○ Example: sysctl -w fs.file-max=100000
○ Relevance: Essential for applications that need to open many files simultaneously,
like large databases or logging systems.
Understanding sysctl
net.core.somaxconn = 1024
vm.swappiness = 10
fs.file-max = 100000
Pro Tip: Always test sysctl changes in a staging environment before applying
them in production.
Best Practices for Using ulimit and sysctl in Production
Understand how to use ulimit and sysctl to optimize system performance for
production environments.
● Logs provide a record of system activities and errors, making them crucial
for diagnosing issues.
● Proactive log monitoring helps prevent issues from escalating into critical
incidents.
Focus Areas:
What is /var/log/?
Example:
What is journalctl?
Key Commands:
● View all logs: journalctl -xe (shows logs with extra detail).
● Filter logs by time: journalctl --since "2023-10-01" --until "2023-10-02"
● View logs for a specific service: journalctl -u nginx
● View logs from the previous boot: journalctl -b -1
Using journalctl for Systemd Logs
Example:
journalctl -p crit
Managing Logs with logrotate
What is logrotate?
● A tool that automatically rotates, compresses, and deletes log files based on specified
criteria.
● Helps prevent log files from consuming too much disk space over time.
● Typically used for logs in the /var/log/ directory but can be configured for any log file.
Key Features:
● Rotation: Renames old log files and creates new ones (e.g., syslog becomes syslog.1).
● Compression: Compresses old logs to save space (e.g., .gz format).
● Retention: Keeps a specified number of old log files before deleting them.
● Custom Schedules: Rotate logs daily, weekly, monthly, or based on file size.
Managing Logs with logrotate
Configuration:
● Default configuration is in /etc/logrotate.conf.
● Custom configurations for specific services can be placed in
/etc/logrotate.d/.
Use Compression:
● Compressing logs saves disk space, especially for logs that contain a lot of text data.
● Use compress in the configuration to automatically gzip old logs.
Boot Failures:
● Use dmesg and journalctl to check kernel logs for errors during boot.
● Look for error messages related to hardware or missing files.
● Example: journalctl -b to see logs from the latest boot.
System Crashes:
Hands-On Example:
Scenario: A web server is slow to respond. How do you diagnose the issue?
Step-by-step Analysis:
Outcome: Identify and resolve a misconfigured firewall that was slowing down the
server's response time.
Yes, …You did it!