0% found this document useful (0 votes)
17 views60 pages

Linux Q&a

The document provides an overview of Linux, including its distributions, file system structure, basic commands, user and group management, and the Linux boot process. It covers various Linux flavors, their package management systems, and essential commands for file handling, process management, and networking. Additionally, it explains the significance of directories like /etc and /bin, and details on user creation and permission management.

Uploaded by

vinoth
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)
17 views60 pages

Linux Q&a

The document provides an overview of Linux, including its distributions, file system structure, basic commands, user and group management, and the Linux boot process. It covers various Linux flavors, their package management systems, and essential commands for file handling, process management, and networking. Additionally, it explains the significance of directories like /etc and /bin, and details on user creation and permission management.

Uploaded by

vinoth
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/ 60

RAMMOHAN. L Sr.

Linux Administator

Linux, AWS Interview Questions and Answers


Basic Linux Concepts
Linux is a powerful and flexible operating system commonly used in servers, desktops, and embedded
systems.

Linux Distributions

Linux comes in various flavors, called distributions (distros). Some popular ones include:

• Ubuntu (user-friendly, great for beginners)


• Debian (stable and widely used)
• Fedora (cutting-edge technologies)
• CentOS/Rocky Linux (enterprise-focused)
• Arch Linux (customizable, rolling release)

Linux File System Structure

Linux follows a hierarchical file system. Important directories include:

• / → Root directory (everything starts here)


• /home/ → User home directories (e.g., /home/user)
• /etc/ → Configuration files
• /bin/ → Essential binary programs
• /var/ → Variable data (logs, caches)
• /tmp/ → Temporary files
• /dev/ → Device files
• /mnt/ & /media/ → Mounted drives

Basic Linux Commands


File & Directory Commands

• ls → List files in a directory


• cd <directory> → Change directory
• pwd → Show current directory
• mkdir <dirname> → Create a directory
• rm <filename> → Remove a file
• rmdir <dirname> → Remove an empty directory
• rm -r <dirname> → Remove a directory and its contents
• cp <src> <dest> → Copy files or directories
• mv <src> <dest> → Move (rename) files or directories

File Viewing Commands

• cat <filename> → View file contents


• less <filename> → View file with scrolling
• head <filename> → Show first 10 lines of a file
• tail <filename> → Show last 10 lines of a file
RAMMOHAN. L Sr. Linux Administator

File Permissions

• ls -l → Show file permissions


• chmod 755 <filename> → Change file permissions
• chown user:group <filename> → Change file owner

User & Group Management


• whoami → Show current user
• id → Show user ID (UID) and group ID (GID)
• adduser <username> → Add a new user
• passwd <username> → Change user password
• usermod -aG <group> <user> → Add user to a group
• deluser <username> → Remove a user

Process Management
• ps aux → Show running processes
• top → Real-time process monitoring
• kill <PID> → Terminate a process
• killall <process-name> → Kill a process by name

Networking Commands
• ip a or ifconfig → Show network interfaces
• ping <hostname> → Check connectivity
• netstat -tulnp → Show network connections
• curl <URL> → Fetch data from a URL
• wget <URL> → Download files

Package Management
Linux uses package managers to install and update software:

• Debian-based (Ubuntu, Debian): apt (e.g., sudo apt update && sudo apt install <package>)
• RHEL-based (CentOS, Fedora, Rocky Linux): dnf or yum
• Arch Linux: pacman

Log Files & Monitoring


• /var/log/syslog → System logs
• /var/log/auth.log → Authentication logs
• dmesg → Kernel logs
• journalctl → View systemd logs
RAMMOHAN. L Sr. Linux Administator

System Services & Daemons


• systemctl status <service> → Check service status
• systemctl start <service> → Start a service
• systemctl stop <service> → Stop a service
• systemctl enable <service> → Enable a service at boot

2. Have you worked on Linux?

Yes! I have extensive knowledge of Linux, including its commands, system administration, shell
scripting, networking, security, and troubleshooting.

✅ Basic Commands & Navigation


✅ Shell Scripting & Automation
✅ User & File Permissions Management
✅ Networking & Server Configuration
✅ System Monitoring & Performance Tuning
✅ Security & Hardening
✅ Containerization (Docker, Podman, Kubernetes)
✅ Package Management (APT, YUM, DNF, Pacman, etc.)

3. What are the different Linux flavors?

1. Debian-Based Distributions
These distros are known for their stability and extensive package repositories.

🔹 Debian

✅ Best for: Servers & stability-focused users


✅ Why? Extremely stable, supports multiple architectures, and has a massive package
repository.
🔹 Package Manager: apt

🔹 Ubuntu (Based on Debian)

✅ Best for: Beginners, desktops, and cloud environments


✅ Why? User-friendly, frequent updates, and strong community support.
🔹 Variants:

• Ubuntu Desktop (for general users)


• Ubuntu Server (for hosting & enterprise use)
• Ubuntu LTS (Long-Term Support, for stability)
RAMMOHAN. L Sr. Linux Administator

🔹 Linux Mint (Based on Ubuntu/Debian)

✅ Best for: Windows users switching to Linux


✅ Why? Easy-to-use interface with Cinnamon desktop, pre-installed media codecs.

2. Red Hat-Based Distributions


These are enterprise-grade distros known for security and reliability.

🔹 Red Hat Enterprise Linux (RHEL)

✅ Best for: Enterprises & large organizations


✅ Why? Paid support, security updates, and enterprise features.
🔹 Package Manager: dnf (formerly yum)

🔹 Fedora (Community Version of RHEL)

✅ Best for: Developers & those who want cutting-edge software


✅ Why? Latest features, upstream development for RHEL, fast updates.

🔹 CentOS / Rocky Linux / AlmaLinux

✅ Best for: Servers & enterprise environments


✅ Why? Free alternatives to RHEL with enterprise-level stability.

• CentOS Stream → Rolling-release version (not a full RHEL clone).


• Rocky Linux / AlmaLinux → Direct replacements for CentOS with long-term stability.

3. Arch-Based Distributions
These are lightweight, rolling-release distros designed for advanced users.

🔹 Arch Linux

✅ Best for: Power users & customization lovers


✅ Why? Minimalistic, rolling-release updates, full customization.
🔹 Package Manager: pacman
RAMMOHAN. L Sr. Linux Administator

🔹 Manjaro (Based on Arch)

✅ Best for: Beginners who want Arch’s power with easier installation
✅ Why? Pre-configured desktop environments, rolling updates, strong community.

4. SUSE-Based Distributions
Enterprise-focused and widely used in business environments.

🔹 openSUSE

✅ Best for: Enterprise users & system administrators


✅ Why? Stability, enterprise tools, and YaST (easy system management).
🔹 Variants:

• openSUSE Leap → Stable, point-release model


• openSUSE Tumbleweed → Rolling release, cutting-edge software

🔹 SUSE Linux Enterprise Server (SLES)

✅ Best for: Large enterprises & cloud computing


✅ Why? Strong enterprise support, scalability, and security.

5. Lightweight & Specialized Distros


For older hardware, embedded systems, or unique use cases.

🔹 Puppy Linux

✅ Best for: Very old computers (lightweight & fast)


✅ Why? Runs entirely in RAM, small footprint (~300MB).

🔹 Alpine Linux

✅ Best for: Containers & embedded systems


✅ Why? Security-focused, minimalistic, used in Docker images.

🔹 Kali Linux

✅ Best for: Ethical hacking & cybersecurity


✅ Why? Pre-installed penetration testing tools, forensic tools.
RAMMOHAN. L Sr. Linux Administator

🔹 Parrot OS

✅ Best for: Security professionals & privacy-focused users


✅ Why? Lightweight alternative to Kali Linux, great for digital forensics.

4. What is the Linux boot process?

1. BIOS
▪ BIOS stands for Basic Input/Output System
▪ Performs some system integrity checks
▪ Searches, loads, and executes the boot loader program.
▪ It looks for boot loader in floppy, cd-rom, or hard drive. You can press a key (typically F12 of
F2, but it depends on your system) during the BIOS startup to change the boot sequence.
▪ Once the boot loader program is detected and loaded into the memory, BIOS gives the control to
it.
▪ So, in simple terms BIOS loads and executes the MBR boot loader.

2. MBR
▪ MBR stands for Master Boot Record.
▪ It is located in the 1st sector of the bootable disk. Typically /dev/hda, or /dev/sda
▪ MBR is less than 512 bytes in size. This has three components 1) primary boot loader info in 1st
446 bytes 2) partition table info in next 64 bytes 3) mbr validation check in last 2 bytes.
▪ It contains information about GRUB (or LILO in old systems).
▪ So, in simple terms MBR loads and executes the GRUB boot loader.

3. GRUB
▪ GRUB stands for Grand Unified Bootloader.
▪ If you have multiple kernel images installed on your system, you can choose which one to be
executed.
▪ GRUB displays a splash screen, waits for few seconds, if you don’t enter anything, it loads the
default kernel image as specified in the grub configuration file.
▪ GRUB has the knowledge of the filesystem (the older Linux loader LILO didn’t understand
filesystem).
▪ Grub configuration file is /boot/grub/grub.conf (/etc/grub.conf is a link to this). The following is
sample grub.conf of CentOS.

#boot=/dev/sda

default=0

timeout=5

splashimage=(hd0,0)/boot/grub/splash.xpm.gz

hiddenmenu
RAMMOHAN. L Sr. Linux Administator

title CentOS (2.6.18-194.el5PAE)

root (hd0,0)

kernel /boot/vmlinuz-2.6.18-194.el5PAE ro root=LABEL=/

initrd /boot/initrd-2.6.18-194.el5PAE.img

▪ As you notice from the above info, it contains kernel and initrd image.
▪ So, in simple terms GRUB just loads and executes Kernel and initrd images.

4. Kernel
▪ Mounts the root file system as specified in the “root=” in grub.conf
▪ Kernel executes the /sbin/init program
▪ Since init was the 1st program to be executed by Linux Kernel, it has the process id (PID) of 1.
Do a ‘ps -ef | grep init’ and check the pid.
▪ initrd stands for Initial RAM Disk.
▪ initrd is used by kernel as temporary root file system until kernel is booted and the real root file
system is mounted. It also contains necessary drivers compiled inside, which helps it to access the
hard drive partitions, and other hardware.

5. Init
▪ Looks at the /etc/inittab file to decide the Linux run level.
▪ Following are the available run levels
▪ 0 – halt
▪ 1 – Single user mode
▪ 2 – Multiuser, without NFS
▪ 3 – Full multiuser mode
▪ 4 – unused
▪ 5 – X11
▪ 6 – reboot
▪ Init identifies the default initlevel from /etc/inittab and uses that to load all appropriate program.
▪ Execute ‘grep initdefault /etc/inittab’ on your system to identify the default run level
▪ If you want to get into trouble, you can set the default run level to 0 or 6. Since you know what 0
and 6 means, probably you might not do that.
▪ Typically you would set the default run level to either 3 or 5.

6. Runlevel programs
▪ When the Linux system is booting up, you might see various services getting started. For
example, it might say “starting sendmail …. OK”. Those are the runlevel programs, executed
from the run level directory as defined by your run level.
▪ Depending on your default init level setting, the system will execute the programs from one of
the following directories.
▪ Run level 0 – /etc/rc.d/rc0.d/
▪ Run level 1 – /etc/rc.d/rc1.d/
RAMMOHAN. L Sr. Linux Administator

▪Run level 2 – /etc/rc.d/rc2.d/


