Linux Unit- 4

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 22

Linux Administration

Linux administration involves managing and maintaining Linux-based systems and servers. It includes
tasks such as installing software, managing user accounts, configuring services, ensuring system security,
troubleshooting issues, and optimizing performance.

Managing Users
Managing users in Linux involves creating, modifying, and deleting user accounts, setting permissions,
and managing groups.

1. Viewing User Information


 whoami: Displays the current logged-in user.

 id: Displays user ID (UID), group ID (GID), and groups the user belongs to.

 cat /etc/passwd: Lists all user accoun

2. Adding Users
 Create a New User: sudo useradd -m username

 Set a Password: sudo passwd username

 Add User with Specific Options: sudo useradd -m -d /custom/home -s /bin/bash -c "User Full
Name" username

-d: Set a custom home directory.

-s: Specify the default shell.

-c: Add a comment (usually the full name).

3. Modifying Users
 Change User Details: sudo usermod -c "New Full Name" username

 Change Shell: sudo usermod -s /bin/zsh username

 Lock/Unlock a User:

Lock: sudo usermod -L username

Unlock: sudo usermod -U username

 Move Home Directory: sudo usermod -d /new/home -m username


4. Deleting Users
 Delete User (Keeps Home Directory):sudo userdel username

 Delete User and Remove Home Directory: sudo userdel -r username

5. Managing Groups
 View Groups:groups username

 Create a Group:sudo groupadd groupname

 Add User to Group: sudo usermod -aG groupname username

 -aG: Appends the user to the group.

 Change a User’s Primary Group: sudo usermod -g groupname username

 Remove User from a Group: sudo gpasswd -d username groupname

6. Managing Permissions
 Change File Ownership: sudo chown username:groupname filename

 Change File Permissions: chmod 755 filename

7. Viewing and Monitoring User Activity


 List Logged-In Users: who

 See User Login History: last

8. User Configuration Files


 /etc/passwd: Contains user account information.

 /etc/shadow: Stores encrypted passwords.

 /etc/group: Defines groups.

 /etc/skel/: Contains default files copied to a new user’s home directory.

Super user control


In Linux, the superuser (often referred to as the "root user") has unrestricted access to all system
resources and administrative capabilities. Managing superuser privileges effectively is crucial for system
security and stability.
Understanding the Superuser
 Superuser Permissions:
 Access and modify any file or directory.

 Install, remove, or configure software.

 Manage system services and users.

 Modify critical system settings.

 Root Account:
 The root account is the default superuser account.

 Direct login as root is discouraged for security reasons; use sudo instead.

Using sudo for Superuser Access


The sudo command allows a regular user to execute commands with superuser privileges temporarily.

1. Basic Usage
 Prefix commands with sudo: sudo command

Example:sudo apt update

 After entering your password, the command runs with superuser privileges.

2. Granting Superuser Privileges


To allow a user to use sudo, they must belong to the sudo or wheel group (depending on the
distribution):

 Add a user to the sudo group: sudo usermod -aG sudo username

 Verify group membership: groups username

3. sudo Configuration
 The sudo behavior is controlled by the file /etc/sudoers. Use visudo to edit it safely:

sudo visudo

 Example to allow a user to run all commands without a password prompt:

username ALL=(ALL:ALL) NOPASSWD:ALL

Switching to the Superuser (Root) Account


Temporarily switch to the root account: sudo -I or sudo su

Exit the root session by typing: exit

Restricting Superuser Access


Restricting access to superuser privileges ensures that only authorized users can perform critical tasks.

1. Remove a User from the sudo Group


 Use the following command: sudo deluser username sudo

2. Restrict Specific Commands


 In the /etc/sudoers file, you can limit users to run specific commands:

username ALL=(ALL) /bin/systemctl, /usr/bin/apt

Superuser Responsibilities
 System Updates and Maintenance: Regularly update and patch the system to prevent
vulnerabilities.

 User Management: Add, modify, and delete user accounts as needed.

 File Permissions: Set appropriate file ownership and permissions.

 System Monitoring: Monitor logs and performance to detect issues early.

System Run Levels in Linux


