0% found this document useful (0 votes)
7 views

Unit 2 (2)

Linux is a free, open-source operating system known for its customization, security, and reliability, widely used across various devices. It features multi-user capabilities, multi-tasking, and a variety of distributions, making it suitable for servers, development, IoT, cybersecurity, and scientific research. The document also provides instructions for setting up a Linux virtual machine and managing users, processes, and memory within the Linux environment.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Unit 2 (2)

Linux is a free, open-source operating system known for its customization, security, and reliability, widely used across various devices. It features multi-user capabilities, multi-tasking, and a variety of distributions, making it suitable for servers, development, IoT, cybersecurity, and scientific research. The document also provides instructions for setting up a Linux virtual machine and managing users, processes, and memory within the Linux environment.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Unit 2

Linux
Linux is a free, open-source operating system (OS) based on Unix.

It serves as the underlying platform for servers, desktops, smartphones,


and embedded devices.

It is highly customizable, secure, and widely used in both personal and


professional environments.

Key Features of Linux


Open Source
The source code is freely available for anyone to view, modify,
and distribute.

Multi-User System
Multiple users can access and use the system simultaneously.

Multi-Tasking
It efficiently handles multiple processes at the same time.

Portability
Linux can run on various hardware platforms with minimal
modifications.

Security
Built-in security features like file permissions, user authentication,
and firewall support.

Stability & Reliability


Rarely crashes and handles processes smoothly.

Variety of Distributions (Distros)


Includes Ubuntu, Fedora, Debian, Red Hat, and more, tailored for
different needs.

Common Uses of Linux

Unit 2 1
Servers & Web Hosting
Linux powers a majority of web servers worldwide due to its
reliability, security, and ability to handle high traffic efficiently.
Popular server solutions like Apache and Nginx often run on
Linux.

Development Platforms for Software Engineering


Linux provides robust tools and environments like GCC, Docker,
and version control systems, making it ideal for programming,
application development, and software testing.

IoT & Embedded Systems


Lightweight Linux distributions are widely used in IoT devices and
embedded systems due to their flexibility and ability to run on
limited hardware.

Cybersecurity & Penetration Testing


Security-focused distros like Kali Linux and Parrot OS offer pre-
installed tools for ethical hacking, vulnerability analysis, and
network defense.

Scientific Research & Simulations


Linux supports high-performance computing (HPC) for scientific
research, offering tools for data analysis, simulations, and running
computational models in disciplines like physics and
bioinformatics.
Instructions to Setup Linux VM
Step 1 : Download & Install VMware Workstation Player
1. Open your web browser and go to the VMware download page.

2. Click on Download Now and choose the Windows version.

3. Once the download is complete, run the installer and follow the
on-screen instructions to install VMware Workstation Player on
your Windows 11 machine.

Step 2 : Download Ubuntu 24.04 LTS ISO


1. Visit the Ubuntu website and download the Ubuntu 24.04 LTS ISO
file.

Unit 2 2
2. Save the ISO file to a location on your computer where you can
easily find it later.
Step 3 : Create a New Virtual Machine in VMware
Workstation Player
1. Open VMware Workstation Player and click on Create a New Virtual

Machine .

2. In the , select Installer disc image file (iso) and click


New Virtual Machine Wizard

Browse to locate the Ubuntu 24.04 LTS ISO file you downloaded.

3. Click Next to proceed.

4. Choose the Last Option then Linux

5. Choose Ubuntu 64 then Give name

6. Change Location if you want (Recommended)

7. Set the maximum disk size for the virtual machine. A minimum of
25 GB is recommended.

8. Choose whether to store the virtual disk as a single file or split it


into multiple files. Store Virtual Disk as a Single File is usually more
efficient.

9. Click Next to continue.

10. Click on Customize Hardware to adjust the virtual machine’s hardware


settings, such as memory, processors, and network settings.

11. Allocate at least 2 GB of RAM for better performance.

12. Adjust the number of CPU cores if necessary.

13. Click Close to save the hardware settings and then click Finish to
complete the virtual machine setup.

14. Select your newly created virtual machine in VMware Workstation


Player and click on Play Virtual Machine .

15. The virtual machine will boot from the Ubuntu ISO file. Follow the
on-screen instructions to start the installation process.

16. Click Edit VM Setting (For Any Changes).

User Management in Linux

Unit 2 3
User management in Linux is the process of creating, modifying, and
deleting user accounts and groups to control access to system
resources.

It ensures that users have appropriate permissions and privileges to


perform their tasks while maintaining system security.

Key Concepts of User Management


User Types
Root User (Superuser)

Has full control over the system.

Can modify any file, install/remove software, and manage


other users.

Identified by UID (User ID) 0.

Regular Users

Created by the administrator.

Have limited permissions and access only to their home


directories.