▪Run level 3 – /etc/rc.d/rc3.d/
▪Run level 4 – /etc/rc.d/rc4.d/
▪Run level 5 – /etc/rc.d/rc5.d/
▪Run level 6 – /etc/rc.d/rc6.d/
▪ Please note that there are also symbolic links available for these directory under /etc directly. So,
/etc/rc0.d is linked to /etc/rc.d/rc0.d.
▪ Under the /etc/rc.d/rc*.d/ directories, you would see programs that start with S and K.
▪ Programs starts with S are used during startup. S for startup.
▪ Programs starts with K are used during shutdown. K for kill.
▪ There are numbers right next to S and K in the program names. Those are the sequence number in
which the programs should be started or killed.
▪ For example, S12syslog is to start the syslog deamon, which has the sequence number of 12.
S80sendmail is to start the sendmail daemon, which has the sequence number of 80. So, syslog
program will be started before sendmail.

5. What is a Linux filesystem? What are /etc and /bin?


A Linux filesystem is the way files and directories are stored, organized, and accessed on a Linux
system. Unlike Windows (which uses drive letters like C:, D:), Linux uses a single hierarchical
structure starting from the root directory (/), where everything is stored.

Common Linux Filesystem Types

• ext4 → Default in most Linux distributions (Ubuntu, Debian, etc.).


• XFS → Used in enterprise environments (RHEL, CentOS).
• Btrfs → Supports snapshots and advanced features.
• ZFS → Great for data integrity, used in enterprise and NAS systems.
• FAT32/exFAT/NTFS → Used for compatibility with Windows.

What is /etc?
• /etc contains system-wide configuration files.
• It stores settings for services, applications, users, networking, and more.
• Examples of important files in /etc:
o /etc/passwd → User account information.
o /etc/shadow → Encrypted passwords.
o /etc/hosts → Maps hostnames to IPs.
o /etc/resolv.conf → DNS configuration.
o /etc/fstab → Filesystem mount points.
o /etc/ssh/sshd_config → SSH server settings.

What is /bin?
• /bin (shortfor "binary") contains essential system programs (executables).
• These are critical commands needed for basic system functionality.
• Examples of important commands in /bin:
o /bin/ls → List files in a directory.
o /bin/cp → Copy files.
o /bin/mv → Move/rename files.
o /bin/rm → Remove files.
o /bin/cat → View file contents.
RAMMOHAN. L Sr. Linux Administator

o /bin/bash → Default shell.

🔹 Difference between /bin and /sbin:

• /bin → Commands available to all users (e.g., ls, cp, mv).


• /sbin → Commands for system administration (root-only commands like fdisk, reboot).

User & Permission Management

6. How to create a user and give permissions?

Create a New User


To create a new user, use the adduser or useradd command.

Using adduser (Recommended)


sudo adduser username

• This creates a new user and their home directory (/home/username).


• It also prompts you to set a password.

Using useradd (Manual Setup)


sudo useradd -m -s /bin/bash username
sudo passwd username # Set password manually

• -m → Creates a home directory.


• -s /bin/bash → Sets the default shell.

Add the User to a Group


Groups help manage permissions for multiple users.

Check Existing Groups


cat /etc/group
Add User to a Group
sudo usermod -aG groupname username

Example:

sudo usermod -aG sudo username # Give sudo (admin) rights

• -aG → Adds the user to a group without removing them from other groups.

Check User Groups


groups username

File & Directory Permissions


RAMMOHAN. L Sr. Linux Administator

Linux uses read (r), write (w), execute (x) permissions for:

• Owner (User who owns the file)


• Group (Users in the same group)
• Others (Everyone else)

View Permissions
ls -l filename

Example output:

-rwxr--r-- 1 user group 1234 Jan 1 12:00 file.txt

• rwx → Owner has read, write, execute permissions.


• r-- → Group has read permission.
• r-- → Others have read permission.

Change File/Directory Permissions (chmod)


Grant Execute Permission to a File
chmod +x script.sh
Set Specific Permissions
bash
chmod 755 file.txt

• 7 → Owner: rwx
• 5 → Group: r-x
• 5 → Others: r-x

Recursive Permission Change (for directories)


bash
chmod -R 755 /path/to/directory

Change File Ownership (chown)


Change Owner

sudo chown username file.txt


Change Owner & Group

sudo chown username:groupname file.txt

Recursive Ownership Change (for directories)


sudo chown -R username:groupname /path/to/directory

Give a User Sudo (Admin) Privileges


RAMMOHAN. L Sr. Linux Administator

Add User to the sudo Group


sudo usermod -aG sudo username # For Debian/Ubuntu
sudo usermod -aG wheel username # For RHEL/CentOS/Fedora

Test Sudo Access

Switch to the new user:

su - username

Run a test command:

sudo ls /root

7. How to add a user to an existing group in Linux?

Check Existing Groups


Before adding a user, check available groups:

cat /etc/group

or

groups

(This shows the groups of the currently logged-in user.)

To check a specific user's groups:

groups username

Add a User to an Existing Group


Using usermod (Recommended)
sudo usermod -aG groupname username

• -aG → Append (-a) user to Group (-G) (Prevents removal from other groups).
• Example: Add user john to the docker group:

sudo usermod -aG docker john

Verify Group Membership


After adding the user, confirm their groups:

groups username
RAMMOHAN. L Sr. Linux Administator

or

id username

Example output:

uid=1001(john) gid=1001(john) groups=1001(john),998(docker)

Make Changes Take Effect


The user must log out and log back in for the group changes to take effect.
Alternatively, force a session reload:

su - username

or

newgrp groupname

(Temporarily applies the group change in the current session.)

Remove a User from a Group (Optional)


To remove a user from a group:

sudo gpasswd -d username groupname

Example:

sudo gpasswd -d john docker

8. How to change the owner permissions of a user or a file?

Change File Ownership (chown)


The chown (change owner) command changes the owner or group of a file/directory.

Change the Owner of a File


sudo chown newuser filename

🔹 Example: Assign ownership of file.txt to john

sudo chown john file.txt


RAMMOHAN. L Sr. Linux Administator

Change the Owner and Group


sudo chown newuser:newgroup filename

🔹 Example: Change owner to john and group to developers

sudo chown john:developers file.txt


Change Ownership of a Directory (Recursive)
sudo chown -R newuser:newgroup /path/to/directory

🔹 Example: Assign /var/www to www-data

sudo chown -R www-data:www-data /var/www

• -R → Recursively changes ownership for all files inside the directory.

Change File Permissions (chmod)


The chmod (change mode) command modifies read, write, execute permissions.

Change Permissions Using Numeric Mode

Each permission level is represented by a number:

• 4 → Read (r)
• 2 → Write (w)
• 1 → Execute (x)

Syntax:

chmod xyz filename

• x → Owner permissions
• y → Group permissions
• z → Others' permissions

🔹 Example: Grant read (4), write (2), execute (1) permissions to the owner and read &
execute to others:

chmod 755 file.txt

🔹 Breakdown:

• 7 → Owner (rwx = 4+2+1)


• 5 → Group (r-x = 4+0+1)
• 5 → Others (r-x = 4+0+1)
RAMMOHAN. L Sr. Linux Administator

Change Permissions Using Symbolic Mode


chmod u+x filename # Add execute permission to the user
chmod g-w filename # Remove write permission for group
chmod o+r filename # Add read permission for others

• u → Owner (User)
• g → Group
• o → Others
• a → All (User, Group, Others)

🔹 Example: Grant execute permission to everyone:

chmod a+x script.sh

Verify File Ownership & Permissions


To check file permissions and ownership, use:

ls -l filename

Example output:

-rwxr--r-- 1 john developers 1234 Jan 1 12:00 file.txt

• john → Owner
• developers → Group
• rwxr--r-- → Permissions

Change Ownership of a User's Home Directory


If you need to transfer ownership of a user’s home directory:

sudo chown -R newuser:newgroup /home/newuser

🔹 Example: Change home directory ownership for user alex

sudo chown -R alex:alex /home/alex

Special Permissions (chmod Advanced)


Set a File as Read-Only
chmod 444 file.txt
Make a File Executable
chmod +x script.sh
RAMMOHAN. L Sr. Linux Administator

Prevent Others from Accessing a File


chmod 700 file.txt

Process & Resource Management

9. What is process management?

A process is any running instance of a program in Linux. Each process has a unique Process
ID (PID) and can be in different states like running, sleeping, or stopped.

Linux process management allows you to create, monitor, control, and terminate processes
to ensure system efficiency.

Viewing Processes
To manage processes, you need to see what’s running.

Check Running Processes


ps aux

• a → Show processes of all users.


• u → Display user details.
• x → Show background processes.

🔹 Example Output:

USER PID %CPU %MEM TIME COMMAND


root 1 0.1 0.3 00:00 /sbin/init
john 1245 2.5 1.0 00:01 firefox

Dynamic Process Monitoring


top

or

htop # (Better UI, but may require installation)

• Shows real-time CPU and memory usage.


• Press q to exit.

Controlling Processes
You can stop, restart, or change priority of a process.

Kill a Process by PID


kill PID

🔹 Example: Kill Firefox process (PID 1245)


RAMMOHAN. L Sr. Linux Administator

kill 1245
Force Kill a Process
kill -9 PID

🔹 Example: Forcefully stop a frozen process

kill -9 1245
Kill a Process by Name
pkill process_name

🔹 Example: Kill all instances of Firefox

pkill firefox
Stop (Pause) a Process
kill -STOP PID
Resume a Paused Process
kill -CONT PID

Running Processes in the Background & Foreground


Run a Process in the Background

Add & at the end of the command.

firefox &
Check Background Jobs
jobs
Bring a Process to Foreground
fg %job_id
Send a Running Process to Background

Press Ctrl + Z to pause a process, then run:

bg

Managing Process Priorities (nice & renice)


Processes have priority values (-20 to 19).

• Lower value (-20) → Higher priority.


• Higher value (19) → Lower priority.

Start a Process with a Lower Priority


nice -n 10 command

🔹 Example: Start a backup with low priority


RAMMOHAN. L Sr. Linux Administator

nice -n 19 tar -czf backup.tar.gz /home &


Change Priority of a Running Process
renice -n priority -p PID

🔹 Example: Lower priority of PID 1245

renice -n 10 -p 1245

Check System-Wide Resource Usage


vmstat

or

iostat

• Useful for debugging CPU, memory, disk issues.

10. How to check disk space in Linux?

Check Disk Space Usage (df Command)


The df (disk free) command displays the available and used disk space on all mounted
filesystems.

Basic Usage
df -h

🔹 Explanation:

• -h → Human-readable format (MB, GB, TB).

🔹 Example Output:

Filesystem Size Used Avail Use% Mounted on


/dev/sda1 100G 40G 60G 40% /
tmpfs 2.0G 100M 1.9G 5% /run
/dev/sdb1 500G 250G 250G 50% /data

• Size → Total disk size.