Run levels are a concept in Linux that define the state of the operating system, specifically the services
and processes that should be running. They determine what functions the system is configured to
provide, such as multi-user mode, graphical interface, or maintenance mode.

Standard Run Levels


Run levels range from 0 to 6, though the specific configuration can vary between Linux distributions.
Here’s a general breakdown:

Run State Description


Level

0 Halt Shuts down the system safely.


1 Single-user mode For maintenance; only the root user is allowed.

2 Multi-user mode without Multiple users allowed, but no network services.


networking

3 Multi-user mode with networking Full multi-user mode with network services
enabled.

4 Undefined (customizable) User-definable for specific needs.

5 Multi-user mode with GUI Multi-user mode with a graphical user interface
(GUI).

6 Reboot Reboots the system.

Checking and Changing Run Levels


In modern systems, run levels have been replaced by systemd targets, but the concept remains relevant
for legacy systems.

1. View Current Run Level

For systems using the traditional SysVinit: runlevel

Output example: N 3

 N: Previous run level (e.g., unknown or not set).

 3: Current run level.

2. Change Run Level

 For SysVinit systems, use the init command: sudo init 5

 This would switch to run level 5 (GUI mode).

Run Levels and systemd Targets


On modern Linux systems with systemd, run levels are replaced by targets. The equivalent targets are:

Run Level systemd Target

0 poweroff.target

1 rescue.target

multi-
2, 3, 4
user.target

5 graphical.target
Run Level systemd Target

6 reboot.target

1. Check Current Target

systemctl get-default

2. Change Current Target

 To switch to a specific target temporarily:

 sudo systemctl isolate graphical.target

 To set a target as default:

 sudo systemctl set-default multi-user.target

Examples of Use
1. Enter Maintenance Mode

Switch to single-user mode for maintenance tasks: sudo systemctl isolate rescue.target

2. Shut Down the System

sudo systemctl isolate poweroff.target

3. Reboot the System

sudo systemctl isolate reboot.target

Differences Between Legacy and Modern Systems


Feature SysVinit (Run Levels) systemd (Targets)

Configuration /etc/inittab Service files in /lib/systemd/system/

Commands init, telinit systemctl

Flexibility Limited Highly configurable and modular


Managing File Systems in Linux
Managing file systems in Linux involves creating, mounting, formatting, and monitoring storage devices
to ensure the system operates efficiently. Here's an overview of key tasks:

1. Understanding File Systems


A file system organizes data on a storage medium. Common Linux file systems include:

 Ext4: Default for most distributions, offering reliability and performance.

 XFS: High-performance journaling file system.

 Btrfs: Modern file system with advanced features like snapshots.

 VFAT/NTFS: Used for compatibility with Windows.

2. Viewing File System Information


 Check Disk Space: df -h

o -h: Displays human-readable sizes (e.g., GB, MB).

 Check Inode Usage: df -i

 List Block Devices: lsblk

 Display File System Type: blkid

 Detailed File System Usage: du -sh /path/to/directory

o -s: Summarize the total size.

o -h: Human-readable format.

3. Creating and Formatting File Systems


1. Create a Partition
Use fdisk or parted to create partitions: sudo fdisk /dev/sdX

 Replace /dev/sdX with your device name (e.g., /dev/sda).

2. Format the Partition


 Format as Ext4:

 sudo mkfs.ext4 /dev/sdX1

 Format as XFS:

 sudo mkfs.xfs /dev/sdX1

 Format as FAT32 (for cross-platform compatibility):


 sudo mkfs.vfat -F 32 /dev/sdX1

4. Mounting and Unmounting File Systems


1. Mount a File System

 Create a mount point: sudo mkdir /mnt/mydisk

 Mount the device: sudo mount /dev/sdX1 /mnt/mydisk

 Verify the mount: mount | grep /mnt/mydisk

2. Unmount a File System: sudo umount /mnt/mydisk

 Use lsof to check open files if unmounting fails: lsof +D /mnt/mydisk

5. Persistent Mounts
To make a mount persistent across reboots, edit the /etc/fstab file:

1. Get the UUID of the device: blkid /dev/sdX1

2. Add an entry to /etc/fstab: UUID=your-uuid /mnt/mydisk ext4 defaults 0 2

6. Checking and Repairing File Systems

 Check File System Health: sudo fsck /dev/sdX1

o Add -y to auto-fix errors: sudo fsck -y /dev/sdX1

 Force a Check: sudo tune2fs -c 1 /dev/sdX1

7. Monitoring File System Usage


 Find Large Files: sudo find / -type f -size +100M

 Analyze Disk Usage: sudo ncdu /

(Install ncdu if not available: sudo apt install ncdu)

 Monitor Disk I/O: iostat -x 1

(Install sysstat if needed: sudo apt install sysstat)

8. Managing Swap Space


1. Create a Swap File

 Create and set up a swap file:

sudo fallocate -l 1G /swapfile

sudo chmod 600 /swapfile

sudo mkswap /swapfile


sudo swapon /swapfile

 Add it to /etc/fstab for persistence:

/swapfile none swap sw 0 0

2. Monitor Swap Usage: free -h

9. Mounting Network File Systems


 NFS: Mount an NFS share: sudo mount -t nfs server:/share /mnt/nfs

 Samba (SMB): Mount a Samba share:

sudo mount -t cifs -o username=user,password=pass //server/share /mnt/smb

10. Backups and Snapshots


 Using rsync for Backups: rsync -avh /source /destination

 Using btrfs Snapshots: sudo btrfs subvolume snapshot /mnt/data /mnt/backup

Kernel Administration in Linux


The kernel is the core component of the Linux operating system, managing hardware resources and
enabling communication between hardware and software. Kernel administration involves configuring,
updating, and optimizing the kernel for system requirements.

Linux Kernel Sources


The Linux kernel source code is the official repository of all the kernel's code and is maintained by the
Linux Foundation under the leadership of Linus Torvalds. Accessing and managing the kernel source
allows developers to build custom kernels or contribute to kernel development.

1. Accessing the Linux Kernel Source


The Linux kernel source code is publicly available and can be obtained in multiple ways:

1. Downloading Official Kernel Tarballs

 The kernel source tarballs are hosted at kernel.org.

 To download:
wget https://cdn.kernel.org/pub/linux/kernel/v6.x/linux-6.x.x.tar.xz

 Extract the tarball:

tar -xvf linux-6.x.x.tar.xz

cd linux-6.x.x

2. Using Git to Clone the Repository

 Clone the official Linux kernel repository:

git clone https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git

cd linux

 To check out a specific version:

 git checkout v6.x

2. Kernel Directory Structure


The kernel source tree contains several directories. Here are some important ones:

Directory Purpose

arch/ Architecture-specific code (e.g., x86, ARM, etc.).

block/ Block device subsystem code.

drivers/ Device drivers (e.g., network, storage, graphics).

fs/ File system code (e.g., Ext4, Btrfs, NFS).

include/ Header files used across the kernel.

kernel/ Core kernel code (e.g., scheduling, signals, locking).

net/ Networking stack code.

mm/ Memory management subsystem.

tools/ Various tools for testing and debugging (e.g., perf, bpftool).

Documentation/ Kernel documentation for developers and users.

3. Building the Linux Kernel from Source


Step 1: Install Required Tools

Install necessary dependencies:

sudo apt update


sudo apt install build-essential libncurses-dev bison flex libssl-dev libelf-dev

Step 2: Configure the Kernel

1. Start with the current system configuration:

cp /boot/config-$(uname -r) .config

2. Customize the kernel configuration:

make menuconfig

o This command opens a menu-based interface to select features, drivers, and modules.

Step 3: Compile the Kernel

1. Build the kernel:

make -j$(nproc)

o Replace $(nproc) with the number of CPU cores for faster compilation.

2. Install kernel modules: sudo make modules_install

Step 4: Install the Kernel

Install the compiled kernel: sudo make install

Step 5: Update Bootloader

Update GRUB or other bootloader configurations: sudo update-grub

Step 6: Reboot

Reboot the system to boot into the new kernel: sudo reboot