Assigned a unique UID ≥ 1000 (on modern Linux systems).

Systems Users (Service Accounts)

Used by system processes and applications.

Typically have UIDs between 1 and 999.

Managing Users
Creating Users
Add a New User

sudo useradd -m username

-m creates a home directory.

By default, no password is set.

Set a Password for the User

Unit 2 4
sudo passwd username

Prompts to enter and confirm a new password.

Add a User with a Specific Home Directory

sudo useradd -m -d/custom/path username

Create a User with a Specific UID

sudo useradd -u 1500 username

Create a User with a Specific Shell

sudo useradd -s /bin/bash username

Modifying Users
Change a User’s Username

sudo usermod -l new_username old_username

Change a User’s Home Directory

sudo usermod -d/new/home/path -m username

Change a User’s UID

sudo usermod -u 2000 username

Lock and Unlock a User Account

sudo usermod -L username #Lock the account


sudo usermod -U username #Unlock the account

Deleting Users
Delete a User Without Removing Home Directory

Unit 2 5
sudo userdel username

Leaves the home directory and files intact.

Delete a User and Their Home Directory

sudo userdel -r username

-r removes the home directory and mail spool.


Managing Groups
Types of Groups
Primary Group

Assigned when the user is created.

The user’s files belong to this group.

Secondary Group

Additional groups a user can belong to.

Group Management Commands


Create a Group

sudo groupadd groupname

Add a User to a Group

sudo usermod -aG groupname username

Change a User’s Primary Group

sudo usermod -g new_primary_group username

Remove a User from a Group

sudo gpasswd -d username groupname

Delete a Group

Unit 2 6
sudo groupdel groupname

Checking User Information


List All Users

cat /etc/passwd

Each line represents a user account.

Check User’s Groups

groups username

Get User Details

id username

Displays UID, GID (Group ID), and groups.

List All Groups

cat /etc/group

Check Last Login Information

last username

Managing User Permissions & Access


File Permissions

ls -l file.txt

Displays permissions like -rw -r --r-- (owner, group, others).

Change File Ownership

sudo chown user:group file.txt

Unit 2 7
Change File Permissions

chmod 755 script.sh

7 (rwx), 5 (r-x), 5 (r-x) for owner, group, others.


Disabling or Restricting Users
Disable a User Without Deleting

sudo usermod -L username

Locks the account

Expire a User’s Account

sudo chage -E 2025-01-01 username

Disables the account after January 1, 2025.

Prevent User Login (Disable Shell Access)

sudo usermod -s /usr/sbin/nologin username

Switching Between Users


Switch to Another User

su - username

Switches to username with their environment.

Execute a Command as Another User

sudo -u username command

UNIX Kernel-Level Services &


Commands
The UNIX kernel is the core component of the operating system
responsible for managing hardware and system resources.

Unit 2 8
It provides essential services such as process management, memory
management, file system handling, device management, and system
calls.

Process Management
Handles process creation, scheduling, and termination.

Executing Process Creation ( fork() )


The fork() function is used to create a new process in C.

#include <stdio.h>
#include <unistd.h>
int main()
{
pid_t pid = fork(); // Create a child process

if(pid>0)
{
printf("Parent Process, PID : %d\n",getpid());
}
else if(pid==0)
{
printf("Child PID : %d, Parent PID : %d\n", getpi(), getppi
d());
}
else
{
print("Fork Failed\n");
}

return 0;
}

Executing Process Execution ( exec() )


The exec() function replaces the current process with a new one.

#include <stdio.h>
#include <unistd.h>

Unit 2 9
int main()
{
printf("Befor exec()\n");
execlp("ls","ls","-l",NULL); //Execute 'ls -l' command
printf("This line will not execute if exec() succeeds\n");
return 0;
}

If exec() is successful, the second printf() statement will not


execute.
Executing Process Termination ( exit() )
The exit() function terminates a process.

#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("Process is running...\n");
exit(0); // Terminate the process
}

The process terminates immediately after printing the message.

Managing & Monitoring Processes


Built-in shell commands for process management.

View Running Processes ( ps & top )

ps → Displays currently running processes.

top → Provides real-time system resource usage.

ps aux # Show all running processes


ps -ef # Show all processes with user details
top # Show real-time process details

Killing a Process

kill <PID> → Terminates a process by its Process ID.

Find the process ID using :

Unit 2 10
ps aux | grep process_name

Terminate the process :

kill 1234 # (gentle kill)


kill -9 1234 # (force kill)

Adjusting Process Priority ( nice and renice )

nice/renice → Adjusts process priority.

Start a process with a lower priority :

nice -n 10 my_program # Run process with priority 10

Change priority of an existing process :

renice -5 -p 1234 # Set priority to -5 for process 1234

Managing Background Jobs ( jobs , fg and bg )

