Professional Documents
Culture Documents
Linux+ Notes
Linux+ Notes
COMPTIA
LINUX+
STUDY
NOTES
Table of Contents
Performing Basic Linux Tasks ...................................................................................................... 6
Identify the Linux Design Philosophy ........................................................................................ 6
Enter Shell Commands ............................................................................................................. 7
Get Help with Linux ................................................................................................................... 9
Managing Users and Groups ...................................................................................................... 10
Assume Superuser Privileges ................................................................................................. 10
Create, Modify, and Delete Users ........................................................................................... 11
Create, Modify, and Delete Groups ......................................................................................... 12
Query Users and Groups ........................................................................................................ 13
Configure Account Profiles ...................................................................................................... 14
Managing Permissions and Ownership ...................................................................................... 15
Modify File and Directory Permissions .................................................................................... 15
Modify File and Directory Ownership ...................................................................................... 16
Configure Special Permissions and Attributes ........................................................................ 16
Troubleshoot Permissions Issues ........................................................................................... 17
Managing Storage ....................................................................................................................... 18
Create Partitions ...................................................................................................................... 18
Manage Logical Volumes ........................................................................................................ 19
Mount File Systems ................................................................................................................. 20
Manage File Systems .............................................................................................................. 21
Navigate the Linux Directory Structure .................................................................................... 22
Troubleshoot Storage Issues .................................................................................................. 23
Managing Files and Directories .................................................................................................. 26
Create and Edit Text Files ....................................................................................................... 26
Search for Files ....................................................................................................................... 27
Perform Operations on Files and Directories .......................................................................... 28
Process Text Files ................................................................................................................... 29
Manipulate File Output ............................................................................................................ 30
Managing Kernel Modules .......................................................................................................... 32
Explore the Linux Kernel ......................................................................................................... 32
Install and Configure Kernel Modules ..................................................................................... 33
Monitor Kernel Modules .......................................................................................................... 34
● While often used interchangeably, some distinguish between the terms. Free software
emphasizes user rights, while open source focuses on collaboration.
● "Free" here refers to freedom, not monetary cost.
● The term "free and open source software" (FOSS) is used to encompass both values.
● The GNU Project, led by Richard Stallman, initiated the free software movement.
● The GNU General Public License (GPL) enforces copyleft, meaning derivatives must
also be under the same license.
● Linux adheres to the Unix philosophy, emphasizing simplicity, modularity, and individual
tools that do one thing well.
● Interactivity, handling input/output streams, and favoring limited functionality are key
aspects.
GNU/Linux
Linux Distributions
● Instead of an official "Linux" OS, there are various Linux distributions (distros) based on
the Linux kernel.
● Distros differ in the software they add on top of the kernel, community support, release
schedules, and more.
● Some popular distros include Slackware, Debian, Ubuntu, Kali Linux, Red Hat, CentOS,
Fedora, openSUSE, and Arch Linux.
● In Linux, users interact with the system through text commands entered at a prompt.
● The CLI presents a command prompt, and users enter commands to interact with the
system.
● Command-line administration is vital for Linux administrators, while regular users often
rely on graphical interfaces.
Shells
● A shell acts as an interpreter between users and the kernel, facilitating command input
and output.
● Common CLI-based shells include Bourne shell (sh), Bash (bash), C shell (csh),
KornShell (ksh).
Bash Syntax
Errors
Superuser Commands
Shell History
Tab Completion
● Bash supports tab completion for quick and error-free command, file, and directory input.
/usr/share/doc/
Online Documentation
● Official distro documentation: Provided by popular Linux distributions for specific distro-
related information.
● Linux Documentation Project (LDP): Offers comprehensive Linux documentation,
including HOWTOs, Guides, FAQs, and more.
● Linux man-pages project: Provides official man pages for Linux kernel and C library
interfaces.
● GNU coreutils manual: The source for documentation on GNU core utilities included in
Linux distributions.
Interactive Help
Superuser
● Root account serves as the local administrator and security context for some
applications.
● Logging in directly as the root user is discouraged due to its extensive privileges.
● "Principle of Least Privilege" suggests giving users the minimum necessary access for
their tasks.
The su Command
● Enables users to edit files with their credentials, even if the file requires root privileges.
● Must be configured in the /etc/sudoers file.
● The syntax is sudoedit [options] {file name}.
● Many Linux distributions disable the root account for users and grant administrative
privileges through the wheel group.
● Members of the wheel group can use sudo to perform administrative tasks.
● Membership in the wheel group should be carefully controlled.
● Modern storage location for hashed passwords and additional account info.
● Only root has access to its content for enhanced security.
● Prevents users from accessing each other's password hashes.
● Fields include User name, Password hash, Days since password changed (from 01-01-
1970), Days before password must be changed, Days until user is warned to change
password, Days after password expires for account disablement.
● Creates a group.
● By default, the group has no members and no password.
● Syntax: groupadd [options] [group names].
who Command:
● who provides details about users currently logged into the system.
● Shows user names, system names, and login times.
● Use -u option to see how long users have been idle.
w Command:
last Command:
id Command:
.bash_profile File:
/etc/skel/ Directory:
/etc/profile File:
/etc/profile.d/ Directory:
/etc/bashrc File:
Permission Attributes:
Permission Contexts:
● Owner (u)
● Group (g)
● Other (o)
Permission String:
chmod Command:
Symbolic Mode:
Absolute Mode:
● Ownership determines who can apply and modify permissions on a file or directory.
● The owner of a file or directory is the user who created it.
● By default, only the owner (or superuser) can change the permissions of an object.
chown Command:
chgrp Command:
● Special permissions are used when normal permissions are not enough.
● They allow users to execute files with the privileges of the file's owner or group
temporarily.
● SUID (Set User ID) allows users to execute a file with the privileges of the owner.
● SGID (Set Group ID) allows users to execute a file with the privileges of the group
owner.
● These permissions are set using chmod and are indicated by "s" in the execute position.
Sticky Bit:
● Sticky bit ensures that only the owner or root can delete a file or directory.
● Set using chmod and indicated by "t" or "T" (if execute permission is not set) in the
execute position.
File Attributes:
● File attributes allow you to customize the system's interaction with files.
● Examples include read-only, automatic compression, saving when deleted, and
immutability.
Immutable Flag:
● The immutable flag prevents files from being modified, even by the root user.
● Set with chattr and shown as "i" in file attributes.
● ACLs allow for more granular control over permissions beyond traditional owner and
group.
● getfacl retrieves ACL information, and setfacl modifies ACLs.
● ACLs are formatted as "u:{user}:{permissions}" for users and "g:{group}:{permissions}"
for groups.
Permissions Troubleshooting:
● When facing permissions issues, verify object permissions and ownership using the ls
-al command.
● Ensure users have the necessary permissions and do not have access beyond what
they should.
● Check for the immutable flag, SUID permissions for executables, and sticky bits on
directories.
● Ensure correct owner and owning group settings.
● Set the SGID permission on a directory to make new files inherit its group ownership.
● Use groups {user name} to check a user's group membership.
● Modify group membership when needed to grant or restrict access to specific users.
Managing Storage
Create Partitions
● Setting XFS file system labels: Use the command xfs_admin -L {label name}
/dev/{device name}{partition number}.
● Partitions: Divisions of storage drives that act as separate logical drives, enhancing data
organization. Partitions need formatting and file system assignment.
● Partition Tables: Used to identify partitions; stored in the drive. Partition size cannot
exceed free space.
● Types of Partitions: Three types - Primary (one file system or logical drive, e.g., boot
partition), Extended (contains logical drives), Logical (created within an extended
partition, no set limit but typically limited to 12 per drive).
● Swap Space: A partition for out-of-memory situations, typically twice the RAM capacity.
● fdisk Utility: Menu-driven tool for partition management, supporting DOS and Linux
partition tables.
● fdisk Syntax: fdisk [options] {device name}
● GNU Parted: Useful for creating, destroying, and resizing partitions.
● GNU Parted Syntax: parted [options] {device name}
● partprobe Command: Updates the kernel with changes in the partition table without
rebooting.
● partprobe Syntax: partprobe [options] [device name]
● mkfs Command: Builds a Linux file system on a device or partition.
● mkfs Syntax: mkfs [options] {device name}
● fstab File: Stores information on storage devices and partitions to specify where and how
partitions should be mounted.
● /dev/ Directory: Contains files representing and supporting attached devices, following
naming conventions.
● /dev/disk/by- Identifiers: Persistent naming schemes like by-id, by-path, and by-uuid
used to identify devices more predictably.
● Device mapping is the process of abstracting physical storage devices into virtual
storage devices.
● Linux uses the device mapper to create virtual devices and manage data transfer
between virtual and physical devices.
● Device mapper is used for tasks like volume encryption and integrity checking services.
DM-Multipath:
● DM-Multipath is a Linux kernel feature that enhances redundancy and performance for
block storage devices.
● It uses the device mapper to provide multiple I/O paths between the CPU and storage
devices.
● If one path fails, DM-Multipath switches to another available path, ensuring device
availability for reading and writing.
mdadm Command:
● LVM is an application of the device mapper that maps physical devices and partitions
into virtual containers called volume groups.
● Volume groups contain one or more logical volumes, which become the storage devices.
● LVM advantages include dynamic volume operations, easier management, mapping
across multiple physical devices, and creating snapshots.
/dev/mapper/ Directory:
LVM Tools:
● LVM tools are categorized into physical volume (PV) tools, volume group (VG) tools, and
logical volume (LV) tools.
● The mount command is used to load a file system to a specified directory to make it
accessible to users and applications.
● You need to specify both the device to mount and the desired mount point.
● Mount options, such as auto, noauto, nouser, user, exec, noexec, ro, rw, sync, and
async, can be specified.
● These options are often included in the /etc/fstab file for automatic mounting during
system startup.
Binaries:
● Binaries are source code compiled into executable programs or files readable by the
computer system.
● The umount command is used to unmount a file system after it has been mounted.
● The file system must not be in use when unmounting.
● Common umount command options include -f (force unmounting despite issues), -l
(perform a "lazy" unmount), -R (recursively unmount directories), -t {fs type}
(unmount specific file system types), -O {mount options} (unmount file systems with
● Lists the status of all currently mounted file systems in a format similar to fstab.
● Represents the status of mounted objects as reported by the Linux kernel.
● Used to obtain details about currently mounted file systems.
● Displays information about all block storage devices available on the system.
● Provides details such as names, major and minor numbers, size, device type, and mount
points.
● Similar to lsblk, it prints each block device in a flat format and includes additional
information like device/partition UUID and file system type.
● Use lsblk -f for additional information.
● Tools for managing ext file systems, such as ext2, ext3, and ext4, include e2fsck,
resize2fs, tune2fs, and dumpe2fs.
● Dumps ext2, ext3, and ext4 file system information, including superblock and block
group information.
● Useful for troubleshooting faulty file systems.
XFS Tools:
● Tools for working with the XFS file system include xfs_info, xfs_admin,
xfs_metadump, xfs_growfs, xfs_copy, and xfs_repair.
● Linux file system includes regular files (text, executables), directories, special files (block
or character), links, domain sockets, and named pipes.
● Represented by letters in the ls -l command output (d for directories, b/c for special
files, l for links, s for domain sockets, p for named pipes).
Home Directory
Parent Directory
Paths
● Degraded storage occurs when a storage drive in a RAID array has failed.
● Depending on the RAID type, the system may still function with reduced performance.
● The failed drive can be replaced to restore optimal performance.
● Investigating storage performance issues begins with considering the technology in use.
● Workstations may use SATA hard drives or SSDs, while servers typically use more
efficient options like SCSI, SAS, or SSDs, often in RAID arrays.
● Failing disks, controllers, or hardware components can cause performance problems.
● In a busy server, too many open files can lead to resource exhaustion, causing most
Linux commands to fail.
● Rebooting the server can temporarily resolve the issue.
● The ulimit command can be used to adjust the available number of file descriptors.
● Traditional magnetic hard disk drives may develop bad blocks over time.
● Bad blocks are sections of the disk that can't be read from or written to, and the file
system marks them for exclusion.
● Too many bad blocks can diminish performance and capacity, indicating a failing hard
disk drive that should be replaced.
● df (disk free) command shows device free space, file system, total size, space used,
percentage used, and mount point.
● du (disk usage) command shows directory and file sizes, helping track space hogs.
● The -h option makes the output more human-friendly (e.g., in GB).
I/O Scheduling:
● I/O scheduling manages the order of input/output operations for block storage devices.
● Different scheduler types are available, including deadline, cfq, and noop.
● Changing the scheduler can help optimize performance in specific situations.
iostat Command:
ioping Command:
● ioping tests device I/O latency in real-time, similar to the standard ping for network
latency.
● Useful for troubleshooting latency issues.
Storage Quotas:
● Commands like quotacheck, edquota, and setquota are used for quota
management.
● Activate quotas by editing the fstab file.
● For XFS, use the xfs_admin utility to configure quotas.
Quota Reports:
● Troubleshooting starts with basic checks like permissions and available storage.
● Verify physical connections and system recognition of storage devices.
● Check configuration files (e.g., /etc/fstab) and tools like fsck.
● Text editors are essential tools for viewing, creating, and modifying text files.
● They were originally designed for programming but are now used for various text-based
files.
● In Linux, many configuration components, such as system, network, kernel, and shell
configurations, are stored in text files.
● Text editors can work in both CLI and GUI environments and may have different modes
of operation.
Common Editors
● Popular text editors for Linux include Vi, Vim, Emacs, gVim, gedit, and GNU nano.
● Vim, short for Vi IMproved, is widely used and offers advanced features like text
completion, syntax highlighting, and spell checking.
● Vim operates in different modes: Insert, Execute, Command, and Visual modes.
● GNU nano is user-friendly and is less complex than Vim but lacks some advanced
features.
Using Vim
Using gedit
● Gedit is the default text editor for the GNOME desktop environment in Linux.
● It offers a graphical, menu-based interface, making it user-friendly.
● Gedit provides features like syntax highlighting and spell checking.
● The gedit command can be used in the CLI to open files with or without specifying a
filename.
● locate is used to search for files and directories by performing a quick search in the
mlocate database.
● The database must be regularly updated for effective searches.
● Syntax: locate [options] {string}
● Options include -r for using regular expressions, -c to display the number of matching
entries, and more.
● find allows you to search for files and directories based on specific criteria, recursively
throughout a directory structure.
● Syntax: find [options] {search locations} {search criteria}
[actions]
● Provides more precise and live searching compared to locate.
● You can perform actions on the found results using options like -print, -exec, -ok,
and -delete.
● locate uses a pre-built database for faster but potentially outdated results.
● find performs live searches with more specific criteria and can take longer.
● which displays the complete path of a specified command by searching the directories
assigned to the PATH variable.
● Useful for locating where a program is installed and identifying which version of a
command you're using.
● The cat command is used to display, combine, and create text files.
● It is commonly used to display the contents of small text files.
● Options include -n to number lines, -s to suppress output of repeated empty lines, and
more.
● head displays the first 10 lines of a file, while tail displays the last 10 lines.
● Useful for quickly checking the beginning or end of a file.
● You can use options like -n to specify a different number of lines.
● Both less and more are used to display file contents and page through them if they
extend beyond the screen.
● less typically has more features and is preferred.
● Navigation includes arrow keys, searching, and pressing q to quit.
● touch is used to change the access or modification time of a file to the current time or
create an empty file.
● Useful for testing permissions and creating files.
The ls Command
● cut is used to separate fields from text files based on a specified delimiter.
● Options include -d to specify the delimiter, -f to specify the field numbers, and -s to
suppress lines without the delimiter.
The ln Command
● Text streams are sequences of lines of text used for reading from or writing to devices
and system components, including files, CLI, and network sockets.
● Three primary text streams in Linux are standard input (stdin), standard output (stdout),
and standard error (stderr).
Redirection Operators:
Piping:
● Piping involves combining the standard output of one command as the standard input for
another command.
● The pipe operator | is used to connect commands together.
● xargs reads from standard input and executes a command for each argument provided.
● Useful for processing multiple arguments from standard input.
● tee reads standard input, sends it to the CLI, and copies the output to specified files.
● The -a option appends output to files.
Terminal Redirection:
● The kernel is the core of an operating system, responsible for managing various aspects
of a computer system.
● It manages file system access, memory, processes, devices, and resource allocation.
● The kernel controls hardware devices and is loaded into the main memory during system
startup.
● It contains system-level commands and functions hidden from regular users.
● The kernel divides software running in memory into two spaces: kernel space and user
space.
● Kernel space is where the kernel executes its services, while user space includes all
other applications.
● System calls facilitate communication between user space and kernel space, allowing
user applications to access kernel resources.
3. Types of Kernels:
4. Device Drivers:
● Device drivers are software programs that enable the OS to communicate with hardware
devices.
● They act as intermediaries between the operating system and hardware components.
● Device drivers can be included in the OS or installed as needed.
● It manages system resources and hardware devices, offering features like virtual
memory management, networking support, shared libraries, etc.
● The Linux kernel is highly modular, allowing users to configure and extend its
functionality.
● The Linux kernel is continuously updated and given version numbers for identification.
● The version number format is major.minor, and it changes periodically based on major
developments.
● The uname command is used to check the kernel version and system information.
7. Kernel Layers:
● Kernel modules extend the functionality of the Linux kernel and can be dynamically
loaded or unloaded.
● Advantages of kernel modules include reducing kernel burden, lower memory
consumption, and the ability to update or recompile the kernel without rebooting.
● Kernel modules have the .ko file extension, and they are specific to particular kernel
versions.
● Useful commands for managing kernel modules include lsmod to display loaded
modules, modinfo to view module information, insmod to install modules, and rmmod
to remove modules.
● The modprobe command is preferred as it can load dependent modules.
● The depmod command is used to update the modules dependency database, allowing
modprobe to load modules and their dependencies accurately.
● Configuration settings for kernel modules are stored in files with .conf extensions in the
/etc/modprobe.d/ directory.
● You can define module aliases, blacklist modules, or specify commands to run when
loading a module.
6. Kernel Parameters:
● The sysctl command is used to view or set kernel parameters at runtime, with options
like displaying parameters, setting parameter values, loading settings from a file, and
more.
● The /etc/sysctl.conf file allows for configuring changes to the running Linux kernel,
including network, security, and logging settings.
● /proc/ is a virtual file system (VFS) that provides information about the kernel's running
processes.
● Some important files in the /proc/ directory include /proc/cmdline for kernel boot
options, /proc/cpuinfo for CPU details, /proc/devices for a list of device drivers,
● The /proc/version file contains information about the Linux kernel, including its
version, the version of the GNU Compiler Collection (GCC) used for compilation, the
compiler's username, and the compilation time.
● Verifying the kernel version can help ensure system functionality.
● The dmesg (display message or driver message) command displays messages sent to
the kernel's message buffer during and after system boot.
● Device drivers and other kernel components send messages to the buffer, including
diagnostic messages in case of errors.
● The dmesg command is commonly used for troubleshooting various system issues.
● You can use options like -c to clear the kernel buffer, -f to restrict output by facility, and
-l to restrict output by message level.
● Additionally, you can use -e for human-readable timestamps, -L for color-coded
messages, and -H for human-friendly formatting.
Monitoring kernel modules and reviewing kernel information using these methods helps ensure
that the system is running as expected and that kernel modules are loaded correctly. It's
especially valuable for troubleshooting and system maintenance.
2. Boot Loader:
● A boot loader is a program stored in ROM that loads the kernel from a storage device
and initiates the operating system.
● It can protect the boot process with a password to prevent unauthorized system booting.
● Boot loaders can manage multiple operating systems on a computer.
● Boot loader components include the boot sector program (loaded by the boot
environment), the second stage boot loader (loads the operating system and contains a
kernel loader), and the boot loader installer (controls installation of drive sectors).
4. BIOS (Basic Input/Output System) and UEFI (Unified Extensible Firmware Interface):
5. Password Protection:
● Both BIOS and UEFI support password protection to restrict unauthorized system
booting.
● Systems can be booted from various sources, including ISO images, PXE (Preboot
Execution Environment) for network booting, HTTP/FTP for network booting, and NFS
(Network File System) for network booting.
7. Sectors:
● Sectors are the smallest storage units on a drive, storing 512 bytes of data by default.
● MBR (Master Boot Record) and GPT (GUID Partition Table) are partition structures.
● Initrd (initial ramdisk) and initramfs (initial RAM file system) are temporary root file
systems loaded into memory during system boot.
● They help initialize the permanent root file system, manage device driver modules, and
handle complex boot scenarios.
● The /boot/ directory contains important boot-related files, including GRUB (Grand Unified
Bootloader) configuration files, EFI boot files, initrd/initramfs images, and the Linux
kernel (vmlinuz).
● The dracut command generates initramfs images for Linux systems, replacing mkinitrd
on some distributions.
● The Linux boot process involves a series of steps, from BIOS/UEFI initialization to kernel
and initrd/initramfs loading, and finally boot scripts execution.
● Users select the desired operating system, the kernel initializes hardware and mounts
the root file system, and systemd manages service startup.
● Kernel panic occurs when a fatal error is detected, rendering the system unstable or
unusable.
● Kernel panic can happen during boot due to issues like corrupted kernel, initrd/initramfs
problems, root file system mounting errors, or hardware incompatibility.
Understanding and configuring these boot components is essential for system administrators to
manage Linux systems effectively.
Configure GRUB 2
1. GNU GRUB:
● GNU GRUB (GRand Unified Bootloader) is the primary bootloader for most modern
Linux distributions.
● It allows users to select which operating system or kernel version to boot in a multi-
platform environment.
2. GRUB 2 Improvements:
● GRUB 2 is a complete redesign and rewrite of the GRUB system, offering more control
over the boot process and several improvements.
● These improvements include support for non-x86 platforms, live booting, partition
UUIDs, dynamic module loading, boot loader configuration through scripts, rescue
mode, and custom graphical boot menus.
3. GRUB 2 Installation:
● Use the grub2-install command to install GRUB 2 on BIOS systems. This copies
GRUB 2 files into the /boot/grub2 directory and, on some platforms, installs GRUB 2
into the boot sector.
● For UEFI systems, use a package manager to install the grub2-efi package, which
copies GRUB 2 files to the EFI system partition in the /boot/efi directory.
4. Configuration Files:
5. /etc/grub.d/ Directory:
● The /etc/grub.d/ directory contains scripts used to build the main grub.cfg file.
● These scripts execute in a specific order and should not be directly edited. Custom
scripts can be added with appropriate prefixes to control their execution order.
● The /etc/grub.d/40_custom file allows for the customization of the boot menu
presented to users.
● Users can specify the order of menu choices, provide user-friendly names, and add
password protection to menu entries.
7. Password Generation:
8. /etc/default/grub File:
● The /etc/default/grub file contains settings for GRUB 2 display menu options,
including timeout, submenu ordering, graphical terminal display, and more.
9. grub2-mkconfig Command:
By understanding and configuring these components and files, administrators can customize
and manage the GRUB 2 bootloader according to their system's requirements.
● Localization involves adapting a system's components for use within a distinct culture or
language.
● This includes translating the interface, configuring time zones, keyboard layouts, and
date and time formats according to specific regions.
2. /usr/share/zoneinfo/ Directory:
3. /etc/timezone File:
4. date Command:
5. timedatectl Command:
● Aligning the hardware clock with UTC is recommended to prevent time correction issues.
7. hwclock Command:
8. localectl Command:
● Character encoding is the process of converting text to bytes and vice versa.
● The locale settings in Linux determine the character encoding scheme used by the
system.
Configure GUIs
Configuring graphical user interfaces (GUIs) in Linux involves selecting and customizing the
GUI environment to meet the needs and preferences of users. GUIs provide a visual interface
for interacting with the system and are a common choice for workstations and desktops. Here
are the key concepts and actions related to configuring GUIs in Linux:
GUIs in Linux:
1. What is a GUI: A graphical user interface (GUI) is a visual way to interact with a
computer system, allowing users to perform tasks using graphical elements such as
icons, menus, and windows. GUIs are an alternative to command-line interfaces (CLIs)
in Linux.
2. Choosing a Desktop Environment: Linux offers various desktop environments, each
with its own look, feel, and features. Some popular desktop environments include
GNOME, KDE Plasma, Cinnamon, and MATE. The choice of desktop environment is a
matter of personal preference.
3. Display Servers: Linux supports multiple display servers, including X11 (X Window
System) and Wayland. Display servers handle graphical output and user input for GUI
applications.
4. X11 (X Window System): X11 is the traditional display server used in Linux for many
years. It provides a framework for graphical applications to interact with the hardware.
Various implementations, such as X.Org Server, are available.
5. Wayland: Wayland is a newer and more modern display server protocol designed to
replace X11. It offers improved performance, security, and native support for
compositing.
Remote Desktop:
1. Remote Desktop Software: Remote desktop software allows users to access and
control a remote system's GUI from a local computer. Common remote desktop
solutions for Linux include Virtual Network Computing (VNC), xrdp, NoMachine, and
SPICE.
2. SSH Port Forwarding: Secure Shell (SSH) can be used to tunnel remote desktop
connections securely over the network. SSH port forwarding allows you to establish
encrypted connections for services like VNC.
Console Redirection:
Accessibility Options:
Overall, configuring a GUI in Linux involves selecting the appropriate desktop environment,
display server, and remote desktop software to meet the user's needs. It also includes
customizing accessibility features to ensure an inclusive computing experience. The choice of
GUI components and their configurations should align with the specific requirements of the
users and the purpose of the system.
Manage Services
Services and Daemons:
● Daemons are background processes that run without human intervention and can start
at boot, by applications, or manually.
Service Management:
System Initialization:
● System initialization begins when the kernel loads and involves loading the OS
components.
● An init daemon, such as SysVinit or systemd, handles system initialization.
systemd:
● systemd is a modern init method and is the dominant approach in modern Linux
distributions.
● It offers improvements like parallelization, cgroups for process tracking, and other
features.
systemd Targets:
● hostnamectl is used to view and change the system's hostname and system information.
● SysVinit is an older init method with runlevels, still supported by some distributions.
● Runlevels control the system's state and determine which daemons should run.
● /etc/init.d/ stores initialization scripts for services and controls how they start.
● service is another tool for controlling SysVinit services, starting, stopping, restarting, and
reloading them.
These notes provide a concise summary of the key topics covered in your lesson about
managing services.
pgrep Command:
ps Command:
top Command:
systemd-analyze Command:
lsof Command:
Process Priorities:
● Processes are prioritized based on nice values (-20 to 19), with lower values indicating
higher priority.
nice Command:
renice Command:
Kill Commands:
These notes summarize the key points from your lesson. If you need more specific information
or have any questions, feel free to ask.
/proc/cpuinfo File:
● Low total memory, not enough free memory, or processes not accessing memory are
common problems.
● Insufficient memory for file access, killing critical processes, or improper swap space
usage can cause issues.
/proc/meminfo File:
free Command:
vmstat Command:
OOM Killer:
● Linux kernel's feature to handle extreme memory shortage by killing processes based on
OOM scores.
● Process OOM scores determine which to kill based on memory release and system
stability.
● Can be controlled by managing OOM control group.
mkswap Command:
● Use /proc/cpuinfo, uptime, sar, /proc/meminfo, free, and vmstat to diagnose CPU and
memory issues.
● Adjust the OOM killer if necessary.
● Consider expanding swap space if adding physical memory isn't possible.
Managing Devices
● Device drivers are essential for hardware devices to work properly in Linux.
● Compatibility issues can arise if hardware lacks Linux-compatible drivers.
● Lack of proper drivers can result in devices not functioning or functioning poorly.
Thin Clients:
● Thin clients are lightweight devices that connect to more powerful servers.
● Servers handle most processing, storage, and data management.
● Centralized operations make system management more efficient.
USB Devices:
Wireless Devices:
● Linux supports various wireless protocols, including Wi-Fi, Bluetooth, and Near Field
Communication (NFC).
● Wi-Fi for wireless LAN connectivity.
● Bluetooth for personal area networking.
● NFC for close-range data sharing.
Printers:
Network Adapters:
GPIO:
● SATA (Serial AT Attachment) is a storage bus interface for connecting storage devices.
● SCSI (Small Computer System Interface) connects various peripherals, including
storage.
● SAS (Serial Attached SCSI) uses a serial interface for high-speed storage connections.
Configure Devices
Device File Locations:
● Device files are located in various directories, including /proc/, /sys/, /dev/, and
/etc/.
● /proc/ and /sys/ contain information about devices and hardware details.
● /dev/ stores device driver files to access devices.
● Configuration files for device-related components can be found in /etc/.
Hotpluggable Devices:
udev Rules:
Printing Software:
● Printers often come with software utilities, but their compatibility with Linux may vary.
● Major vendors provide Linux drivers on their websites.
● CUPS (Common Unix Printing System) serves as a print management system for Linux.
● CUPS enables computers to act as print servers, processing print jobs from clients.
● The lpr command submits files for printing, with options like destination, copies, job
name, job options, and more.
Monitor Devices
The lsdev Command:
● lsblk: Identifies block storage devices and checks if they are recognized, partitioned,
and mounted.
● dmesg: Shows messages sent to the kernel's message buffer after system boot,
including device driver messages. Useful for monitoring hardware issues and driver
problems.
● Ensure devices are properly connected, cables aren't loose, and power is supplied.
● Install necessary drivers for the interface.
● Confirm device's compatibility with the bus interface version (e.g., USB version).
● For serial devices, configure them to use appropriate serial console.
● Adjust permissions on serial consoles if needed.
Printer Issues:
● Check printer for common problems like ink/paper shortage or paper jams.
● Ensure Linux-compatible drivers are installed and loaded.
● Use network diagnostic tools like ping to verify the printer's presence on the network.
● In a print server setup, use lpq and lprm to manage print jobs and prevent queue
overload.
Memory Issues:
Video Issues:
lshw Command:
● lshw lists hardware components and details, extracted from various files.
● Use it to identify recognized devices and review device characteristics.
● You can specify device classes with -c option.
● Helpful for verifying hardware presence and compatibility.
dmidecode Command:
● dmidecode dumps the Desktop Management Interface (DMI) table, which tracks
hardware component information.
● Use it to verify connected devices and their features.
● Be aware that DMI tables may contain inaccurate information.
● ABRT reports on problems detected during system runtime, including hardware issues.
● It collects data like memory dumps and reports to help diagnose problems.
● Configure ABRT to redirect problem data to different destinations or write to local or
remote files.
Managing Networking
● The OSI model standardizes networking into seven layers, from physical (Layer 1) to
application (Layer 7).
● Each layer has a specific function.
● It provides a common reference point for devices and network applications.
TCP/IP Layers:
Network Identities:
● Nodes in a network have various identities: MAC address, IP address, and hostname.
● MAC addresses are physical and unique identifiers.
● IP addresses are logical and unique addresses.
● Hostnames are human-readable and help identify devices.
● Key network devices include switches, routers, and media (e.g., Ethernet cable).
● Switches work at Layer 2 (Data Link), routers at Layer 3 (Network).
● Different types of network cables exist, including twisted pair, coaxial, and fiber optic.
IPv4 Addressing:
Reserved Ranges:
● Some address ranges (e.g., 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16) are reserved for
internal networks.
● Loopback address (127.0.0.1) is used for diagnostics and local network communication.
● Link-local addresses (169.254.0.0–169.254.255.255) are for automatic IP configuration.
IPv6:
● IPv6 offers advantages over IPv4, including a larger address space, built-in encryption,
and more efficient routing.
● Linux is fully compatible with IPv6.
Network Ports:
Network Segments:
1. NTP Services (Network Time Protocol): NTP is used for time synchronization. Linux
systems can act as NTP servers or clients, ensuring accurate timekeeping for network
devices.
2. SSH Services (Secure Shell): SSH provides secure remote access to Linux systems. It
is commonly used for remote administration and secure tunneling. Linux can function as
both an SSH client and server.
3. Web Services: Linux servers are frequently used for hosting websites. Apache is a
popular web server software, and Linux supports web services using HTTP (TCP port
80) and HTTPS (TCP port 443).
4. Certificate Authority Services: Certificate authorities (CAs) manage digital certificates
used for secure identity verification. Linux servers can be configured as CAs, enabling
secure communication and website authentication.
5. Name Server/DNS Services: DNS servers resolve hostnames to IP addresses. Linux
systems can function as DNS servers or clients, ensuring name resolution for network
resources.
6. DHCP Services (Dynamic Host Configuration Protocol): DHCP servers dynamically
assign IP addresses and network configuration settings to clients. Linux can serve as a
DHCP server or client, simplifying IP configuration management.
7. SNMP Services (Simple Network Management Protocol): SNMP enables monitoring
and management of network devices. Linux servers can act as SNMP managers or
agents, collecting and transmitting device performance data.
8. Authentication Services: Centralized authentication services, such as Kerberos and
LDAP, enhance network security by validating user identities. Linux can operate as an
authentication server.
9. Proxy Services: Linux can function as a proxy server, facilitating communication
between untrusted and trusted network segments. Proxy servers, like Squid, are often
used for web browsing.
10. Logging Services: Linux systems generate log files that capture important events and
activities. Centralized logging services collect and store log data for analysis,
troubleshooting, and security monitoring.
11. Monitoring Services: Linux offers various monitoring tools to track system and
application performance. Examples include top, ApacheTop, Monit, and System Monitor.
12. Load Balancing Services: Load balancers distribute incoming connection requests
among multiple servers to improve availability and distribute traffic. They are commonly
used for web services.
13. Clustering Services: Clustering involves creating a group of interconnected servers
(nodes) that work together to ensure high availability and scalability. Clusters are often
used for database access and critical services.
14. File/Print Services: File servers store and centralize user data, while print servers
manage networked printers. These services improve data management and print
resource sharing.
15. Samba and NFS: Samba supports SMB-compatible file sharing for integration with
Windows systems. NFS provides native Unix/Linux file sharing for workstations.
16. Database Services: Linux supports both SQL and NoSQL database services, such as
MySQL, MariaDB, PostgreSQL, and MongoDB, for storing and querying data.
17. VPN Services (Virtual Private Network): VPN servers enable remote users to securely
access the internal network over untrusted connections. Linux can function as both a
VPN server and a VPN client.
18. Virtualization/Container Host Services: Linux serves as a host for virtual machines
(VMs) and containers, allowing efficient resource utilization and isolation of applications.
19. Email Services: Email servers, like Sendmail and Postfix, facilitate the distribution of
electronic mail within organizations. They use email protocols like SMTP, POP3, and
IMAP.
These server roles are vital for maintaining and managing network services in a Linux
environment.
Connect to a Network
Hostname Configuration:
● You can use the hostnamectl command to configure the hostname of your Linux
system. For example: sudo hostnamectl set-hostname server01.
IP Configuration:
NetworkManager:
nmcli Command:
● nmcli is a command-line tool that allows you to view and configure network settings.
● Examples of nmcli subcommands include general status, connection show,
con up, and device status.
● Use the syntax: nmcli [options] [subcommand] [arguments].
nmtui Utility:
● The nmtui utility offers a text-based user interface (TUI) for configuring network
settings.
● Navigate through the interface using the Tab key, Spacebar, Enter key, and arrow keys.
nmgui Utility:
● NetworkManager also includes a graphical user interface (GUI) tool for managing
network connections.
● This tool is suitable for configuring IPv4, IPv6, and various network settings.
ifconfig Command:
ip Command:
● The ip command has largely replaced ifconfig and provides similar information.
● Use the ip command to show IP address details, interface status, and enable/disable
network interfaces.
iwconfig Command:
● The iwconfig command is used for configuring wireless network interfaces, including
SSID, encryption, frequency, and channel settings.
These tools and commands are essential for configuring and verifying network connections on
Linux systems.
DHCP Configuration:
● DHCP clients lease IP configurations from DHCP servers, and leases include IP
addresses, subnet masks, gateway addresses, DNS server addresses, and lease
duration.
● The lease renewal process allows clients to renew their leases, which also provides
opportunities for updates.
/etc/dhcp/dhclient.conf File:
Name Resolution:
● Tools like host and nslookup are used to test name resolution and ensure proper
DNS functionality.
/etc/hosts File:
● The /etc/hosts file contains static IP address and hostname mappings, providing a
manual way of resolving names to IP addresses.
/etc/resolv.conf File:
/etc/nsswitch.conf File:
These concepts and tools are essential for configuring DHCP and DNS client services on Linux
systems, ensuring reliable network connections and proper name resolution.
Cloud Computing:
Cloud Models:
● There are three primary cloud models: Software as a Service (SaaS), Platform as a
Service (PaaS), and Infrastructure as a Service (IaaS), each serving different purposes.
● Public, private, and hybrid clouds offer different structures for deploying cloud services,
with varying levels of control and security.
● Leading cloud service providers include Amazon Web Services (AWS) and Microsoft
Azure, with Red Hat Cloud Suite as a Linux-based private cloud option.
● Various other providers offer specialized services and solutions tailored to different
market segments.
Virtualization:
● Virtualization forms the foundation of cloud computing, allowing more efficient use of
hardware, fault tolerance, and quick server deployments.
● Hypervisors, like Type 1 (bare-metal) and Type 2 (hosted), manage virtual machines,
providing control between VMs and physical hardware.
Templates:
Bootstrapping:
● Bootstrapping refers to the initial setup and customization of virtual machines during
their first boot. Tools like cloud-init, Anaconda, and Kickstart enable bootstrapping.
● These tools help automate the installation and configuration of virtual machines.
Storage:
Networking Configurations:
● Virtual machines can be configured with virtual NICs connected to virtual switches within
the hypervisor.
● Network configurations, including public, private, and internal networks, provide different
levels of connectivity and isolation.
Virtualization Tools:
● Virtualization tools like virsh and libvirt are used for managing virtual machines, providing
command-line and API-based access to VMs.
● GNOME VMM (Virtual Machine Manager) offers a graphical interface for VM
management.
These concepts and tools help configure and manage cloud and virtualization technologies,
enabling businesses to leverage the benefits of scalability, flexibility, and cost-efficiency in their
IT infrastructure.
Software Dependencies:
● Red Hat Package Manager (RPM) and Debian dpkg are two dominant package
management methods.
● RPM packages have a .rpm extension, while Debian uses .deb.
● Compiling from source code is an option for open-source Linux software.
● Compiling requires more effort but offers customization.
Distribution Origins:
● Common Linux distributions and their origins include Red Hat, CentOS, Fedora, and
Debian.
● Dandified YUM (DNF) is an improved version of YUM, using fewer resources and
maintaining RPM support.
● Zypper is an openSUSE package manager that efficiently manages package
dependencies.
DNF Syntax:
Zypper Syntax:
RPM Upgrades:
yum Subcommands:
The -y Option:
● Use the -y option with yum to automatically answer yes when prompted for installing
additional software dependencies.
● Use -i with dpkg to ensure all necessary components are installed when repairing a
software installation.
apt Subcommands:
● Still functional, these commands provide lower-level functionality for more specific
control.
Make sure to run apt update before apt upgrade to ensure the database is aware of newer
packages.
Configure Repositories
Repositories:
● Three types of repositories: Local repositories (on local storage), Centralized internal
repositories (within LAN), Vendor repositories (maintained on the Internet).
Repository Synchronization:
Acquire Software
Download Sites:
● Linux software can often be freely downloaded from application vendors or websites that
centralize information about available software.
● Popular Linux applications include Audacity, Atom, GIMP, and Nmap.
● Open-source hosting sites like GitHub also host software.
.tar Files:
● Linux often uses tar (tape archiver) to bundle files into a single .tar file.
● Useful for bundling multiple files for efficient downloads.
● Example of creating a tarball: tar -cvf tarball.tar file1 file2 file3.
● Basic tar command options: -c (create), -x (extract), -v (verbose), -r (append), -t (test), -f
(specify tarball name).
Compressed Files:
● Compiling software from source allows customization for specific hardware or needs.
● Linux users have access to open-source code for compilation.
● Windows and macOS typically use pre-compiled software.
Compilers:
Libraries:
● Typically, make without arguments installs the application, looking for the makefile in the
current directory.
● Developers may provide instructions and options for optimizing the software.
More on Makefiles:
● Check documentation for the required GCC or other compiler versions when compiling
software.
● Verify the Linux kernel and software dependencies versions required by the program
you're compiling.
● Use ldd {program binary} to check shared library file dependencies.
● Verify library file versions and availability.
● Consider compiling and testing software in a virtual machine to ensure proper
functionality.
● Assume root privileges when using make install command for software compilation.
● MFA involves using more than one factor, such as something you know (password) and
something you have (smart card or token), for enhanced security.
Privilege Escalation:
● Privilege escalation can be both legitimate (e.g., administrator using sudo) and malicious
(exploiting vulnerabilities to gain elevated privileges).
● Poorly configured SUID and SGID permissions can enable privilege escalation.
chroot Jail:
Encryption:
Hashing:
● Hashing converts data into an indecipherable fixed-length output, providing data integrity
and security.
● Hash functions make it challenging to reverse-engineer the original data from the hash.
● SSH key-based authentication involves using a public-private key pair for secure access.
● Key files: id_rsa (private key), id_rsa.pub (public key), authorized_keys (server-
side list of accepted public keys), and known_hosts (client-side list of accepted server
public keys).
sshd_config File:
TCP Wrappers:
● Used to allow or deny connections from specific hosts to the SSH service.
Password Policies:
User Lockouts:
● Use PAM modules like pam_tally2 and pam_faillock to lock out users after
multiple failed login attempts.
● Add directives in /etc/pam.d/password-auth and /etc/pam.d/system-auth.
OpenSSL:
● IPSec secures data in transit, used in site-to-site and remote access VPNs.
● Modes: transport (packet content encryption) and tunnel (packet content and header
encryption).
● StrongSwan is a tool for IPSec implementation.
● SELinux and AppArmor are context-based permission schemes used to enhance Linux
system security.
● Mandatory Access Control (MAC) is the underlying model used by both to control access
based on security designations and clearances.
● SELinux is the default on CentOS and Red Hat Enterprise Linux, offering file system and
network security, protecting against unauthorized access and data tampering.
● SELinux uses User, Role, and Type contexts to control access, where Type (label) is
crucial for fine-grained control.
● Multi-Level Security (MLS) introduces a fourth context for sensitivity levels and
categories.
● SELinux has three modes: Disabled (MAC off), Enforcing (security policies enforced),
and Permissive (security policies not enforced but violations are logged).
● Security policies are categorized as targeted (only certain subjects/objects are confined)
or strict (everything is confined).
● Common SELinux commands include semanage, sestatus, setenforce, and
getsebool for configuration and status checks.
● Diagnose SELinux violations using sealert with the audit log or audit2why for more
human-readable explanations.
For AppArmor:
● AppArmor operates in two modes: Complain (violations logged but not prevented) and
Enforce (violations both logged and prevented).
● Tunables allow you to configure AppArmor without modifying profiles directly (e.g.,
adjusting variable names).
● Major AppArmor commands include apparmor_status, aa-complain, aa-enforce,
and aa-disable to manage profiles.
Configure Firewalls
Iptables:
Firewalld:
IP Sets:
● IP sets are collections of IP addresses, ports, etc., used for efficient rule matching with
iptables.
● Create and modify IP sets with the "ipset" command.
● Reference IP sets in iptables rules to make rule sets dynamic.
Firewall Troubleshooting:
● DenyHosts protects SSH servers from brute force attacks, monitoring failed logins.
● Fail2ban prevents brute force attacks for various services, using log files and Netfilter.
● Both tools help enhance security by blocking malicious IP addresses.
● System logs track and maintain records of system activities and events.
● They use the syslog standard and can be centralized for remote logging or stored
locally.
● Entries in a syslog include date, time, process name, ID, message, facility, and severity.
● Common system log locations include /var/log/syslog, /var/log/messages,
/var/log/auth.log, /var/log/secure, /var/log/kern.log, and /var/log/[application].
Log Rotation:
● Log rotation is the practice of creating new versions of log files to manage their size.
● Logrotate is a utility used for automatic log rotation.
● Log files can be rotated based on size, time, or other criteria.
● It improves log management and analysis.
rsyslogd Service:
syslog-ng Service:
Third-Party Agents:
journalctl Command:
● Journalctl is used to view and query logs created by the systemd journald service.
● It can display logs, filter by severity, service, and more.
● Journalctl settings are configured in /etc/systemd/journald.conf.
/var/log/journal/ Directory:
last Command:
● The last command displays the history of user login and logout events, including time
and date.
● Options allow you to filter results, such as by specific users or terminals.
● It retrieves information from /var/log/wtmp.
lastlog Command:
● The lastlog command lists users and their last login times.
● It retrieves data from /var/log/lastlog and is similar to last, but doesn't show login/logout
events.
● There are three main types of backups: Full, Differential, and Incremental.
● Full backups include all selected files, making them reliable for data recovery.
● Differential backups cover changes since the last full backup.
● Incremental backups include changes since the last full or incremental backup, and they
are faster to perform but slower to recover.
● Snapshot: Records the state of a storage drive at a specific time on the same drive.
● Image: Saves the state of an operating system as an image file (e.g., ISO) for system
recovery.
● Clone: Copies all contents of a storage drive to another storage medium.
● Tar is used to create archives of data, often with a .tar file extension.
● It can create archives, extract files, store additional files, and list archived files.
● Syntax: tar [options] {file names}
● Use the command "tar -xvf" to restore the entire contents of a source file or directory.
● For partial restores, provide the path and name used when creating the tar file.
● Dar (Disk Archiver) replaces tar, offering more backup and archiving functionality.
● It can create full, differential, and incremental backups.
● Example: dar -R [source] -c [backup file] -A [reference backup]
● Cpio copies files to and from archives and has three modes: copy-out, copy-in, and
copy-pass.
● Syntax varies depending on the mode, and it reads from standard input.
● Example: ls | cpio -o > [archive file]
The dd Command:
● Dd copies and converts files for transferring data between different media.
● It has various operands for reading from and writing to files, specifying block size, and
counting blocks.
● Example: dd if=[source] of=[destination]
● Mirrorvg creates copies (mirrors) of all logical volumes in a specified volume group.
● It can create multiple copies for redundancy.
Off-Site Backup:
● Off-site backups store data at a location outside the main site for disaster recovery.
● Data transfer tools include scp, sftp, and rsync for secure off-site data transfer over
networks.
● The shell environment stores settings and behavioral details about the shell.
● New sessions are created through shell spawning, and these sessions can become child
processes.
● Each process calls upon the shell environment and passes details to the next
generation.
Scripts:
● Scripts are computer programs that automate tasks in a runtime or shell environment.
● They are written in scripting languages, a subset of programming languages.
● Scripts do not have the feature set of full programs but integrate with other components
to achieve automation.
Variables:
Environment Variables:
● Environment variables are inherited by child processes and consist of key-value pairs
(e.g., KEY=value).
● Some default environment variables include HOSTNAME, SHELL, MAIL, HOME, PATH,
HISTSIZE, and USER.
● You can change a shell variable to an environment variable using the export
command.
● Change the value of a variable while exporting it using export VARIABLE_NAME="New
value".
● The set command without arguments prints all shell variables, environment variables,
and shell functions.
Search Paths:
● The PATH variable consists of directory paths for locating executable files.
● You can add, modify, or delete paths to customize the search path.
HISTFILESIZE:
● HISTFILESIZE sets the maximum lines in the command history file and the number of
lines displayed with the history command.
● time gathers information about command execution time and statistics, including real,
user, and system time.
Troubleshooting:
● Bash supports various types of operators, including arithmetic, comparison, logical, and
string operators.
● Arithmetic operators perform mathematical operations, comparison operators compare
values, logical operators combine values, and string operators manipulate strings.
● Examples of operators in Bash include +, -, ==, -ge, &&, ||, =, and more.
String Literals:
● String literals are fixed values that represent strings within source code and are enclosed
in single or double quotation marks.
● Double quotes allow variable substitution, while single quotes preserve the literal value
of characters.
● You can use an escape character (\) to remove special meanings from specific
characters in a string, making them interpreted literally.
Arrays:
● Arrays are collections of values, allowing you to store multiple values in a single variable.
● Arrays are ordered based on indices, usually starting from 0.
● You can assign values to arrays using compound assignment (my_arr=(1 "Hello"
3.1)) or individual assignment (my_arr[0]=1).
Functions:
Comments:
● Comments are used to annotate source code for clarity and documentation.
● In Bash, comments are preceded by the # character and are ignored by the interpreter.
1. Create a New Bash Script: Open a text editor on your Linux system, such as nano,
vim, or gedit, and create a new file. For example, you can use nano to create a file
named myscript.sh:
bash
nano myscript.sh
Write the Script: Add your Bash script code to the file. For this example, we'll create a simple
script that prints a greeting message. Here's an example script:
bash
#!/bin/bash
# This is a simple Bash script
Execute the Script: Now that the script is executable, you can run it from the terminal:
bash
./myscript.sh
The ./ is necessary to specify that you want to execute the script located in the current
directory.
Output: When you run the script, it will print the greeting message to the terminal:
bash
Hello, World!
bash
var=5
if [ $var -gt 1 ]
then
echo "$var is greater than 1!"
fi
if...else Statement: The if...else statement lets you choose between two actions based on
a condition:
bash
var=1
if [ $var -gt 1 ]
then
echo "$var is greater than 1!"
else
echo "$var is less than or equal to 1!"
fi
case Statement: The case statement allows you to evaluate multiple conditions. Here's an
example with multiple conditions:
bash
var=blue
case $var in
red)
echo "Your color is red."
;;
green)
echo "Your color is green."
;;
blue)
echo "Your color is blue."
;;
*)
echo "Your color is neither red, green, nor blue."
;;
esac
1.
Loops:
4. while Loop: The while loop repeatedly executes a block of code while a specific
condition is met:
bash
var=1
while [ $var -le 5 ]
do
echo "The current number is $var."
((var++))
done
until Loop: The until loop is similar to the while loop but continues executing code while a
condition is false:
bash
var=1
until [ $var -ge 5 ]
do
echo "The current number is $var."
((var++))
done
for Loop: The for loop is used to iterate through a list of items or numbers:
bash
names=("Carla" "Robert" "Mary")
for name in "${names[@]}"
do
echo "$name is a member of the team."
done
Looping Through Ranges: You can use the for loop to iterate through a range of numbers:
bash
for i in {1..5}
do
echo "The current number is $i."
done
4.
You can incorporate these control statements and loops into your Bash scripts to create more
complex and interactive scripts.
Automating Tasks
Schedule Jobs
Using the at command
The at command allows you to run a task once at a specified time. It's suitable for one-time,
non-recurring tasks. Here's an example:
bash
at 15:30
This will enter an interactive mode where you can specify the command to be executed at 3:30
PM. After entering the command, press Ctrl+D to schedule it.
You can also schedule a task to run after a specific time interval:
bash
at now + 1 hour
This schedules a task to run one hour from the current time.
cron is a daemon used to manage scheduled tasks called cron jobs. You can specify tasks to
run at various intervals: minutes, hours, days, months, or days of the week.
crontab -e
This opens a text editor (usually Vim) where you can define your cron jobs.
The format of a cron job is as follows:
bash
* * * * * /path/to/command
The five asterisks represent the schedule in this order: minutes, hours, days of the month,
months, and days of the week. For example:
1.
2. System-wide cron jobs are located in /etc/cron.d/. Standard users can create and
manage their own cron jobs in /var/spool/cron/.
3. There are also directories like /etc/cron.hourly, /etc/cron.daily,
/etc/cron.weekly, and /etc/cron.monthly, where you can place scripts to be
executed on an hourly, daily, weekly, or monthly basis.
Remember that the cron daemon checks its configuration file every minute, so the tasks are
executed based on the schedule you define.
1. Install Git: If Git is not already installed on your Linux system, you can install it using
your distribution's package manager. For example, on Debian-based systems, you can
use apt:
bash
Configure Git: Set your user name and email address globally. These will be used to identify
your commits. Replace 'User' and 'user@domain.tld' with your actual name and email
address:
bash
git config --global user.name 'User'
git config --global user.email 'user@domain.tld'
Create a Git Repository: Navigate to the directory where your project is located and initialize a
Git repository:
bash
cd /path/to/your/project
git init
Add Files: Add the project files you want to track to the Git repository. You can specify
individual files or use a wildcard * to add all files:
bash
git add myfile
# or to add all files
git add .
Commit Changes: Commit the changes to the repository. When you commit, provide a clear
and descriptive commit message:
bash
git commit -m 'Initial commit'
View Repository Status: You can check the status of your Git repository at any time to see
which files have been modified, added, or deleted:
bash
git status
Working with Branches: Optionally, you can work with branches in Git. Branches are used to
isolate work on a particular feature or bug fix. Here's how to create and merge branches:
Collaborate with Others: If you're collaborating with other developers, you can pull their
changes and push your own. To pull changes from a remote repository:
bash
git pull origin otherbranch
bash
git push origin mybranch
View Commit History: You can view the commit history of your repository to see what changes
were made. Use the git log command:
bash
git log
1.
2. .gitignore File: If there are files or directories you want Git to ignore (e.g., temporary
files, build artifacts), you can create a .gitignore file in your repository and list the
patterns for files or directories to be excluded from version control.
That's a basic overview of how to implement version control using Git on your local system and
collaborate with others. Git is a powerful tool that allows you to manage your project's source
code efficiently and keep track of changes over time.
Infrastructure Automation:
Infrastructure as Code:
● Infrastructure as code (IaC) relies on scripting and code files to manage the deployment
and configuration process.
● It uses a single configuration specification to deploy the supporting infrastructure and
applications.
Orchestration Tools:
Orchestration Procedures:
Attributes:
● They are used to identify tasks to be managed during the orchestration process.
Inventory Management:
Installing Linux
● System requirements are not only about hardware but also about keeping the system
operational and functional.
● Different Linux distributions have varying requirements based on CPU speed, RAM,
storage space, and more.
● Hardware compatibility is crucial as even powerful hardware may not be supported by a
particular distribution.
Partitioning Strategy:
Hardware Compatibility:
● Check whether hardware components are compatible with the chosen Linux distribution.
● Some distros maintain a hardware compatibility list (HCL) to help identify supported
hardware.
● Gathering hardware information from system documentation, BIOS/UEFI, or physical
inspection is necessary.
Installation Methods:
● Consider cost, system role, and distribution when identifying system requirements.
● Choose partitioning strategies based on the system's role, keeping complexity in mind.
● Check hardware compatibility with the chosen Linux distribution.
● Address questions for each hardware component.
● Select an installation method that suits your needs and organization efficiently.
These are key considerations and steps to take when preparing for a Linux installation.
● Set the system's language and keyboard layout to establish a baseline for the installation
process.
● Set the time zone and other date and time settings. You may also have the option to
synchronize with a Network Time Protocol (NTP) server.
● Select the installation media to use. Even if you booted from a specific source, you may
have the option to choose an alternative source for installation.
● Select the software environment and components to install. This may include choosing a
base environment, which can vary from minimal installs to full-fledged GUI installations.
You might also be able to specify specific software packages.
● Design the structure of the root file system, including its size and file system type.
Configure logical volumes on available storage drives and define additional file systems
if needed.
● Configure user accounts, including setting the root user's password and creating
additional administrator or standard user accounts.
● Apply security profiles and policies to the system, if available in the installer.