4. Patching the Kernel


Kernel patches are updates or modifications to the source code. They are often used to fix bugs, add
features, or improve performance.

Applying a Patch
1. Obtain the patch file (e.g., patch-6.x.x).

2. Apply the patch:

3. patch -p1 < /path/to/patch-file

4. Rebuild the kernel to apply changes.

5. Contributing to the Linux Kernel


If you're interested in contributing:

1. Clone the official repository:


git clone https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git

2. Make your changes in a new branch:

git checkout -b my-feature-branch

3. Submit patches following the Linux Kernel Contribution Guidelines.

6. Keeping Kernel Sources Updated


To keep the kernel sources updated with the latest changes:

1. Pull the latest changes from the official repository:

2. git pull

3. For local builds, clean the build directory before recompiling:

4. make clean

Rebuilding the Linux Kernel


Rebuilding the kernel allows customization for specific needs, such as adding support for hardware,
enabling debugging features, or optimizing performance. Below is a step-by-step guide to rebuilding the
Linux kernel.

1. Preparation
Install Required Tools

Before you begin, ensure the necessary development tools and dependencies are installed:

For Debian/Ubuntu:

sudo apt update

sudo apt install build-essential libncurses-dev bison flex libssl-dev libelf-dev

For RHEL/CentOS:

sudo yum groupinstall "Development Tools"

sudo yum install ncurses-devel bison flex elfutils-libelf-devel openssl-devel

Check Disk Space

Ensure you have enough space for the source code and build: df -h
You typically need at least 20 GB of free space.

2. Get the Kernel Source Code


Option 1: Download Official Kernel Tarball

 Visit kernel.org and download the desired version.

 Example for version 6.x.x: wget https://cdn.kernel.org/pub/linux/kernel/v6.x/linux-6.x.x.tar.xz

 Extract the tarball:

tar -xvf linux-6.x.x.tar.xz

cd linux-6.x.x

Option 2: Clone Kernel Source Using Git

git clone https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git

cd linux

3. Configure the Kernel


1. Start with Existing Configuration

Copy the current system's kernel configuration file: cp /boot/config-$(uname -r) .config

2. Configure Kernel Options

 Open the configuration menu: make menuconfig

 Customize the kernel by enabling/disabling features, adding modules, or optimizing for your
hardware.

3. Save and Exit

Save your changes before exiting the configuration tool.

4. Compile the Kernel


1. Build the Kernel

Use make to compile: make -j$(nproc)

 Replace $(nproc) with the number of CPU cores to speed up compilation.

2. Build and Install Modules

sudo make modules_install

3. Install the Kernel

Install the newly built kernel:


sudo make install

5. Update the Bootloader


1. Update GRUB (Debian/Ubuntu)

After installation, update the GRUB configuration: sudo update-grub

2. Update GRUB (RHEL/CentOS)

Regenerate the GRUB configuration file: sudo grub2-mkconfig -o /boot/grub2/grub.cfg

6. Reboot into the New Kernel


Reboot the system to boot into the new kernel: sudo reboot

After rebooting, verify the new kernel is active: uname -r

7. Debugging Build Errors


If the build fails:

1. Check for errors in the output log.

2. Install any missing dependencies based on the error messages.

3. Clean the build directory: make clean

4. Retry the build process.

8. Testing and Validation


After the system reboots:

1. Verify the kernel version: uname -r

2. Test any new features or modules you added.

3. Check logs for errors: dmesg | less

9. Rebuilding for Updates


When updating to a newer kernel version:

1. Pull the latest source code: git pull

2. Clean the build directory: make clean

3. Repeat the configuration and build process.


Installing a Kernel in Linux
1. Install Precompiled Kernel (Easy Method)
 For Debian/Ubuntu:
sudo apt install linux-image-<version>

sudo update-grub

sudo reboot

uname -r

 For RHEL/CentOS:
sudo yum install kernel

sudo grub2-mkconfig -o /boot/grub2/grub.cfg

sudo reboot

uname -r

2. Build and Install Kernel from Source (Advanced Method)


1. Download Kernel Source:
wget https://cdn.kernel.org/pub/linux/kernel/v6.x/linux-6.x.x.tar.xz

tar -xvf linux-6.x.x.tar.xz

cd linux-6.x.x

2. Install Build Tools:


sudo apt install build-essential libncurses-dev bison flex libssl-dev libelf-dev

3. Configure Kernel:
make menuconfig

4. Compile and Install:


make -j$(nproc)

sudo make modules_install

sudo make install

sudo update-grub

sudo reboot
uname -r

Virtualization in Linux
Virtualization refers to creating virtual instances (or virtual machines) of physical hardware, allowing
multiple operating systems to run on a single machine simultaneously. It provides flexibility, efficient
resource use, and isolation between environments.

1. Types of Virtualization
1. Full Virtualization:

o A hypervisor emulates the entire hardware, allowing unmodified guest operating


systems to run.

o Examples: KVM, VMware.

2. Paravirtualization:

o The guest operating system is aware it's running in a virtualized environment and
communicates directly with the hypervisor.

o Examples: Xen (with paravirtualized guests).

3. Operating System-Level Virtualization:

o The host OS kernel provides isolated user-space environments, called containers.

o Examples: Docker, LXC (Linux Containers).

2. Hypervisors
A hypervisor is the software layer that enables virtualization by managing virtual machines.

 Type 1 Hypervisor (Bare-Metal):

o Runs directly on the hardware without an underlying operating system.

o Examples: VMware ESXi, Microsoft Hyper-V, Xen.

 Type 2 Hypervisor (Hosted):

o Runs on top of an existing operating system and relies on it for resource management.

o Examples: VirtualBox, VMware Workstation.

3. Virtualization Technologies in Linux


1. KVM (Kernel-based Virtual Machine):
o A Type 1 hypervisor built into the Linux kernel.

o Supports both full and paravirtualization.

o Manage VMs with tools like virt-manager and virsh.

2. Xen:

o A Type 1 hypervisor that can run paravirtualized or fully virtualized guests.

o Supports advanced features like live migration and resource allocation.

3. QEMU:

o An emulator and virtualization tool that can run on top of KVM or by itself as a user-
space hypervisor.

4. LXC (Linux Containers):

o OS-level virtualization that allows running multiple isolated Linux containers on a single
host without the overhead of VMs.

o LXC uses kernel namespaces and control groups for isolation.

4. Managing Virtualization
 Install KVM (Example on Ubuntu/Debian):

sudo apt install qemu-kvm libvirt-daemon-system libvirt-clients bridge-utils

 Check if KVM is supported:

kvm-ok

 Create and Manage Virtual Machines:

o Use virt-manager (GUI) or virsh (CLI).

o Start a VM with: virsh start <vm_name>

 Docker Containers (OS-Level Virtualization):

o Install Docker: sudo apt install docker.io

o Run a container: sudo docker run -it ubuntu bash

5. Benefits of Virtualization
 Resource Utilization: Run multiple operating systems on a single physical machine.

 Isolation: Keep different workloads and environments isolated.


 Testing and Development: Test software in different environments without needing multiple
physical machines.

 Disaster Recovery: Create snapshots of virtual machines for quick restoration.

Backup Management in Linux


Backup management is the process of creating copies of data to protect it from loss due to hardware
failure, human error, or other disasters. Effective backup strategies ensure that critical data can be
recovered with minimal downtime.

1. Types of Backups
1. Full Backup:

o A complete copy of all selected files or an entire system.

o Pros: Simple to restore.

o Cons: Time-consuming and requires more storage space.

2. Incremental Backup:

o Backs up only the files that have changed since the last backup (whether full or
incremental).

o Pros: Faster and requires less storage.

o Cons: Slower restoration (requires all incremental backups to be restored in sequence).

3. Differential Backup:

o Backs up all files that have changed since the last full backup.

o Pros: Faster restoration than incremental backups.

o Cons: Takes up more space than incremental backups.

4. Mirror Backup:

o A real-time duplicate of data (like a snapshot) with no compression.

o Pros: Fast access to data.

o Cons: Requires more storage and lacks versioning.

2. Backup Tools in Linux


1. rsync
 A powerful tool for copying and synchronizing files locally or remotely.

 Command: rsync -av /source/directory /backup/directory

o -a: Archive mode (preserves permissions, symlinks, etc.).

o -v: Verbose mode.

 Backup to Remote Server: rsync -avz /local/folder username@remote_server:/remote/folder

2. tar
 A utility to create compressed archives of files or directories.

 Full Backup: tar -cvpzf backup.tar.gz /home/user

o -c: Create a new archive.

o -v: Verbose output.

o -p: Preserve file permissions.

o -z: Compress with gzip.

o -f: Specify the filename.

3. dd
 A low-level tool used for making byte-for-byte copies of data, useful for creating disk images or
cloning disks.

 Backup a Disk: dd if=/dev/sda of=/backup/disk_image.img bs=64K conv=noerror,sync

o if: Input file (source device).

o of: Output file (destination).

o bs: Block size (64KB in this example).

o conv=noerror,sync: Continue on errors, padding with zeros.

4. dump and restore


 Tools for backing up and restoring file systems, especially useful for backing up ext2/ext3/ext4
file systems.

 Create a Backup: dump -0u -f /backup/dumpfile /dev/sda1

o -0: Level 0 full backup.

o -u: Update the /etc/dumpdates file.

 Restore a Backup: restore -rf /backup/dumpfile

5. Backup Software (GUI)


 Deja Dup (for GNOME-based desktop environments):

o A simple backup tool that supports scheduling and encryption.

o Can back up to local, remote, or cloud locations.

 Timeshift:

o Primarily used for creating and restoring system snapshots (similar to Windows Restore
Points).

o Useful for system backups and rollbacks.

3. Backup Strategies
1. Onsite vs. Offsite Backups
o Onsite: Store backups locally (e.g., on an external hard drive).

o Offsite: Store backups at a remote location (e.g., in the cloud or another physical
location) to protect against disasters like fire or theft.

2. Automated Backups
o Use cron jobs to automate backup tasks.

o Example (using rsync):

 Edit crontab:

 crontab -e

 Add a backup task that runs every night at 2 AM:

 0 2 * * * rsync -av /source/directory /backup/directory

3. Backup Retention
o Implement a strategy to retain a certain number of backups and delete older ones.

o Example:

 Keep daily backups for a week, weekly backups for a month, and monthly
backups for a year.

 Automate cleanup using find:

 find /backup/directory -type f -name "*.tar.gz" -mtime +30 -exec rm {} \;

4. Cloud Backups
1. Rclone:
o A command-line tool to manage files on cloud storage (e.g., Google Drive, AWS S3).
o Example:

 First, configure rclone:

 rclone config

 Backup to cloud storage:

 rclone sync /local/folder remote:backup-folder

2. Backup Solutions (Managed):


o Backblaze, Google Drive, Dropbox, and other cloud services can be used for backups
using tools like rclone, rsync, or native apps.

5. Restore From Backup


 rsync restore:

 rsync -av /backup/directory /restore/directory

 tar restore:

 tar -xvpzf backup.tar.gz -C /restore/directory

 Timeshift:

o If using Timeshift, select a restore point and click "Restore".

Installing a Kernel in Linux


1. Install Precompiled Kernel
 For Debian/Ubuntu:

sudo apt install linux-image-<version>

sudo update-grub

sudo reboot

uname -r

 For RHEL/CentOS:

sudo yum install kernel

sudo grub2-mkconfig -o /boot/grub2/grub.cfg


sudo reboot

uname -r

2. Install Kernel from Source


1. Download Kernel Source:

wget https://cdn.kernel.org/pub/linux/kernel/v6.x/linux-6.x.x.tar.xz

tar -xvf linux-6.x.x.tar.xz

cd linux-6.x.x

2. Install Dependencies (Ubuntu example):

sudo apt install build-essential libncurses-dev bison flex libssl-dev libelf-dev

3. Configure Kernel:

make menuconfig

4. Compile and Install:

make -j$(nproc)

sudo make modules_install

sudo make install

sudo update-grub

sudo reboot

uname -r

You might also like