jobs → Lists background jobs.

fg/bg → Moves jobs between foreground & background.

Run a command in the background :

sleep 60 & # Run sleep command in the background

List background jobs :

jobs

Move a job to the foreground :

fg %1 # Bring job 1 to the foreground

Resume a background job :

Unit 2 11
bg %1 # Resume job 1 to the background

Managing High CPU Usage Process


Scenario

A system administrator notices that a process ( python3 script.py )


is consuming 90% CPU.

The system performance is degrading.

Problem Statement

How can we reduce the CPU priority of a process without


stopping it?

Steps to Solve

Find the Process ID (PID) of python3 script.py :

ps aux | grep python3

Lower the priority :

renice 10 -p 4567

Terminating a Hung Process


Scenario

A user’s terminal becomes unresponsive after running a


poorly optimized program.

The process does not terminate normally.

Problem Statement

How can we forcefully terminate an unresponsive process?

Solution

Use kill or kill -9 to terminate the process

Steps to Solve

Identify the PID

Unit 2 12
ps aux | grep unresponsive_program

Attempt to terminate gracefully :

kill 6789

If it does not respond, use a forceful kill :

kill -9 6789

Confirm termination :

ps aux | grep 6789

If the process no longer appears, it has been successfully


terminated.
Running & Managing Background Jobs
Scenario

A user runs a script that takes 10 minutes to complete but


needs to continue working in the terminal.

Problem Statement

How can the user continue using the terminal while keeping
the process running?

Solution

Run the script in the background and manage it using jobs , fg

and bg .

Steps to Solve

Run the script in the background :

./long_running_script.sh &

Check running background jobs :

Unit 2 13
jobs

Bring the process to the foreground :

fg %1

Send it back to the background :

bg %1

If the process no longer appears, it has been successfully


terminated.
Memory Management
Memory Management in Linux is a crucial aspect of system
performance monitoring.

The following commands help analyze and manage memory usage


efficiently.

Displays Available & Used Memory → free

The free command provides information about total, used, and


available memory, including swap memory.

Usage

free -h

Output

total → Total physical memory.

used → Memory currently in use.

free → Unused memory.

shared → Memory shared between processes.

Unit 2 14
buff/cache → Memory used for buffering and caching.

available → Memory available for new processes.

Additional Options

free -m → Show output in MB.

free -g → Show output in GB.

free -t → Display total memory, including swap.


Reports Memory, CPU, and Disk I/O Statistics → vmstat

The vmstat (Virtual Memory Statistics) command provides a


summary of memory usage, system performance, and disk I/O.

Output

procs (r,b) → Number of running (r) and blocked (b) processes.

memory (swpd, free, buff, cache) :

swpd → Swap memory used.

free → Free memory

buff → Memory used for buffers.

cache → Memory used for disk cache.

swap (si,so) :

si → Swap memory in.

so → Swap memory out.

io (bi,bo) :

bi → Blocks received from disk.

bo → Blocks sent to disk.

cpu (us,sy,id,wa,st) :

us → CPU usage by user processes.

sy → CPU usage by system processes.

Unit 2 15
id → Idle CPU.

wa → CPU waiting for I/O.

st → CPU stolen by virtual machines.

Additional Options

vmstat -s → Show memory statistics.

vmstat -d → Show disk statistics.


Shows Real-Time Memory Usage → top

The top command provides a dynamic real-time view of system


resource usage, including CPU, memory, and running processes.

Output

Header Information

load average → Average CPU load over 1, 5 and 15 minutes.

Tasks→ Number of total, running, sleeping, and zombie


processes.

CPU usage → Breakdown of CPU usage by user, system,


idle, etc.

Memory (Mem, Swap) → Displays physical and swap memory


usage.

Process Table (Columns)

PID → Process ID.

USER → User who owns the process.

PR → Priority.

NI → Nice value (priority adjustment).

VIRT → Virtual memory used.

RES → Resident memory used.

%CPU, %MEM → CPU & memory usage percentage.

Unit 2 16
COMMAND → Name of the running command.
Sets Memory Usage Limits for Users → ulimit

The ulimit command restricts the resource available to processes


running in a shell session.

Usage

ulimit -a

Set Memory Limits for a Process

ulimit -m 1048576 # Limit memory to 1GB (1024 * 1024 KB)


ulimit -n 2048 # Allow up to 2048 open files

Output

-m → Maximum memory a process can use.

-u → Maximum number of user processes.

-n → Maximum number of open file descriptors.

Key Differences Between User Process & System


Process

Feature User Process System Process

User (via terminal, GUI, or System (during boot or


Started By
script) as a service)

Firefox, Gedit, Python systemd, cron, sshd,


Examples
scripts mysqld

Runs in Foreground/Background Background (Daemon)