• Used → Space already used.
• Avail → Free space available.
• Use% → Percentage of used space.
• Mounted on → The mount point (where it's attached in the system).
RAMMOHAN. L Sr. Linux Administator

Check Directory Size (du Command)


The du (disk usage) command shows space used by files and directories.

Check a Specific Directory Size


du -sh /path/to/directory

🔹 Example:

du -sh /var/log

• -s → Show only the total size.


• -h → Human-readable format.

Check Sizes of All Folders in Current Directory


du -sh *

🔹 Example Output:

1.2G Documents
500M Downloads
3.8G Videos

Find Largest Files


To find the largest files consuming disk space:

find / -type f -size +1G -exec ls -lh {} + 2>/dev/null

🔹 This finds files larger than 1GB.

Or, list the top 10 largest files:

du -ah / | sort -rh | head -10

Check Inode Usage (df -i)


If you can't create new files despite having space, check inodes:

df -i

• If Use% is close to 100%, you need to free up inodes (delete small files).
RAMMOHAN. L Sr. Linux Administator

GUI Method (For Desktop Users)


If using a Linux desktop, you can check disk space via:

• GNOME Disks Utility (gnome-disks)


• KDiskFree (kdiskfree)

11. How to check memory usage in Linux?

Check Memory Usage with free Command


The free command provides an overview of memory usage in the system.

Basic Usage
free -h

• -h → Human-readable format (GB, MB).

Example Output:
total used free shared buff/cache available
Mem: 16G 4.5G 8.3G 300M 3.2G 10G
Swap: 4.0G 0B 4.0G

• total → Total memory available.


• used → Memory currently in use.
• free → Free memory available.
• shared → Memory used by tmpfs (shared between processes).
• buff/cache → Memory used by buffers and cache (can be reclaimed).
• available → Memory available for new processes without swapping.

Monitor Real-Time Memory Usage with top/htop


• top is a real-time system monitor.
• htop is an enhanced version with better visuals (requires installation).

Using top:
top

• Look for the %MEM column to see memory usage by process.

Using htop:
htop

• htop provides a more user-friendly, color-coded interface.


• Press F6 to sort by memory usage.
RAMMOHAN. L Sr. Linux Administator

Check Memory Usage with vmstat


The vmstat command provides detailed information on memory, processes, and system
performance.

Basic Usage:
vmstat -s

This shows a snapshot of memory usage, including swap usage, buffer memory, free
memory, etc.

Example Output:
16777216 K total memory
1048576 K used memory
102400 K active memory
204800 K inactive memory
4096000 K free memory
1048576 K buffer memory
2048000 K swap cache

Check Memory Usage by Process (ps Command)


To see memory usage of specific processes, use ps.

Check Memory Usage of All Processes:


ps aux --sort=-%mem

• --sort=-%mem sorts processes by memory usage (highest first).

Example Output:
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.1 0.2 166432 8248 ? Ss Jan21 0:10 /sbin/init
john 1245 2.5 5.0 1234567 94500 ? Sl Jan21 3:50 firefox

• %MEM → Percentage of physical memory used by the process.


• RSS → Resident Set Size (amount of memory the process is currently using).

Check Cache and Buffers Usage


Memory used for cache and buffers can often be reclaimed.

Use free to View Buffers/Cache:


free -h

• buff/cache → Shows memory used for buffers and cache (can be freed up if needed).

Use cat to View Cache:


cat /proc/meminfo | grep -i cache
RAMMOHAN. L Sr. Linux Administator

Monitor Swap Usage


Swap space is used when physical memory is full.

Check Swap Usage:


swapon -s

or

free -h

• Swap usage is listed under Swap.

Check Memory Usage by Specific Process (pmap Command)


The pmap command provides memory usage details of a specific process.

Basic Usage:
pmap -x PID

🔹 Example: To check the memory usage of a process with PID 1245:

pmap -x 1245

12. What does the top command display?

Check Memory Usage with free Command


The free command provides an overview of memory usage in the system.

Basic Usage
free -h

• -h → Human-readable format (GB, MB).

Example Output:
total used free shared buff/cache available
Mem: 16G 4.5G 8.3G 300M 3.2G 10G
Swap: 4.0G 0B 4.0G

• total → Total memory available.


• used → Memory currently in use.
• free → Free memory available.
• shared → Memory used by tmpfs (shared between processes).
• buff/cache → Memory used by buffers and cache (can be reclaimed).
• available → Memory available for new processes without swapping.
RAMMOHAN. L Sr. Linux Administator

Monitor Real-Time Memory Usage with top/htop


• top is a real-time system monitor.
• htop is an enhanced version with better visuals (requires installation).

Using top:
top

• Look for the %MEM column to see memory usage by process.

Using htop:
htop

• htop provides a more user-friendly, color-coded interface.


• Press F6 to sort by memory usage.

Check Memory Usage with vmstat


The vmstat command provides detailed information on memory, processes, and system
performance.

Basic Usage:
vmstat -s

This shows a snapshot of memory usage, including swap usage, buffer memory, free
memory, etc.

Example Output:
16777216 K total memory
1048576 K used memory
102400 K active memory
204800 K inactive memory
4096000 K free memory
1048576 K buffer memory
2048000 K swap cache

Check Memory Usage by Process (ps Command)


To see memory usage of specific processes, use ps.

Check Memory Usage of All Processes:


ps aux --sort=-%mem

• --sort=-%mem sorts processes by memory usage (highest first).


RAMMOHAN. L Sr. Linux Administator

Example Output:
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.1 0.2 166432 8248 ? Ss Jan21 0:10 /sbin/init
john 1245 2.5 5.0 1234567 94500 ? Sl Jan21 3:50 firefox

• %MEM → Percentage of physical memory used by the process.


• RSS → Resident Set Size (amount of memory the process is currently using).

Check Cache and Buffers Usage


Memory used for cache and buffers can often be reclaimed.

Use free to View Buffers/Cache:


free -h

• buff/cache → Shows memory used for buffers and cache (can be freed up if needed).

Use cat to View Cache:


cat /proc/meminfo | grep -i cache

Monitor Swap Usage


Swap space is used when physical memory is full.

Check Swap Usage:


swapon -s

or

free -h

• Swap usage is listed under Swap.

Check Memory Usage by Specific Process (pmap Command)


The pmap command provides memory usage details of a specific process.

Basic Usage:
pmap -x PID

🔹 Example: To check the memory usage of a process with PID 1245:

pmap -x 1245
RAMMOHAN. L Sr. Linux Administator

Storage & Partitioning

13. What is the use of the lsblk command in Linux?


The lsblk command in Linux is used to list information about all block devices in the system.
Block devices are devices that store data in fixed-size blocks, such as hard drives, SSDs, USB
drives, and other storage devices. It provides a detailed view of these devices, including their
partition structure, mount points, and sizes.

Key Uses of the lsblk Command:

1. View Block Devices: Displays information about all available block devices on the system.
2. Check Partition Structure: Shows the partitions within block devices and how they are
organized.
3. Check Mount Points: Lists where each block device is mounted in the filesystem.
4. Display Device Sizes: Provides the size of each device or partition.

Basic Syntax
lsblk [options]

Common Options with lsblk:

• -a: Display all devices (including empty devices that are not mounted).

lsblk -a

• -f: Show file system information (such as type, label, UUID).

lsblk -f

• -l: Display devices in a list format (useful for scripting).

lsblk -l

• -o: Specify which columns to display, such as NAME, SIZE, TYPE, MOUNTPOINT.

lsblk -o NAME,SIZE,TYPE,MOUNTPOINT

• -n: Output without column headers, just the device names.

lsblk -n

Example Outputs
Basic lsblk Output:
lsblk

Example Output:

NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT


sda 8:0 0 500G 0 disk
RAMMOHAN. L Sr. Linux Administator

├─sda1 8:1 0 500M 0 part /boot


└─sda2 8:2 0 499.5G 0 part /
sdb 8:16 0 1.8T 0 disk
└─sdb1 8:17 0 1.8T 0 part /mnt/data

• NAME: The name of the device or partition.


• SIZE: The size of the device or partition.
• TYPE: Indicates whether it is a disk (disk) or partition (part).
• MOUNTPOINT: Where the partition is mounted (e.g., /, /boot, /mnt/data).

With Filesystem Information (-f):


lsblk -f

Example Output:

NAME FSTYPE LABEL UUID MOUNTPOINT


sda
├─sda1 ext4 boot 1234abcd-56ef-7890-gh12-ijklmnopqrst /boot
└─sda2 ext4 1234abcd-56ef-7890-gh12-ijklmnopqrst /
sdb
└─sdb1 ext4 data 1234abcd-56ef-7890-gh12-ijklmnopqrst /mnt/data

• FSTYPE: The type of filesystem (e.g., ext4, ntfs).


• LABEL: Label of the filesystem (if any).
• UUID: Unique identifier for the partition.

List Only Names and Sizes:


lsblk -o NAME,SIZE

Example Output:

NAME SIZE
sda 500G
├─sda1 500M
└─sda2 499.5G
sdb 1.8T
└─sdb1 1.8T

14. How to do disk partitioning in Ubuntu?

Disk partitioning in Ubuntu involves dividing a physical disk into smaller, manageable sections, each
treated as a separate unit (partition). Each partition can then be used to store data, a specific
filesystem, or to install operating systems. You can perform disk partitioning using tools like gparted,
fdisk, or parted.

Using GParted (Graphical Interface)

GParted is
a graphical tool that makes partitioning disks easier, especially for users who prefer
a GUI over the command line.

Install GParted:

If GParted isn't installed by default, you can install it:

sudo apt update


RAMMOHAN. L Sr. Linux Administator

sudo apt install gparted


Steps to Partition a Disk with GParted:

1. Launch GParted: Open the terminal and type:

sudo gparted

2. Select the Disk to Partition:


o In the top-right corner of the GParted window, select the disk you want to partition
(e.g., /dev/sda).
3. Create a New Partition Table:
o If the disk is empty or you want to reformat it, you can create a new partition table.
o Click on Device → Create Partition Table.
o Choose the partition table type (usually GPT or MBR). GPT is recommended for
disks larger than 2TB.
4. Create Partitions:
o Right-click on the unallocated space and select New.
o Choose the partition size, file system type (e.g., ext4 for Linux), and label.
o Click Add to create the partition.
5. Apply Changes:
o After creating all partitions, click the green checkmark to apply the changes.
6. Format Partitions:
o If needed, format the partition by right-clicking on it and choosing Format to →
choose the file system (e.g., ext4).

Using fdisk (Command Line Tool)

fdisk is a command-line tool used for creating, deleting, and managing partitions.

Check the Disk:

To list the disks and their partitions:

sudo fdisk -l
Steps to Partition a Disk with fdisk:

1. Launch fdisk: To start partitioning a disk (e.g., /dev/sda):

sudo fdisk /dev/sda

2. Create a New Partition:


o Type n to create a new partition.
o Choose the partition number (usually press Enter to accept the default).
o Specify the first sector (press Enter to use the default).
o Specify the last sector (size of the partition) or the partition size (e.g., +10G for a
10GB partition).
3. Change Partition Type (Optional):
o To change the partition type (e.g., from Linux to Linux swap), type t.
o Then type the partition number and the desired partition type code (e.g., 82 for swap).
4. Write the Partition Table:
o Type w to write the changes to the disk.
RAMMOHAN. L Sr. Linux Administator

5. Format the Partition:


o After creating the partition, format it using mkfs. For example, to format as ext4:

sudo mkfs.ext4 /dev/sda1

Using parted (Advanced Command Line Tool)

parted is more flexible than fdisk, supporting both MBR and


GPT partition tables. It is ideal for
managing large disks (greater than 2TB) and modern partitioning.

Steps to Partition a Disk with parted:

1. Launch parted:

sudo parted /dev/sda

2. Create a New Partition Table (Optional):


o For a new disk, you can create a new partition table using mklabel:

(parted) mklabel gpt

3. Create Partitions:
o To create a partition, use the mkpart command. For example, to create an ext4
partition:

(parted) mkpart primary ext4 0% 50GB

o This command creates a partition starting at the beginning of the disk and ending at
50GB.
4. Exit parted:
o Type quit to exit the parted prompt.
5. Format the Partition:
o After creating the partition, format it:

sudo mkfs.ext4 /dev/sda1

Mounting the Partition

Once you've partitioned and formatted your disk, you can mount the partition to make it
accessible.

Create a Mount Point:


sudo mkdir /mnt/mydisk
Mount the Partition:
sudo mount /dev/sda1 /mnt/mydisk
Make the Mount Permanent (Optional):

To mount the partition automatically on boot, add it to /etc/fstab.

1. Open the fstab file:


RAMMOHAN. L Sr. Linux Administator

sudo nano /etc/fstab

2. Add the following line at the end (replace with the correct UUID or device):

UUID=your-partition-uuid /mnt/mydisk ext4 defaults 0 2

3. Save and close the file.

15. Where is fstab located in Linux?

The fstab (file system table) file in Linux is located at:

/etc/fstab

This file contains information about the system’s disk partitions, filesystems, and mount
points. It is used by the system to automatically mount filesystems at boot time.

Key Information in /etc/fstab:

• Device: The device or partition (e.g., /dev/sda1, UUID, or LABEL).


• Mount Point: The directory where the device or partition should be mounted (e.g., /, /home).
• Filesystem Type: The type of filesystem (e.g., ext4, ntfs, vfat, etc.).
• Options: Mount options (e.g., defaults, ro, rw, noatime).
• Dump: Used by the dump command to determine if the filesystem should be backed up.
• Pass: Used by the fsck tool to determine the order of filesystem checks at boot.

Example of /etc/fstab:
# <file system> <mount point> <type> <options> <dump> <pass>
UUID=abcd-1234 / ext4 defaults 0 1
/dev/sda2 /home ext4 defaults 0 2
/dev/sdb1 /mnt/data ntfs defaults 0 0

• UUID=abcd-1234: The UUID (unique identifier) of the partition.


• /home: The mount point for the /dev/sda2 partition.
• ext4: The filesystem type for the / and /home partitions.
• defaults: The mount options (standard options).
• 0 and 1/2: Controls the order in which filesystem checks are done.

Modifying /etc/fstab:

• To edit the fstab file, use a text editor with superuser privileges, like nano:

sudo nano /etc/fstab

Be cautious when editing the fstab file, as incorrect entries can prevent the system from
booting properly.
RAMMOHAN. L Sr. Linux Administator

16. Scheduling & Security

Scheduling in Linux

Scheduling in Linux refers to the process of managing the execution of tasks or commands in
the system. The main utility for task scheduling in Linux is cron, which allows you to
schedule jobs (commands or scripts) to run at specified times or intervals.

Cron Jobs (Using cron)


What is cron?

cron isa daemon that runs in the background and executes scheduled tasks at specified times
or intervals. The jobs are defined in a special configuration file called a crontab (cron table).

Crontab File:

• The crontab file is used to define when and how often a command will run.
• Each user has their own crontab file (stored in /var/spool/cron/crontabs), but system-wide cron
jobs are usually stored in /etc/crontab or /etc/cron.d/.

Crontab Syntax:

The crontab syntax has 5 time fields followed by the command to be executed:

* * * * * /path/to/command
|||||
| | | | + ---- Day of the week (0 - 7) (Sunday = 0 or 7)
| | | +------ Month (1 - 12)
| | + -------- Day of the month (1 - 31)
| + ---------- Hour (0 - 23)
+ ------------ Minute (0 - 59)
Example:

To schedule a job to run every day at 3 AM:

0 3 * * * /path/to/script.sh
Managing Cron Jobs:

• To edit the crontab file:

crontab -e

• To list all scheduled cron jobs for the current user:

crontab -l

• To remove all scheduled cron jobs for the current user:

crontab -r
RAMMOHAN. L Sr. Linux Administator

Common Cron Directories:

• /etc/cron.daily/ – Jobs to run daily.


• /etc/cron.weekly/ – Jobs to run weekly.
• /etc/cron.monthly/ – Jobs to run monthly.
• /etc/crontab – System-wide cron jobs.

At Jobs (One-Time Task Scheduling)


What is at?

at is
used for scheduling one-time tasks to be run at a specific time. Unlike cron, which repeats
tasks, at schedules a task to run once.

Example Usage of at:

To schedule a task to run at 2:30 PM:

echo "/path/to/script.sh" | at 2:30 PM


Viewing Scheduled at Jobs:

To list scheduled jobs:

atq
Removing Scheduled at Jobs:

To remove a job:

atrm <job_id>

where <job_id> is the ID shown in the output of atq.

Security in Linux

Security in Linux involves a variety of tools, configurations, and practices designed to protect
the system and its data. The security mechanisms cover user access control, file permissions,
encryption, and more.

User Authentication and Permissions


User and Group Management:

• Add a user: sudo adduser username


• Add a user to a group: sudo usermod -aG groupname username
• Delete a user: sudo deluser username
RAMMOHAN. L Sr. Linux Administator

File Permissions:

• Linux uses a three-tier permission system for files:


o Owner: The user who owns the file.
o Group: The group that the file belongs to.
o Others: All other users.

Permissions include:

o r: Read
o w: Write
o x: Execute

Example:

To change file permissions using chmod:

chmod 755 filename

This gives the owner full permissions (read, write, execute), and the group and others can
read and execute.

Changing Ownership with chown:


sudo chown user:group filename
Check Permissions with ls -l:
ls -l filename

This will show the file's permissions in the first column (e.g., -rwxr-xr-x).

SELinux (Security-Enhanced Linux)


What is SELinux?

SELinux is a security module that provides an additional layer of access control by enforcing
rules that limit the actions of processes and users.

• Modes of SELinux:
o Enforcing: SELinux policies are enforced.
o Permissive: SELinux allows actions but logs them.
o Disabled: SELinux is disabled.

Check SELinux Status:


sestatus
Changing SELinux Modes:

To change to permissive mode (for troubleshooting):

sudo setenforce 0

To switch to enforcing mode:


RAMMOHAN. L Sr. Linux Administator

sudo setenforce 1

Firewall Configuration
What is ufw (Uncomplicated Firewall)?

ufw is a command-line interface for managing firewall rules on Ubuntu.

Common ufw Commands:

• Enable the firewall:

sudo ufw enable

• Allow a specific port (e.g., 80 for HTTP):

sudo ufw allow 80

• Deny a specific port (e.g., 22 for SSH):

sudo ufw deny 22

• Check the status of the firewall:

sudo ufw status

Encryption in Linux
Disk Encryption:

Linux supports full disk encryption (e.g., LUKS - Linux Unified Key Setup) to protect data
on disks.

• Encrypting a disk using LUKS: You can encrypt a partition with cryptsetup. For example:

sudo cryptsetup luksFormat /dev/sda1


File Encryption (Using GPG):

To encrypt a file with GPG:

gpg -c filename

This will prompt you for a passphrase to encrypt the file.

Sudo (Superuser Do)

sudo is a command that allows users to execute commands with superuser (root) privileges,
ensuring that the system is not exposed to unnecessary risks by logging in as root.

• Granting sudo access: Add the user to the sudo group:


RAMMOHAN. L Sr. Linux Administator

sudo usermod -aG sudo username


Check sudo access:

You can check whether your user has sudo privileges by running:

sudo -l

17. What are Crontab and Cronjob?

Crontab and Cronjob are closely related terms in Linux related to task scheduling. Both are
used for automating tasks to run at specific intervals, but they refer to different aspects of the
process.

Crontab (Cron Table)

The crontab (short for "cron table") is a configuration file that defines the schedule and
commands for automated tasks in Linux. It contains a list of commands to be run and the
timing for each task. Each user on the system can have their own crontab file, but there is also
a system-wide crontab file.

Crontab File Format:

Each line in the crontab file represents a single scheduled task and follows a specific syntax:

* * * * * /path/to/command
|||||
| | | | + ---- Day of the week (0 - 7) (Sunday = 0 or 7)
||||
| | | +------ Month (1 - 12)
| | + -------- Day of the month (1 - 31)
| + ---------- Hour (0 - 23)
+ ------------ Minute (0 - 59)

• Minute: 0 to 59
• Hour: 0 to 23 (0 = midnight)
• Day of the month: 1 to 31
• Month: 1 to 12
• Day of the week: 0 to 7 (0 or 7 = Sunday)

You can use * (asterisk) to denote "every" value for that field. For example, * * * * * would
run the command every minute of every hour, day, month, and day of the week.

Example Crontab Entries:

• Run a script every day at 3 AM:

0 3 * * * /path/to/script.sh

• Run a script every Monday at 2 PM:

0 14 * * 1 /path/to/script.sh
RAMMOHAN. L Sr. Linux Administator

• Run a script every minute:

* * * * * /path/to/script.sh

Cronjob (Cron Job)

A cronjob refers to a single scheduled task (command or script) defined within the crontab.
A cronjob is essentially the individual task that gets executed according to the schedule
defined in the crontab file.

A cronjob can refer to:

• The task itself (the command or script to be run).


• The scheduling details (the specific timing for the task to run).

Example of a Cronjob:

A cronjob could be a script that backs up data daily at midnight. The crontab entry for such a
cronjob could look like this:

0 0 * * * /path/to/backup.sh

This is a cronjob that runs the backup.sh script every day at midnight.

Working with Crontab and Cronjobs


Crontab Commands:

• Edit the crontab file (to create or modify cronjobs):

crontab -e

• List the current user's cronjobs:

crontab -l

• Remove all cronjobs for the current user:

crontab -r

• View the system-wide crontab file (/etc/crontab): System-wide cronjobs are often
stored in /etc/crontab or in files in /etc/cron.d/.

Log Files:

Cronjob output (including errors) can be sent to log files or emailed to the user who
scheduled the job. By default, output is mailed to the user, but you can direct it to a file or
suppress it:

0 3 * * * /path/to/script.sh > /path/to/logfile.log 2>&1


RAMMOHAN. L Sr. Linux Administator

This directs both standard output and error output to a log file (logfile.log).

18. What is SELinux?

SELinux (Security-Enhanced Linux)

SELinux is a Linux kernel security module that provides an additional layer of security by
enforcing mandatory access control (MAC) policies. It was developed by the National
Security Agency (NSA) and is now included in many Linux distributions, particularly those
designed for enterprise use, such as Red Hat and CentOS.

The primary goal of SELinux is to limit the damage caused by security breaches and to
confine processes to specific roles, thereby reducing the attack surface. It does this by
enforcing rules that specify how processes, users, and objects (such as files and directories)
can interact with each other.

Key Concepts of SELinux:

1. Mandatory Access Control (MAC):


o Unlike traditional Discretionary Access Control (DAC), where the owner of a file or
resource has control over who can access it, MAC policies are enforced by the
operating system and are not changeable by users or administrators.
o SELinux adds a layer of security by restricting how processes (programs) can access
files, devices, and other resources on the system.
2. Security Labels:
o Every file, directory, process, and resource in SELinux is assigned a security label.
o The security label is a combination of:
▪ User: The user the file belongs to (not necessarily the Linux system user).
▪ Role: The role assigned to the file or process.
▪ Type: The type of file or process (e.g., web server, system, or user).
▪ Level: Optional, defines sensitivity (e.g., confidential or secret).
3. Policies:
o SELinux operates based on security policies that define what actions are allowed
and under what circumstances.
o These policies define interactions between processes and objects.
o SELinux comes with a default policy that can be customized for specific needs.
4. Types of SELinux Modes:
o Enforcing: In this mode, SELinux policies are actively enforced, and any actions that
violate the policy are denied.
o Permissive: In permissive mode, SELinux does not enforce policies but logs
violations. It is useful for troubleshooting or when you want to see what would be
blocked if SELinux were enforcing.
o Disabled: SELinux is completely disabled, and no policies are enforced.

To check the current SELinux status:

sestatus
RAMMOHAN. L Sr. Linux Administator

How SELinux Works:

1. Process Labeling:
o Every process running on the system is assigned a label that includes a user, role, and
type. This label determines what resources the process can access.
o For example, a web server process may be labeled with a httpd_t type, which would
restrict it from accessing certain system files unless explicitly allowed.
2. File Labeling:
o Each file or resource on the system is assigned a security label (type). For example, a
web server might only be allowed to read files labeled as httpd_sys_content_t.
3. Access Control Decisions:
o When a process tries to access a file or resource, SELinux checks the policy to see if
the action is allowed based on the labels of both the process and the resource.
o If the policy does not allow the action, the access is denied.

SELinux Modes:

• Enforcing Mode: In enforcing mode, SELinux applies policies and denies any action
that violates the policies. This is the most secure mode. To enable enforcing mode:

sudo setenforce 1

• Permissive Mode: In permissive mode, SELinux allows all actions but logs
violations. This mode is often used for troubleshooting or during initial system setup
when policies are being tested. To enable permissive mode:

sudo setenforce 0

• Disabled Mode: SELinux is completely disabled. No policies are enforced, and the
system operates like a standard Linux system without SELinux protections. To disable
SELinux (permanent change):
o Edit /etc/selinux/config:

SELINUX=disabled

Then reboot the system for the changes to take effect.

Managing SELinux Policies:

• Audit Logs: SELinux logs access violations and policy denials in /var/log/audit/audit.log.
This log helps administrators understand which actions are being blocked and why.
• Checking SELinux Status: To view the current status of SELinux, you can use the
sestatus command:

sestatus

• Changing SELinux Mode Temporarily: Use the setenforce command to change


SELinux's mode (temporarily):
RAMMOHAN. L Sr. Linux Administator

o Enforcing: sudo setenforce 1


o Permissive: sudo setenforce 0
• SELinux Troubleshooting: If you need to troubleshoot SELinux issues, you can use
the audit2allow tool to generate custom SELinux policy modules to allow certain
actions that are being denied.

audit2allow -a

• View and Modify SELinux Policy: The semanage command can be used to manage
SELinux policies:

sudo semanage fcontext -a -t httpd_sys_content_t "/var/www/html(/.*)?"


sudo restorecon -Rv /var/www/html

Advantages of SELinux:

1. Fine-grained control: SELinux allows fine-grained access control based on policies,


enabling greater security over traditional discretionary access control (DAC).
2. Prevents unauthorized access: Even if an attacker gains access to the system, SELinux's
restrictions on process access prevent them from exploiting other parts of the system.
3. Minimal risk from bugs or vulnerabilities: By isolating processes and limiting access to
resources, SELinux reduces the impact of vulnerabilities and exploits in applications.

Disadvantages of SELinux:

1. Complex Configuration: SELinux's configuration can be complex for users and


administrators unfamiliar with its policies.
2. Compatibility Issues: Some applications may not work correctly with SELinux if the
necessary policies are not configured.
3. Performance Overhead: SELinux's additional layer of checks can impose a slight
performance overhead, especially on busy systems.

19. How does DNS work?

How DNS (Domain Name System) Works

The Domain Name System (DNS) is a system that translates human-readable domain names
(like www.example.com) into machine-readable IP addresses (like 192.0.2.1). Since the internet
primarily uses IP addresses to identify devices and servers, DNS is a fundamental part of how
the internet functions, enabling users to access websites using easy-to-remember names rather
than complex numeric IP addresses.

DNS Structure

DNS operates in a hierarchical structure, which is made up of several levels:

• Root DNS Servers: The highest level of the DNS hierarchy. These servers store information
about top-level domains (TLDs) such as .com, .org, .net, etc.
RAMMOHAN. L Sr. Linux Administator

• Top-Level Domains (TLDs): The next level includes domain extensions like .com, .org, .net,
.gov, and country codes like .uk, .de, etc.
• Second-Level Domains: These are the domain names directly under the TLD, such as
example in example.com.
• Subdomains: Optional domains beneath second-level domains, such as www in
www.example.com.
• Resource Records (RRs): Data about domain names and their corresponding IP addresses or
other resources.

The DNS Resolution Process

When you type a website URL into your browser (e.g., www.example.com), DNS helps translate
that domain into an IP address. Here’s how the resolution process typically works:

Step 1: Browser Cache Check

Before reaching out to external DNS servers, your browser will check its own local cache to
see if it has recently accessed the domain. If it has, it will use the cached IP address,
bypassing the rest of the DNS lookup process.

Step 2: OS/Local Resolver Cache Check

If the browser doesn't have the information, it will ask your operating system's local
resolver. The OS maintains a cache of recently looked-up domains. If the IP address for the
domain is found here, it will return the result.

Step 3: Query to Recursive DNS Resolver

If the domain isn't cached locally, the request is sent to a recursive DNS resolver. This
resolver is typically provided by your ISP (Internet Service Provider) or a third-party DNS
service (like Google DNS or Cloudflare). The recursive resolver is responsible for finding the
correct IP address by querying other DNS servers.

Step 4: Query to Root DNS Server

If the recursive resolver doesn’t have the answer cached, it will query one of the root DNS
servers. The root server doesn’t know the exact IP address for the domain but can direct the
resolver to the appropriate TLD (Top-Level Domain) server based on the domain's
extension (e.g., .com, .org).

Step 5: Query to TLD DNS Server

The TLD DNS server contains information about the domain and can direct the query to the
authoritative DNS server for the specific domain. For example, if the domain is
www.example.com, the .com TLD server will point the resolver to the authoritative DNS server
for example.com.
RAMMOHAN. L Sr. Linux Administator

Step 6: Query to Authoritative DNS Server

The authoritative DNS server for the domain holds the actual DNS records for the domain,
including A records (which map domain names to IP addresses). The authoritative server
returns the correct IP address for www.example.com.

Step 7: Response Sent Back

The recursive resolver receives the IP address from the authoritative server and sends it back
to your browser. Your browser can now use that IP address to connect to the web server
hosting the website.

Step 8: Caching for Future Requests

The recursive resolver will cache the IP address for a period of time (determined by the
Time-to-Live (TTL) value in the DNS record). This way, if another request for the same
domain is made, the resolver can return the cached IP address without going through the
entire lookup process again.

Types of DNS Records

DNS uses various types of records to store information about a domain. Some common ones
include:

• A Record (Address Record): Maps a domain to an IPv4 address (e.g., example.com ->
192.0.2.1).
• AAAA Record: Maps a domain to an IPv6 address (e.g., example.com ->
2001:0db8::ff00:0042:8329).
• CNAME Record (Canonical Name): Maps one domain to another (e.g., www.example.com -
> example.com).
• MX Record (Mail Exchange): Specifies the mail servers responsible for receiving email for
the domain (e.g., example.com's mail servers).
• TXT Record: Stores text-based information (often used for domain verification or SPF
records to prevent email spoofing).
• NS Record (Name Server): Specifies the authoritative DNS servers for the domain.
• PTR Record (Pointer Record): Used for reverse DNS lookups, mapping an IP address to a
domain name.

DNS Caching

DNS caching is a mechanism that stores DNS query results for a period of time to avoid
redundant lookups, which helps improve performance and reduce the load on DNS servers.
There are three types of caching:

• Browser Cache: Stores recent DNS queries in the browser for quicker access.
• Operating System Cache: Stores DNS data at the OS level.
• DNS Resolver Cache: Stores DNS data at the recursive resolver level.
RAMMOHAN. L Sr. Linux Administator

Each cache has a Time-to-Live (TTL) value, which specifies how long the result is
considered valid. After the TTL expires, the cache is cleared, and a new query is performed.

Common DNS Issues

Some common issues related to DNS include:

• DNS Resolution Failures: If the DNS lookup fails, it can lead to errors like "DNS server not
found" or "server not responding." This may be due to incorrect DNS settings, network
problems, or issues with the DNS server.
• DNS Spoofing or Poisoning: Malicious actors may inject false DNS records into the cache of
a resolver, redirecting users to malicious websites.
• DNS Hijacking: Attackers may take control of a domain's DNS records to redirect traffic to
malicious sites.

Tools for DNS Troubleshooting

There are several tools to help troubleshoot DNS issues:

• nslookup: A command-line tool to query DNS servers directly and retrieve DNS
records for a domain.

nslookup example.com

• dig: A more powerful tool for querying DNS information, useful for detailed
diagnostics.

dig example.com

• ping: Tests connectivity to an IP address (useful for checking if the domain resolves
correctly).

ping example.com

20. Do you know about firewalls?

A firewall is a network security system designed to monitor and control incoming and
outgoing network traffic based on predetermined security rules. Firewalls are commonly used
to establish a barrier between trusted internal networks and untrusted external networks (such
as the internet) to protect against unauthorized access, malicious attacks, and data breaches.

Types of Firewalls

There are several types of firewalls, each with different functions and use cases. The most
common types include:
RAMMOHAN. L Sr. Linux Administator

1. Packet-Filtering Firewall

• How it works: It examines packets (small units of data) transferred over the network. Each
packet is compared against a set of predefined rules (such as allowed IP addresses, ports, and
protocols). If the packet matches the rules, it is allowed; otherwise, it is discarded.
• Pros: Simple and fast.
• Cons: Does not inspect the contents of the packet or track the state of network connections,
making it vulnerable to certain types of attacks (e.g., IP spoofing).

2. Stateful Inspection Firewall

• How it works: Unlike packet-filtering firewalls, stateful inspection firewalls maintain the
state of active connections. They track the state of network connections (e.g., TCP streams)
and allow packets that are part of a valid connection, while blocking those that are not.
• Pros: More secure than packet filtering, as it tracks connection states.
• Cons: Can consume more resources and be more complex to configure.

3. Proxy Firewall

• How it works: A proxy firewall acts as an intermediary between the internal network and
external networks. It forwards requests from clients on the internal network to external
servers and vice versa, hiding the client's identity and inspecting the traffic for potential
threats.
• Pros: Provides higher security by hiding internal IP addresses and scanning the content of
packets.
• Cons: Can introduce latency and slow down traffic due to content inspection.

4. Next-Generation Firewall (NGFW)

• How it works: A next-generation firewall combines traditional firewall features with


additional advanced capabilities, such as intrusion prevention systems (IPS), application
awareness, deep packet inspection (DPI), and user identity management.
• Pros: Provides comprehensive security features, including threat intelligence and deep
content inspection.
• Cons: More complex to configure and may require more resources.

5. Web Application Firewall (WAF)

• How it works: A WAF is specifically designed to protect web applications by filtering and
monitoring HTTP traffic. It inspects traffic between the web server and the client, looking for
malicious requests such as SQL injection, cross-site scripting (XSS), and other web-based
attacks.
• Pros: Specializes in securing web applications, providing more targeted protection.
• Cons: Only protects web applications, not other network services.

Firewall Functions

Firewalls perform several essential functions, including:


RAMMOHAN. L Sr. Linux Administator

1. Traffic Filtering

Firewalls control access by filtering network traffic based on specific rules, such as:

• IP addresses: Source and destination IP addresses.


• Ports: Specific network ports (e.g., port 80 for HTTP, port 443 for HTTPS).
• Protocols: The type of communication protocol being used (e.g., TCP, UDP, ICMP).
• Packet Content: In some cases, firewalls can inspect the content of packets to detect
malicious payloads or forbidden data.

2. NAT (Network Address Translation)

Firewalls often perform NAT, which allows private IP addresses (e.g., 192.168.1.1) to be
translated into a public IP address for communication over the internet. This helps protect
internal network addresses from exposure.

3. Logging and Monitoring

Firewalls maintain logs of traffic that passes through them, which can be useful for
monitoring network activity, detecting anomalies, and troubleshooting security incidents.

4. VPN Support

Many firewalls provide support for Virtual Private Networks (VPNs). They can encrypt
traffic between remote devices and the internal network, allowing secure access over the
internet.

5. Intrusion Detection and Prevention

Some firewalls have built-in intrusion detection and prevention systems (IDS/IPS) that
monitor network traffic for signs of malicious behavior and automatically block suspicious
traffic.

How Firewalls Work

Firewalls operate at different layers of the OSI (Open Systems Interconnection) model.
Depending on the firewall type, they can inspect traffic at the following layers:

• Layer 3 (Network Layer): Packet-filtering firewalls typically operate here, inspecting IP


addresses and packet headers.
• Layer 4 (Transport Layer): Stateful firewalls examine transport-layer protocols (TCP/UDP)
and maintain state information for connections.
• Layer 7 (Application Layer): Next-generation firewalls and WAFs inspect traffic at the
application layer, looking at the actual data (e.g., HTTP requests, emails) to detect malicious
activities.
RAMMOHAN. L Sr. Linux Administator

Firewall Rules

Firewall rules are configured to define what traffic should be allowed or blocked. A basic rule
typically includes:

• Source IP address: Where the traffic is coming from.


• Destination IP address: Where the traffic is going.
• Port number: The port the traffic is using.
• Protocol: The protocol (e.g., TCP, UDP).
• Action: Allow or block the traffic.

Firewall Deployment Architectures

Firewalls can be deployed in different network architectures depending on the use case:

1. Perimeter Firewall

A perimeter firewall is placed between an organization's internal network and external


networks (such as the internet). It serves as the first line of defense against external threats.

2. Internal Firewall

An internal firewall is used to segment different parts of an internal network, ensuring that
communication between internal subnets or departments is tightly controlled. It provides an
additional layer of defense within the network.

3. DMZ (Demilitarized Zone) Firewall

A DMZ firewall is typically placed between the internal network and external network, often
used to protect publicly accessible servers (e.g., web servers, email servers). The DMZ serves
as an isolated network that is more exposed to potential attacks.

Common Firewall Commands (Linux)

Here are some common commands to configure and manage firewalls on a Linux system
using iptables or firewalld:

Using iptables (older system, still in use):

• View current firewall rules:

sudo iptables -L

• Allow traffic on a specific port (e.g., port 80 for HTTP):

sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT

• Block incoming traffic from a specific IP:


RAMMOHAN. L Sr. Linux Administator

sudo iptables -A INPUT -s <IP_ADDRESS> -j DROP

• Save the iptables rules:

sudo iptables-save > /etc/iptables/rules.v4


Using firewalld (default on many modern Linux distributions):

• Check firewall status:

sudo firewall-cmd --state

• Allow traffic on a specific port (e.g., HTTP):

sudo firewall-cmd --zone=public --add-port=80/tcp --permanent

• Reload the firewall to apply changes:

sudo firewall-cmd --reload

Advantages of Firewalls

1. Network Protection: Firewalls provide a critical barrier between trusted internal networks
and untrusted external networks, preventing unauthorized access.
2. Traffic Control: Firewalls can control which types of traffic are allowed based on IP address,
protocol, port, and other factors.
3. Monitoring and Logging: Firewalls can generate logs that help administrators monitor
network traffic and detect suspicious activity.
4. Improved Privacy: By hiding the internal network behind firewalls, organizations can
protect the privacy and security of sensitive data.

Disadvantages of Firewalls

1. Complex Configuration: Misconfigured firewalls can block legitimate traffic, causing


service interruptions.
2. Limited Protection: Firewalls cannot protect against internal threats or issues with software
vulnerabilities unless they are specifically configured to do so.
3. Performance Impact: Firewalls can introduce latency or consume system resources,
particularly when inspecting large volumes of traffic or performing complex filtering.

Web Servers & SSL

21. What is Apache?

Apache refers to the Apache HTTP Server, commonly known as Apache, which is an
open-source and widely used web server software. It is designed to serve web content (such
as HTML files, images, and scripts) over the internet. Apache is one of the oldest and most
reliable web servers, and it is often the default web server for many Linux distributions, as
well as other operating systems.
RAMMOHAN. L Sr. Linux Administator

Apache is a crucial part of the LAMP stack (Linux, Apache, MySQL/MariaDB,


PHP/Python/Perl), which is commonly used to host dynamic websites and web applications.

Key Features of Apache

1. Open-Source and Free: Apache is open-source software, meaning anyone can view,
modify, and distribute the source code. It’s free to use and has a large community of
developers supporting it.
2. Cross-Platform: Apache can run on a variety of operating systems, including Linux,
Windows, macOS, and others. It is compatible with both Unix-like and Windows
systems.
3. Modular Architecture: Apache uses a modular architecture, which allows users to
add or remove functionality by enabling or disabling modules. For example, there are
modules for handling SSL/TLS encryption, URL rewriting, authentication, and more.
4. Customizable and Configurable: Apache provides flexibility with its configuration.
The web server can be customized to meet specific needs by editing configuration
files (e.g., httpd.conf). It supports .htaccess files for directory-level configuration.
5. Virtual Hosting: Apache can host multiple websites on a single server using virtual
hosts. This allows you to run several different domains on the same IP address, each
with its own configuration.
6. Support for Dynamic Content: Apache can serve static content (HTML, images)
and also dynamic content by integrating with server-side scripting languages like
PHP, Perl, and Python. It often works in conjunction with mod_php to run PHP
scripts.
7. Security: Apache offers robust security features, such as access control (through
mod_auth), SSL/TLS encryption (via mod_ssl), and the ability to configure fine-grained
access permissions based on IP address, user-agent, etc.
8. Performance: Apache uses a variety of techniques to handle requests efficiently. It
can run in different modes (e.g., prefork, worker, and event modes) to manage
processes and threads based on system resources and use cases.

How Apache Works

When you request a webpage from a browser (e.g., http://www.example.com), the following steps
typically occur:

1. DNS Resolution: The browser resolves the domain name (www.example.com) to an IP address
using DNS.
2. Connection: The browser establishes a connection to the Apache server via the internet,
using the specified IP address.
3. Request Handling: Apache receives the request and processes it, following its configured
rules.
4. Serve Content: If the request is for a static file (e.g., index.html), Apache will serve it directly
from the file system. For dynamic content (e.g., PHP scripts), Apache may pass the request to
an interpreter like PHP.
5. Response: Apache sends the requested content back to the browser as an HTTP response.
RAMMOHAN. L Sr. Linux Administator

Apache Configuration Files

Apache's behavior is controlled through configuration files, the main one being httpd.conf, but
other configuration files and directories (such as .htaccess or files in /etc/apache2) can also be
used.

• httpd.conf: The main configuration file for Apache, where global settings like server root,
document root, and module configurations are defined.
• .htaccess: A directory-level configuration file that allows web administrators to modify
settings for specific directories, enabling things like URL rewriting, access control, and
redirection.
• apache2.conf: The configuration file used on systems running Apache 2.x (common in
modern distributions), which may include references to other configuration files for modular
configurations.

Apache Modules

Apache’s modular architecture allows the server to be extended by loading different modules.
Some commonly used modules include:

• mod_ssl: Provides SSL/TLS support for encrypted connections (HTTPS).


• mod_rewrite: Used for URL rewriting, enabling clean, user-friendly URLs.
• mod_php: Allows Apache to process PHP code for dynamic web pages.
• mod_proxy: Implements proxy functionality, enabling Apache to forward requests to other
servers.
• mod_headers: Allows modification of HTTP headers sent with responses.

You can load or unload these modules in the Apache configuration file based on your needs.

Apache vs. Nginx

Although Apache is one of the most popular web servers, it's not the only one available.
Nginx is another widely used web server, and each has its strengths:

• Apache: Best known for its flexibility, extensive module support, and compatibility with
dynamic content. It’s often chosen for serving content where extensive configuration and
customization are required.
• Nginx: Known for its high performance, low resource consumption, and ability to handle a
large number of concurrent connections. It is often used as a reverse proxy and load balancer.

In practice, many large-scale web applications use both Apache (for handling dynamic
content) and Nginx (for reverse proxy and load balancing).

Basic Commands for Managing Apache

Here are some common commands to manage Apache on a Linux system (e.g., Ubuntu):
RAMMOHAN. L Sr. Linux Administator

• Start Apache:

sudo systemctl start apache2

• Stop Apache:

sudo systemctl stop apache2

• Restart Apache:

sudo systemctl restart apache2

• Check Apache Status:

sudo systemctl status apache2

• Enable Apache to Start on Boot:

sudo systemctl enable apache2

• Disable Apache from Starting on Boot:

sudo systemctl disable apache2

• Test Apache Configuration:

sudo apachectl configtest

• View Apache Logs: Apache logs are typically stored in /var/log/apache2/:


o Error logs: /var/log/apache2/error.log
o Access logs: /var/log/apache2/access.log

Apache Security Best Practices

To ensure the security of your Apache web server, consider the following best practices:

1. Disable Unnecessary Modules: Only load the modules that are necessary for your
application to reduce attack surface.
2. Keep Apache Up-to-Date: Regularly update Apache to apply security patches and bug fixes.
3. Use HTTPS: Always use SSL/TLS (with mod_ssl) to encrypt sensitive data transmitted
between the client and server.
4. Restrict Access: Use Allow and Deny directives to limit access to specific directories and
files.
5. Configure Proper File Permissions: Ensure that files served by Apache have correct
permissions to prevent unauthorized access.
RAMMOHAN. L Sr. Linux Administator

22. What is PHPAdmin?

phpMyAdmin is a popular open-source web-based application written in PHP that provides


a user-friendly interface for managing MySQL and MariaDB databases. It allows users to
interact with databases through a web browser, making it easier to perform various database
operations without needing to use command-line tools or complex SQL queries.

phpMyAdmin is widely used by developers, system administrators, and website owners to


manage their databases, especially when working with LAMP (Linux, Apache, MySQL,
PHP) or LEMP (Linux, Nginx, MySQL/MariaDB, PHP) stacks.

Key Features of phpMyAdmin

1. Web Interface: phpMyAdmin provides an intuitive web-based graphical user


interface (GUI) for managing MySQL/MariaDB databases. This allows users to
perform database operations like creating tables, running queries, and managing users
without needing to know SQL commands.
2. Multi-Database Support: phpMyAdmin can manage multiple databases at once,
allowing users to switch between databases and perform operations on each one as
needed.
3. SQL Query Execution: You can execute SQL queries directly from the
phpMyAdmin interface. This is useful for running complex SQL commands or
managing large datasets without needing to use a separate SQL client.
4. Database Backup and Restoration: phpMyAdmin enables users to easily back up
and restore databases. You can export a database in multiple formats, such as SQL,
CSV, XML, or JSON, and later restore it on the same or another MySQL/MariaDB
server.
5. Table Management: It offers powerful tools to create, modify, and delete tables. You
can also perform various actions on tables, such as altering fields, indexing, or setting
foreign keys.
6. User Management: phpMyAdmin allows you to manage MySQL/MariaDB users
and their privileges. You can create new users, assign permissions (e.g., SELECT,
INSERT, DELETE), and manage access control to databases.
7. Importing Data: You can import data into databases using phpMyAdmin. Supported
formats include CSV, SQL, and others. This feature is useful for transferring data
between databases.
8. Exporting Data: Similarly, you can export data from databases to various formats for
backups or for use in other systems.
9. Search Functionality: phpMyAdmin allows you to search through your databases,
tables, or specific rows in tables, making it easier to locate and manage data.
10. Complex Query Support: phpMyAdmin supports more advanced features like joins,
views, and stored procedures, which are essential for complex database operations.

How to Install phpMyAdmin


On a Linux-based system (e.g., Ubuntu):

To install phpMyAdmin on a server running Ubuntu, follow these steps:


RAMMOHAN. L Sr. Linux Administator

1. Update the package list:

sudo apt update

2. Install phpMyAdmin:

sudo apt install phpmyadmin

During the installation, you will be prompted to choose the web server (Apache or
Nginx). If you are using Apache, select apache2. If you are using Nginx, you'll need
to manually configure phpMyAdmin with PHP-FPM.

3. Enable the phpMyAdmin configuration (for Apache):

sudo ln -s /usr/share/phpmyadmin /var/www/html/phpmyadmin

This will create a symbolic link to the phpMyAdmin directory in the web server's root
directory, so it can be accessed through the browser.

4. Configure PHP (if necessary): Ensure that PHP and necessary extensions (like php-
mysqli) are installed and configured for use with Apache and phpMyAdmin.
5. Access phpMyAdmin: Once the installation is complete, you can access
phpMyAdmin via the browser by navigating to:

http://your-server-ip/phpmyadmin

You will be prompted to log in using your MySQL/MariaDB credentials.

Security Considerations

While phpMyAdmin is a useful tool, it also poses security risks if not properly configured.
Here are a few tips to enhance security:

1. Use Strong Authentication: phpMyAdmin should not be accessible to the public


without proper authentication. Use strong, unique passwords for MySQL/MariaDB
users, and avoid using the root user for regular tasks.
2. Restrict Access: Limit access to phpMyAdmin to trusted IP addresses using Apache's
or Nginx's configuration files. You can also use HTTP authentication to add another
layer of security.
3. HTTPS (SSL/TLS): Ensure phpMyAdmin is served over HTTPS to encrypt data
transmitted between the client and the server, including sensitive credentials.
4. Change the Default URL: The default URL for phpMyAdmin (e.g., /phpmyadmin) is
well-known, so changing it to something less predictable can reduce the chances of
attacks. You can configure this in the web server's configuration.
5. Disable Remote MySQL Access: If you're not using phpMyAdmin to manage
remote MySQL/MariaDB servers, you can disable remote access to the MySQL
server for enhanced security.
RAMMOHAN. L Sr. Linux Administator

Alternatives to phpMyAdmin

Although phpMyAdmin is a widely used tool, there are other web-based database
management tools available:

• Adminer: A lightweight and simple alternative to phpMyAdmin with support for multiple
database management systems (MySQL, PostgreSQL, SQLite, etc.).
• MySQL Workbench: A desktop application for managing MySQL databases, which
includes a rich set of tools for designing, managing, and querying MySQL databases.
• DBeaver: A multi-database tool that supports MySQL, PostgreSQL, SQLite, and many other
databases. It offers both a graphical interface and SQL editor.

23. What is an SSL certificate? How can we create it and configure it in Apache?

An SSL certificate (Secure Sockets Layer certificate) is a type of digital certificate that
authenticates the identity of a website and encrypts the communication between the web
server and the web browser. It is part of the TLS (Transport Layer Security) protocol, which
is the successor to SSL, but the term SSL is still commonly used.

An SSL certificate ensures that:

1. Encryption: All data transferred between the web server and the client (e.g., passwords,
credit card information) is encrypted, preventing it from being intercepted by unauthorized
parties.
2. Authentication: The SSL certificate verifies that the website is authentic and not a phishing
site, providing confidence to users that the website they are communicating with is legitimate.
3. Trust: SSL certificates help to build trust with users because modern browsers display a
padlock icon in the address bar when a website is using SSL, signaling that the connection is
secure.

Websites that use SSL certificates will have URLs starting with HTTPS (instead of HTTP),
which indicates that the connection is encrypted using SSL/TLS.

Types of SSL Certificates

1. Domain Validation (DV) SSL: This is the most basic type of SSL certificate,
verifying that the domain is owned by the requester. It’s quick to issue but offers
minimal verification.
2. Organization Validation (OV) SSL: In addition to validating the domain, this type
also verifies the identity of the organization requesting the certificate. It’s more secure
than DV SSL.
3. Extended Validation (EV) SSL: The most secure SSL certificate, EV SSL requires a
detailed verification process. Websites with an EV SSL certificate will display the
organization name in the address bar.
4. Wildcard SSL: This type of SSL certificate covers all subdomains of a domain,
making it easier to secure multiple subdomains.
5. Multi-Domain SSL: A single SSL certificate that can secure multiple domains, often
used by businesses managing several websites.
RAMMOHAN. L Sr. Linux Administator

How to Create and Configure an SSL Certificate in Apache

There are two primary methods to obtain and use an SSL certificate in Apache:

1. Using a Self-Signed SSL Certificate: A self-signed certificate is one you generate on


your own. It will encrypt traffic but won't be trusted by browsers unless the certificate
is manually installed by the user.
2. Using a Trusted SSL Certificate from a Certificate Authority (CA): Trusted
certificates are issued by a recognized Certificate Authority, and browsers will trust
them without any warnings.

1. Creating and Configuring a Self-Signed SSL Certificate

Step 1: Install Apache and OpenSSL (if not installed)

Ensure that Apache and OpenSSL are installed on your server. You can install them using
the following commands on a Debian-based system (Ubuntu):

sudo apt update


sudo apt install apache2 openssl

Step 2: Create the SSL Certificate

To create a self-signed SSL certificate, use the following steps:

1. Create a directory to store the certificate and private key files:

sudo mkdir /etc/ssl/private


sudo mkdir /etc/ssl/certs

2. Generate a private key and a self-signed certificate:

sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/ssl/private/apache-
selfsigned.key -out /etc/ssl/certs/apache-selfsigned.crt

You’ll be prompted to enter information for the certificate, such as:

o Country Name (2-letter code)


o State or Province Name
o Locality Name (City)
o Organization Name (Your company)
o Common Name (domain or subdomain name, e.g., example.com)

Step 3: Configure Apache to Use SSL

1. Enable SSL module and the default SSL site in Apache:

sudo a2enmod ssl


sudo a2ensite default-ssl.conf
RAMMOHAN. L Sr. Linux Administator

2. Edit the SSL configuration file to point to your self-signed certificate and private key:

sudo nano /etc/apache2/sites-available/default-ssl.conf

Modify the following lines to reflect the paths of the SSL certificate and private key:

SSLCertificateFile /etc/ssl/certs/apache-selfsigned.crt
SSLCertificateKeyFile /etc/ssl/private/apache-selfsigned.key

Step 4: Restart Apache

Finally, restart Apache to apply the SSL configuration:

sudo systemctl restart apache2

Your Apache server should now be configured to use SSL. You can verify by visiting your
website via https:// (e.g., https://your-domain.com), and it should display the padlock icon in the
browser.

2. Using a Trusted SSL Certificate from a CA

To obtain a trusted SSL certificate from a Certificate Authority, you will typically need to:

1. Generate a Certificate Signing Request (CSR): Use OpenSSL to generate a CSR,


which you will submit to the CA to request an SSL certificate.

Example command:

sudo openssl req -new -newkey rsa:2048 -nodes -keyout /etc/ssl/private/your-domain.key -out
/etc/ssl/certs/your-domain.csr

You will be prompted to enter the details for your organization and domain.

2. Submit the CSR to a CA: Submit the generated CSR file to a trusted Certificate
Authority (e.g., Let's Encrypt, DigiCert, Comodo, etc.). After verification, the CA
will provide you with an SSL certificate.
3. Install the SSL Certificate: Once you have received the SSL certificate (often in .crt
or .pem format), you need to install it on your Apache server. Place the certificate file
and the CA’s certificate chain file in the appropriate directories (e.g., /etc/ssl/certs/).
4. Configure Apache to Use the SSL Certificate: Similar to the self-signed certificate
process, modify the Apache SSL configuration file to point to your newly obtained
SSL certificate and private key:

SSLCertificateFile /etc/ssl/certs/your-domain.crt
SSLCertificateKeyFile /etc/ssl/private/your-domain.key
SSLCertificateChainFile /etc/ssl/certs/CA-chain.crt

5. Restart Apache: Restart Apache to apply the new SSL configuration:

sudo systemctl restart apache2


RAMMOHAN. L Sr. Linux Administator

6. Verify SSL Installation: You can verify your SSL installation using online tools like
SSL Labs SSL Test to ensure your website is properly secured with SSL.

Enforcing HTTPS in Apache

To ensure all traffic to your website is encrypted, you can configure Apache to redirect HTTP
requests to HTTPS:

1. Edit the Apache Configuration File: Open your default Apache configuration file
(e.g., /etc/apache2/sites-available/000-default.conf for HTTP).

Add the following redirect rule:

<VirtualHost *:80>
ServerName your-domain.com
Redirect permanent / https://your-domain.com/
</VirtualHost>

2. Restart Apache: Restart Apache to apply the changes:

sudo systemctl restart apache2

24. Which is better, Apache or Nginx? Which web server is best for high loads?

The choice between Apache and Nginx depends on the specific requirements of your web
application, including traffic volume, scalability needs, and the complexity of your web
server configuration. Both are popular and widely used web servers, but they have different
characteristics that make them suitable for different use cases.

Apache vs. Nginx: Key Differences

1. Architecture and Performance:


o Apache: Apache uses a process-based or thread-based approach to handle requests.
It creates a new process or thread for each incoming request. While this approach
offers flexibility (support for different types of content, modules, etc.), it can be
resource-intensive, especially under heavy load.
o Nginx: Nginx uses an event-driven, asynchronous architecture. It handles multiple
requests within a single process using non-blocking I/O. This allows Nginx to handle
a large number of simultaneous connections with minimal resources, making it more
efficient under high traffic loads.
2. Handling Static Content:
o Apache: Apache can serve static content well, but it is not as efficient as Nginx.
Static files like HTML, CSS, and images require more resources in Apache, as it
spawns a new process for each request.
o Nginx: Nginx excels at serving static content. Its event-driven model and optimized
handling of static files allow it to serve static resources faster and more efficiently
than Apache.
3. Dynamic Content Handling:
RAMMOHAN. L Sr. Linux Administator

o Apache: Apache has robust support for dynamic content. It has built-in support for
various scripting languages, such as PHP, Perl, and Python. Apache's ability to
integrate directly with modules like mod_php makes it a good choice for serving
dynamic content.
o Nginx: Nginx does not process dynamic content natively. Instead, it passes requests
for dynamic content to external servers (e.g., PHP-FPM, Python, etc.). This makes it
highly flexible and efficient when combined with PHP-FPM or other backend
services.
4. Configuration and Flexibility:
o Apache: Apache provides a high level of configurability with its extensive set of
modules and .htaccess files. It is well-suited for complex configurations and fine-
grained access control. .htaccess files allow for decentralized configuration, which is
useful on shared hosting environments.
o Nginx: Nginx has a more straightforward and declarative configuration style. It does
not use .htaccess files, which reduces overhead and enhances performance. While
Nginx is less flexible than Apache in terms of module configuration, it is simpler and
faster for basic use cases.
5. Load Balancing and Reverse Proxy:
o Apache: Apache can perform load balancing and act as a reverse proxy using
modules like mod_proxy and mod_balancer. However, it is less efficient than Nginx in
handling large numbers of concurrent requests.
o Nginx: Nginx is highly optimized as a reverse proxy and load balancer. It can
distribute traffic to backend servers with minimal overhead and can handle many
more concurrent connections than Apache.
6. SSL/TLS Performance:
o Apache: Apache can handle SSL/TLS traffic with modules like mod_ssl. However,
due to its process-based architecture, it may not perform as well under high SSL
traffic loads.
o Nginx: Nginx is known for its excellent SSL performance. It uses asynchronous
handling for SSL connections, which means it can process more encrypted
connections with less resource consumption compared to Apache.
7. Memory Usage:
o Apache: Apache tends to use more memory because it spawns a new process or
thread for each request, which can be resource-intensive when handling high numbers
of concurrent connections.
o Nginx: Nginx uses far less memory due to its event-driven architecture, making it
more suitable for high-traffic websites with a large number of concurrent
connections.

Which is Better for High Loads?

When it comes to handling high traffic loads, Nginx is generally the better choice for the
following reasons:

1. Efficient Resource Usage: Nginx's event-driven, non-blocking architecture allows it


to handle many concurrent requests with minimal memory and CPU usage. This
makes it ideal for high-traffic sites and services that need to scale efficiently.
2. Better for Static Content: Nginx serves static content (images, HTML, CSS,
JavaScript) much more efficiently than Apache. If your site serves a large number of
static assets, Nginx will provide better performance under heavy load.
3. Reverse Proxy and Load Balancing: Nginx is highly efficient as a reverse proxy and
load balancer. It can distribute incoming requests across multiple backend servers
RAMMOHAN. L Sr. Linux Administator

(e.g., application servers, database servers) while maintaining low latency and high
throughput.
4. Handling Thousands of Concurrent Connections: Nginx can handle tens of
thousands of concurrent connections due to its lightweight and asynchronous nature.
This makes it well-suited for handling high traffic volumes, especially for real-time
applications.

When to Choose Apache

While Nginx is often better suited for high-load environments, there are certain situations
where Apache might be the better choice:

1. Complex Configuration Needs: If your application requires complex configurations


(e.g., URL rewriting, fine-grained access control), Apache may be more suitable due
to its extensive set of modules and configuration options.
2. Legacy Systems: If you are working with legacy systems or applications that rely
heavily on .htaccess files or require certain Apache-specific features, Apache might be
the better choice.
3. Dynamic Content: Apache is well-integrated with dynamic content handling, such as
PHP via mod_php. If your site relies heavily on dynamic content generation, Apache
may be simpler to set up.
4. Compatibility with Older Software: If you are using older software or applications
that are optimized for Apache, it might be easier to stick with Apache.

Best Web Server for High Loads

• For static-heavy websites and high concurrency: Nginx is generally the better
option. It excels at handling a large number of concurrent connections with lower
resource usage, making it ideal for high-traffic, static content-driven websites.
• For complex configurations and dynamic content: Apache might be better if you
need more flexibility in configuration, especially if your website depends on complex
.htaccess rules or heavy dynamic content generation via Apache modules.

25. What is the path of Apache configuration files?

The path of Apache configuration files can vary depending on the distribution of Linux
you're using (e.g., Ubuntu, CentOS, or Debian). However, there are common locations where
Apache configuration files are typically stored:

Main Apache Configuration File

• For Debian/Ubuntu-based systems (e.g., Ubuntu, Debian, Linux Mint):


o Main Apache Configuration: /etc/apache2/apache2.conf
o This is the main configuration file where general Apache settings are defined.
• For Red Hat/CentOS-based systems (e.g., CentOS, RHEL, Fedora):
o Main Apache Configuration: /etc/httpd/conf/httpd.conf
RAMMOHAN. L Sr. Linux Administator

o This is the main configuration file on CentOS or RHEL systems.

Other Important Apache Configuration Files

1. Virtual Hosts Configuration:


o Debian/Ubuntu: /etc/apache2/sites-available/
▪ Here, individual configuration files for each virtual host are stored (e.g.,
/etc/apache2/sites-available/000-default.conf for the default site). Sites in this
directory need to be enabled with a2ensite.
o CentOS/RHEL: /etc/httpd/conf.d/
▪ Apache reads configurations from the files in this directory automatically.
Virtual hosts or additional configurations are usually stored here (e.g.,
/etc/httpd/conf.d/vhost.conf).
2. SSL Configuration:
o Debian/Ubuntu: /etc/apache2/sites-available/default-ssl.conf
o CentOS/RHEL: /etc/httpd/conf.d/ssl.conf

These files are where you configure SSL settings for Apache (e.g., for SSL
certificates).

3. Apache Modules Configuration:


o Debian/Ubuntu: /etc/apache2/mods-available/ and /etc/apache2/mods-enabled/
▪ Apache modules are stored in the mods-available directory and can be enabled
using a2enmod.
o CentOS/RHEL: /etc/httpd/conf.modules.d/
▪ This directory contains module configuration files that are included by the
main Apache configuration.
4. Additional Configuration Files:
o Debian/Ubuntu: /etc/apache2/conf-available/ and /etc/apache2/conf-enabled/
▪ Configuration files in conf-available can be enabled using a2enconf.
o CentOS/RHEL: Apache's extra configuration files are usually placed in
/etc/httpd/conf.d/.
5. Logs Configuration:
o Apache log files are typically found in:
▪ Debian/Ubuntu: /var/log/apache2/
▪ CentOS/RHEL: /var/log/httpd/
o The primary log files are:
▪ access.log (for tracking HTTP requests)
▪ error.log (for logging errors and warnings)

Other Paths and Files:

• Debian/Ubuntu:
o User-specific configuration: /etc/apache2/envvars — Contains environment variables
used by Apache.
o Access Control and Directory Settings: /etc/apache2/conf-available/security.conf —
Security-related configurations like AllowOverride and Options.
• CentOS/RHEL:
o User-specific configuration: /etc/httpd/conf.d/userdata/ — Contains user-specific
configurations.
RAMMOHAN. L Sr. Linux Administator

How to Check Apache Configuration Files

You can check Apache's configuration and syntax using the following command:

apache2ctl configtest # On Debian/Ubuntu


httpd -t # On CentOS/RHEL

This command will help you check for any syntax errors in your configuration files.

Virtualization & Cloud Computing

26. What is virtualization?

Virtualization is the process of creating a virtual (rather than physical) version of something,
such as an operating system (OS), server, storage device, or network resource. It allows
multiple operating systems (OS) or environments to run on a single physical machine,
enabling better resource utilization, isolation, and scalability.

At its core, virtualization abstracts the physical hardware, making it appear as if there are
multiple independent systems running on a single physical machine.

Key Concepts of Virtualization

1. Virtual Machine (VM): A Virtual Machine (VM) is a software-based simulation of


a physical computer. It runs an operating system (called the guest OS) and behaves
just like a physical computer, but it's hosted on a physical machine (the host). Each
VM has its own virtual CPU, memory, storage, and network interfaces.
2. Hypervisor: A Hypervisor is the software layer that enables virtualization. It allows
multiple VMs to run on a single host. There are two types of hypervisors:
o Type 1 Hypervisor (Bare-metal): Installed directly on the hardware, without
needing an underlying operating system. Examples: VMware ESXi, Microsoft Hyper-
V, Xen.
o Type 2 Hypervisor (Hosted): Installed on top of an existing operating system.
Examples: VMware Workstation, Oracle VirtualBox, Parallels Desktop.
3. Host Machine: The Host Machine is the physical computer or server on which
virtual machines run. It provides the physical resources (CPU, RAM, disk) to the
virtual machines through the hypervisor.
4. Guest Machine: A Guest Machine (or VM) is the virtual computer running inside a
hypervisor. Each guest can run its own operating system independently of the host
OS.

Types of Virtualization

1. Hardware Virtualization: This is the most common form of virtualization. The


hypervisor abstracts the hardware of the host machine and allocates virtual hardware
to the VMs. It allows multiple VMs to share the resources of the physical machine,
such as CPU, memory, and storage.
2. Operating System Virtualization (Containerization): In OS-level virtualization (or
containers), the underlying OS provides multiple isolated environments called
RAMMOHAN. L Sr. Linux Administator

containers. Unlike full virtualization, containers share the host OS's kernel but run in
isolated user spaces. Examples: Docker, LXC.
3. Storage Virtualization: This type of virtualization abstracts the physical storage
devices and presents them as a single logical unit, regardless of the physical hardware
used. It improves storage management, scalability, and redundancy. Examples: SAN
(Storage Area Network), NAS (Network-Attached Storage).
4. Network Virtualization: Network virtualization combines multiple physical network
devices into a single logical network. It allows for better management of network
resources and isolation between different networks. Examples: VLAN (Virtual Local
Area Network), SDN (Software-Defined Networking).
5. Desktop Virtualization: Desktop virtualization enables users to run desktop
environments remotely on a server. Each user has a virtual desktop that can be
accessed from any device. This is often used in enterprise environments. Examples:
VMware Horizon, Citrix Virtual Apps.

Benefits of Virtualization

1. Resource Efficiency: Virtualization allows multiple virtual environments to run on a


single physical machine, leading to better utilization of hardware resources like CPU,
memory, and storage.
2. Isolation: Each virtual machine is isolated from others, meaning that if one VM
crashes or is compromised, the other VMs and the host are unaffected.
3. Cost Savings: Virtualization reduces the need for multiple physical machines, which
reduces hardware costs, power consumption, and cooling needs.
4. Scalability: Virtualization makes it easy to create new virtual machines quickly,
allowing for rapid scaling of infrastructure as needed.
5. Flexibility: Virtual machines can run different operating systems (e.g., Linux,
Windows) on the same physical hardware.

27. What is cloud computing?

Cloud computing is adopted by every company, whether it is an MNC or a startup many are
still migrating towards it because of the cost-cutting, lesser maintenance, and the increased
capacity of the data with the help of servers maintained by the cloud providers.

One more reason for this drastic change from the On-premises servers of the companies to
the Cloud providers is the ‘Pay as you go’ principle-based services provided by them i.e., you
only have to pay for the service which you are using. The disadvantage On-premises server
holds is that if the server is not in use the company still has to pay for it.

Cloud Computing means storing and accessing the data and programs on remote servers that
are hosted on the internet instead of the computer’s hard drive or local server. Cloud
computing is also referred to as Internet-based computing, it is a technology where the
resource is provided as a service through the Internet to the user. The data that is stored can
be files, images, documents, or any other storable document.

28. What is AWS?

AWS stands for Amazon Web Services, It is an expanded cloud computing platform provided
by Amazon Company. AWS provides a wide range of services with a pay-as-per-use pricing
RAMMOHAN. L Sr. Linux Administator

model over the Internet such as Storage, Computing power, Databases, Machine Learning
services, and much more. AWS facilitates for both businesses and individual users with
effectively hosting the applications, storing the data securely, and making use of a wide
variety of tools and services improving management flexibility for IT resources.

29. What is EC2?

EC2 stands for Elastic Compute Cloud. EC2 is an on-demand computing service on the AWS
cloud platform. Under computing, it includes all the services a computing device can offer to
you along with the flexibility of a virtual environment. It also allows the user to configure
their instances as per their requirements i.e. allocate the RAM, ROM, and storage according
to the need of the current task. Even the user can dismantle the virtual device once its task is
completed and it is no more required. For providing, all these scalable resources AWS
charges some bill amount at the end of every month, the bill amount is entirely dependent on
your usage. EC2 allows you to rent virtual computers. The provision of servers on AWS
Cloud is one of the easiest ways in EC2. EC2 has resizable capacity. EC2 offers security,
reliability, high performance, and cost-effective infrastructure so as to meet the demanding
business needs.

30. How can we configure an EC2 instance?

EC2 stands for Elastic Compute Cloud. EC2 is an on-demand computing service on the AWS
cloud platform. Under computing, it includes all the services a computing device can offer to
you along with the flexibility of a virtual environment. It also allows the user to configure
their instances as per their requirements i.e. allocate the RAM, ROM, and storage according
to the need of the current task.

Amazon EC2 is a short form of Elastic Compute Cloud (ECC) it is a cloud computing service
offered by the Cloud Service Provider AWS. You can deploy your applications in EC2
servers without worrying about the underlying infrastructure. You configure the EC2-
Instance in a very secure manner by using the VPC, Subnets, and Security groups. You can
scale the configuration of the EC2 instance you have configured based on the demand of the
application by attaching the autoscaling group to the EC2 instance. You can scale up and
scale down the instance based on the incoming traffic of the application.31. What is an AMI?

An Amazon Machine Image is a special type of virtual appliance that is used to instantiate
(create) a virtual machine within EC2. It serves as the basic unit of deployment for services
delivered using EC2. Whenever you want to launch an instance, you need to specify AMI. To
launch instances, you can also use different AMIs. If you want to launch multiple instances
from a single AMI, then you need multiple instances of the same configuration.

32. How can we choose the required instance type?

Different Amazon EC2 instance types are designed for certain activities. Consider the unique
requirements of your workloads and applications when choosing an instance type. This might
include needs for computing, memory, or storage.

What are the AWS EC2 Instance Types?


RAMMOHAN. L Sr. Linux Administator

1. General Purpose Instances

2. Compute Optimized Instances

3. Memory-Optimized Instances

4. Storage Optimized Instances

5. Accelerated Computing Instances

You might also like