Unit 2 17
Feature User Process System Process

Some require sudo to


Can be killed by user? Yes, using kill
kill.

Command to check ps aux grep <process_name>

File System Management


Controls file access, storage, and permissions.

Key Functions
File Creation

Deletion

Access Control

Mounting

Commands
ls → Lists files and directories.

chmod → Changes file permissions.

chown → Changes file ownership.

df → Displays disk space usage.

du → Shows directory space usage.

mount/umount → Mounts and unmounts file systems.

fsck → Checks and repairs the file system.

Kernel-Level vs System-Level Services


Feature Kernel-Level Services System-Level Services

Core services of the OS Services running on top


Definition that directly interact with of the kernel to provide
hardware. system functionality.

System daemons, user


Managed By Kernel
commands

Process management, Networking, logging,


memory management, scheduling,
Functionality
device control, IPC, authentication, user
security process management.

Unit 2 18
Feature Kernel-Level Services System-Level Services

Process scheduling,
SSH, FTP, logging, web
memory paging, file
Example Services servers, firewall,
system operations,
cronjobs.
device drivers
systemcl, crontabm netstat,
Example Commands ps, kill, df, free, mount
tail -f /var/log/syslog

When interacting with When running system


When Used? hardware or system services, applications,
resources and networking tools.

Grep Command
Grep stands for Global Regular Expression Print.

Grep command search for a particular string/keyword from a file and


print lines matching a pattern.

It check line by line and print lines matching given pattern.

We can use grep anywhere like with files, searching for file, directories
etc.

Cases of Grep Command


Case 1
To ignore the upper and lower case while searching.

grep -i "keyword" file

Case 2
To search everything except given pattern/keyword.

grep -v "keyword" file

Case 3
To print how many times (count) given keyword present

grep -c "keyword" file

Case 4

Unit 2 19
To search for exact match of given keyword in a file.

grep -w "keyword" file

Case 5
To print the line no. of matches of given keyword in a file.

grep -n "keyword" file

Case 6
To search a given keyword in multiple files.

grep "keyword" file1 file2 file3

Case 7
To suppress file names while searching a given keyword in
multiple files.

grep -h "keyword" file1 file2 file3

Case 8
To search multiple keywords in a file.

grep -E "keyword1|keyword2|keyword3" file

Case 9
To search multiple keywords in multiple files.

grep -E "keyword1|keyword2|keyword3" file1 file2 file3

Case 10
To only print file names which match given keywords.

grep -l "keyword" *

Unit 2 20
Case 11
To get the keywords/patterns from a file and match with another
file.

grep -f keywords file

Case 12
To print the matching line which starts with a given keyword.

grep "^keyword" file

Case 13
To print the matching line which ends with a given keyword.

grep "keyword$" file

Case 14
To search a keyword in all 100 files in a directory (dirA).

grep "keyword" dirA/*

Case 15
We can use egrep command for multiple keyword search.

egrep "keyword1|keyword2|keyword3" file

Case 16
To search but not print on terminal or to suppress error messages.

grep "keyword" file > /dev/null 2>&1

Compile & Install Linux Kernel from


Source Code
Step 1 : Install Required Dependencies

Unit 2 21
Install the necessary packages.

sudo apt update && sudo apt upgrade -y # For Debian/Ubuntu-b


ased systems
sudo apt install build-essential libncurses-dev bison flex libssl-de
v libelf-dev bc -y

Step 2 : Download the Latest Kernel Source


Code
Visit the official kernel website to find the latest stable kernel version.

cd /usr/src
sudo wget https://cdn.kernel.org/pub/linux/kernel/v6.x/linux-6.8.t
ar.xz # Replace with latest version
sudo tar -xvf linux-6.8.tar.xz
cd linux-6.8

Step 3 : Configure the Kernel


You can either use the default configuration or customize it.

sudo cp -v /boot/config-$(uname -r) .config # Use existing confi


g
sudo make menuconfig # Optional: Customize kernel options (re
quires ncurses)

If you just want to use the default settings.

sudo make olddefconfig

Step 4 : Compile the Kernel


Now, compile the Linux kernel. This process can take a long time
depending on your CPU.

sudo make -j$(nproc) # Compile kernel using all CPU cores

Step 5 : Install Kernel Modules

Unit 2 22
Once the kernel is compiled, install the modules.

sudo make modules_install

Step 6 : Install the New Kernel


Now install the newly compiled kernel.

sudo make install

Step 7 : Update Bootloader (GRUB)


After installing the kernel, update GRUB to recognize it.

sudo update-grub # For Debian/Ubuntu

Step 8 : Reboot & Verify


Reboot your system to apply the new kernel.

sudo reboot

Once the system reboots, verify the installed kernel version :

uname -r

It should display the newly installed kernel version.

Unit 2 23

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy