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

Linux and System Programming

LINUX

Uploaded by

inyiakodsamuel85
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Linux and System Programming

LINUX

Uploaded by

inyiakodsamuel85
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Content List

Content List............................................................................................................................ 1

Linux .......................................................................................................................................... 3

Introduction to Linux: ............................................................................................................ 3

Key Features of Linux: .......................................................................................................... 3

Common Linux Distributions: ............................................................................................... 4

Linux File System Structure (Ret Hat OS): ............................................................................... 5

Detail View ................................................................................................................................ 9

/Home Directory .................................................................................................................... 9

/bin ....................................................................................................................................... 10

/Sbin ..................................................................................................................................... 10

Interview Question ............................................................................................................... 11

/etc ........................................................................................................................................ 12

/proc ..................................................................................................................................... 12

Installing Packages: ................................................................................................................. 13

Downloading Links:................................................................................................................. 13

Basic Linux Commands ........................................................................................................... 14

File and Directory Management: ......................................................................................... 14

File Content Viewing and Manipulation: ................................................................................. 18

Text Editors: ......................................................................................................................... 19

File Permission and Ownership: .......................................................................................... 20

Detailed view: ...................................................................................................................... 23

1
Umask value: ....................................................................................................................... 23

Interview Questions: ............................................................................................................ 24

Time, Date, and Timezones: ................................................................................................ 25

User and Group Administration Commands:....................................................................... 26

DEMO: User Account Management and Permissions ......................................................... 28

Solution to Task ................................................................................................................... 28

System Information:............................................................................................................. 33

Process Management: .......................................................................................................... 34

Task: Deployment and Verification of Apache HTTP Server. ............................................. 35

Service Management Commands: ....................................................................................... 35

Task Solution: ...................................................................................................................... 36

Networking: ......................................................................................................................... 37

2
Linux
Introduction to Linux:
Linux is an open-source operating system kernel initially developed by Linus Torvalds in 1991.
Since then, it has evolved into a powerful and versatile platform that runs everything from
small embedded systems to massive server farms.

At its core, Linux is built on the Unix operating system principles, emphasizing stability,
efficiency, and flexibility. What sets Linux apart is its open nature, allowing anyone to view,
modify, and distribute its source code under the terms of the GNU General Public License
(GPL).

Key Features of Linux:


1. Open Source: Linux's source code is freely available, enabling a collaborative
development model where developers worldwide contribute to its improvement.

2. Customizability: Linux offers a high degree of customization, allowing users to tailor


their system to their specific needs. With various distributions (distros), users can
choose one that aligns with their preferences in terms of desktop environment, package
management, and system architecture.

3. Stability and Security: Linux is renowned for its stability and security. Its robust
architecture and stringent permission system make it less prone to crashes and malware
attacks compared to other operating systems.

4. Command-Line Interface (CLI): While Linux provides graphical user interfaces


(GUIs), it's known for its powerful command-line interface (CLI). This allows users to
perform complex tasks efficiently, automate processes, and manage the system
remotely.

5. Vast Software Ecosystem: Linux boasts a vast array of open-source software, covering
everything from productivity tools and multimedia applications to development
environments and server software.

3
Common Linux Distributions:
1. Ubuntu Linux: Ubuntu is known for its user-friendliness, extensive community
support, and regular release cycle. It's a great choice for beginners and experienced
users alike, offering a balance between stability and up-to-date software.

2. Fedora Linux: Fedora emphasizes the use of cutting-edge technologies and serves as
a testing ground for features that may eventually be incorporated into Red Hat
Enterprise Linux. It's favored by developers and enthusiasts who want access to the
latest software releases.

3. Red Hat Enterprise Linux (RHEL): RHEL is a leading distribution in the enterprise
sector, known for its stability, long-term support, and comprehensive ecosystem of
certified software and hardware. It's backed by Red Hat, Inc., providing premium
support and services.

4. CentOS Linux: CentOS, short for Community ENTerprise Operating System, is a free
and open-source distribution built from the same sources as RHEL. It aims to provide
a stable and compatible platform for organizations and individuals who prefer the
RHEL environment without the associated subscription costs.

5. Amazon Linux 2 AMI: Amazon Linux 2 is a lightweight, high-performance Linux


distribution designed specifically for Amazon Web Services (AWS) cloud
environments. It includes packages optimized for running applications on AWS
infrastructure and comes with long-term support.

6. SUSE Linux Enterprise Server (SLES): SUSE Linux Enterprise Server is a powerful
distribution tailored for mission-critical workloads and enterprise deployments. It offers
high availability, security, and interoperability features, making it a preferred choice for
businesses.

7. Gentoo Linux: Gentoo is a source-based distribution known for its flexibility and
performance optimization. Users have granular control over system configuration and
package management, allowing for a highly customized and efficient computing
environment.

8. Mandriva Linux: Mandriva, formerly known as Mandrake, was a user-friendly


distribution with a focus on simplicity and ease of use. While it's no longer actively
maintained, its legacy continues through derivative projects like OpenMandriva.

4
9. Debian Linux: Debian is one of the oldest and most influential Linux distributions,
known for its commitment to free and open-source software principles. It serves as the
foundation for many other distributions, including Ubuntu and its variants.

10. Slackware: Slackware is one of the earliest Linux distributions, known for its
simplicity, stability, and adherence to Unix-like principles. It's favoured by experienced
users who appreciate its minimalistic approach and hands-on system administration.

Linux File System Structure (Ret Hat OS):


The Linux file system structure provides a hierarchical organization of files and directories,
starting from the root directory (/). Here's an overview of the key directories in the Linux file
system:

5
1. / (Root Directory):

 The root directory is the top-level directory in the file system hierarchy.

 All other directories and files are contained within the root directory.

 It is represented by a forward slash (/).

2. /bin (Binaries):

6
 Contains essential executable files (binaries) required for system booting and
basic operations.

 Binaries stored here are accessible to all users.

3. /boot (Boot Files):

 Contains boot loader files, kernel images, and other files required for system
booting.

4. /dev (Devices):

 Contains device files representing hardware devices and system resources.

 Devices are represented as files in Linux, allowing them to be accessed using


standard file operations.

5. /etc (Configuration Files):

 Contains system-wide configuration files and directories.

 Configuration files for various services, applications, and system settings are
stored here.

6. /home (User Home Directories):

 Contains user home directories, each typically named after the corresponding
username.

 Users have read and write access to their respective home directories.

7. /lib (Libraries):

 Contains shared libraries (shared objects) required by executable files in /bin


and /sbin.

 Essential libraries for system functions and services are stored here.

8. /mnt (Mount Points):

 Used as a temporary mount point for mounting external storage devices such as
USB drives and network shares.

9. /opt (Optional):

7
 Contains optional software packages or applications installed by the system
administrator.

 Third-party software and add-on packages are typically installed here.

10. /proc (Process Information):

 Virtual file system that provides information about running processes and
system resources.

 Contains directories and files representing system processes, memory usage,


CPU information, and more.

11. /root (Root Home Directory):

 Home directory for the root user (superuser).

 Root user has full administrative privileges and can access system-wide
directories and files.

12. /sbin (System Binaries):

 Contains essential system binaries required for system administration and


maintenance.

 Binaries stored here are typically executed by the root user.

13. /tmp (Temporary Files):

 Used for storing temporary files created by system processes and users.

 Files in /tmp are typically deleted upon system reboot.

14. /usr (User Binaries and Data):

 Contains user-readable data, documentation, and additional binaries not


required for system booting.

 Subdirectories include /usr/bin for user binaries, /usr/sbin for system binaries,
/usr/lib for libraries, and /usr/share for shared data.

15. /var (Variable Files):

 Contains variable data files that may change frequently during system
operation.

8
 Subdirectories include /var/log for log files, /var/spool for print and mail spool
files, and /var/tmp for temporary files.

Detail View
/Home Directory
Contains normal users home directory details.

We can view the content of the home directory by running

ls /home

To add another user to the system, we use the adduser or useradd. Using

adduser Simon

we get an error (Permission Denied). this is because the ec2-user does not have the permission
for adding a user. To view the current user in the system, run

whoami

The root user is the user with the permission to add other users. So, in order to add a user using
the ec2-user, we muss add sudo to the command (the sudo command gives the ec2-user
temporary admin priveledges).

sudo adduser Simon

9
The above users we’ve added are normal users, to add a user as a root user, we can use the

sudo -u root adduser Simon

/bin
Contain binary files [commands]

1. ls:
 Lists directory contents.
 Example: ls.
2. whoami:
 Prints the current username.
 Example: whoami.
3. clear:
 Clears the terminal screen.
 Example: clear.
4. cd:
 Changes the current directory.
 Example: cd /path/to/directory.
5. chmod:
 Changes file permissions.
 Example: chmod u+x filename.
BUT some commands like the adduser are not found in the bin directory but rather in the sbin
directory.
/Sbin
Contains system binary files to be execute by the administrator

1. adduser:

 Adds a new user to the system.

 Example: adduser username.

10
2. passwd:

 Changes a user's password.

 Example: passwd username.

3. chage:

 Changes user password expiry information.

 Example: chage -M 90 username.

Interview Question

What is the difference between bin and Sbin in Linux ?

In Linux, the 'bin' and 'sbin' directories serve different purposes. The 'bin' directory, short
for 'binaries,' contains essential executable files that are fundamental to the basic operations
of the system. These binaries are accessible to all users of the system. On the other hand,
the 'sbin' directory, short for 'system binaries,' contains executable files that are primarily
used for system administration tasks. These binaries are typically meant to be executed by
the root user or other administrative users with elevated privileges. In summary, while both
directories contain executable files, 'bin' houses essential binaries for general use, whereas
'sbin' is reserved for binaries used specifically for system administration.

11
/etc
Contains configuration files

 /etc/ssh/sshd_config: Configuration file for the SSH server (sshd), specifying server
settings such as authentication methods and port number.

cat /etc/ssh/sshd_config

 /etc/shadow: Contains encrypted password hashes for user accounts.

cat /etc/shadow

 /etc/passwd: Contains basic information about user accounts, such as usernames and
user IDs.

cat /etc/passwd

/proc
Provides access to kernel data structures and system information.

 meminfo:

 Contains information about system


memory usage, including total
memory, free memory, and memory
usage by different components.

cat /proc/meminfo

 cpuinfo:

 Provides detailed information about


the CPU(s) installed on the system,
such as model name, CPU speed,
cache size, and flags.

cat /proc/cpuinfo

12
Installing Packages:
Here's the format for installing packages along with examples:

a. apt-get/apt: Package management tool for Debian-based systems like Ubuntu.

 Installation Example: sudo apt-get install package_name

 Update Repository: sudo apt-get update

 Upgrade Installed Packages: sudo apt-get upgrade

b. yum/dnf: Package management tool for Red Hat-based systems like CentOS.

 Installation Example: sudo yum install package_name

 Update Repository: sudo yum update

 Upgrade Installed Packages: sudo yum upgrade

Downloading Links:
When you need to download files or content from the internet directly to your system, you can
use the following commands:

a. wget:

 Description: A command-line tool for downloading files from the web.

 Installation (if not installed):

 Debian-based systems: sudo apt-get install wget

 Red Hat-based systems: sudo yum install wget

 Usage:

wget [options] URL

 Example:

wget https://example.com/file.txt

b. curl:

 Description: Another versatile command-line tool for transferring data with URLs.

 Installation (if not installed):

13
 Debian-based systems: sudo apt-get install curl

 Red Hat-based systems: sudo yum install curl

 Usage:

curl [options] URL

 Example:

curl -O https://example.com/file.txt

Basic Linux Commands


How do we run Linux commands in our FEWA projects?

1. Create a Linux server in the AWS Cloud.

2. Connect via ssh into the server (make sure that ssh port 22 is open).

3. Start running tasks/workloads using commands.

File:

 In computing, a file is a collection of data or information that is stored on a storage


device.

 Files can contain text, images, programs, or any other type of data.

 Each file is identified by a unique name and can be accessed, modified, or deleted by
the user or the operating system.

Directory:

 In computing, a directory (also known as a folder) is a file system structure used to


organize and store files.

 Directories can contain files and other directories, creating a hierarchical structure.

 They provide a way to organize and manage files efficiently, making it easier for users
to locate and access the information they need.

File and Directory Management:


This category involves commands for managing files and directories in the Linux system.

1. ls(list), ll (long list): List directory contents.

14
 Example: ls (lists files and directories in the current directory).

 Example: ls -l (displays detailed information about files and directories).

 Example: ls -a (lists all files and directories, including hidden ones).

 Example: ls -h (displays file sizes in a human-readable format).

 Or

ll (similar to ls -l, but with more user-friendly formatting).

 Example: ll -t (displays files sorted by modification time).

 Example: ll -tr (displays files sorted by modification time in reverse order).

2. cd: Change directory.

 Example: cd /path/to/directory (changes the current directory to the specified


path).

 Example: cd .. (moves up one level in the directory hierarchy).

 Example: cd ../../.. (moves up three levels in the directory hierarchy).

 Example: cd - (switches to the previous directory).

 Example: cd ~ (switches to the user's home directory).

3. pwd: Print working directory.

 Example: pwd (displays the current working directory).

4. mkdir: Create a directory.

Example:

 mkdir new_directory (creates a directory named "new_directory").

 mkdir -p class1/class2/class3/class4 (creates a directory structure with four


nested directories (class1, class2, class3, and class4). The -p option ensures that
parent directories are created if they don't already exist.)

or we do it manually which is time consuming

15
mkdir class1
mkdir class1/class2
mkdir class1/class2/class3
mkdir class1/class2/class3/class4

This sequence of commands creates each directory (class1, class2, class3, and
class4) one after the other. Each mkdir command creates a single directory.
This approach allows you to create the directory structure step by step,
creating each level as needed.

 mkdir -pv class1/class2/class3/class4:


mkdir: This is the command used to create directories.
-p: This option tells mkdir to create parent directories as needed.
-v: This option (verbose) displays a message for each directory created,
providing visibility into the process.
So, when you run mkdir -pv class1/class2/class3/class4, it will create the
directory structure class1/class2/class3/class4 and display a message for each
directory created, like this:

mkdir: created directory 'class1'


mkdir: created directory 'class1/class2'
mkdir: created directory 'class1/class2/class3'
mkdir: created directory 'class1/class2/class3/class4'

5. touch: Create an empty file or update file timestamps.

 Example: touch new_file.txt (creates an empty file named "new_file.txt").

If "new_file.txt" already exists, touch will update its timestamp without


modifying the file's content.

6. echo: Display a line of text.

 Example: echo "I am a DevOps Engineer" (displays the text "I am a DevOps
Engineer" on the terminal).

 Example: echo "I am a DevOps Engineer" > dev (redirects the output of the
echo command to a file named "dev").

7. tree: Display directory tree structure.

16
 Example: tree (displays the directory tree structure starting from the current
directory).

 Example: tree /path/to/directory (displays the directory tree structure starting


from the specified directory).

8. cp: Copy files and directories.

 Example: cp file1.txt file2.txt (copies file1.txt to file2.txt).

9. mv: Move or rename files and directories.

 Example: mv old_file.txt new_file.txt (renames old_file.txt to new_file.txt).

10. rm: Remove files or directories.

 Example: rm file.txt (removes the file named "file.txt").

 Example: rm -r directory (removes the directory and its contents recursively).

 Example: rm -rf directory (forcefully removes the directory and its contents
recursively without prompting for confirmation).

11. rmdir: Remove empty directories.

 Example: rmdir directory (removes the empty directory named "directory").

12. cat: Concatenate and display file contents.

 Example: cat file.txt (displays the contents of file.txt).

 Example: cat -n file.txt (displays the contents and the total number of lines of
file.txt).

13. grep: Search for patterns in files.

 Example: grep "pattern" file.txt (searches for "pattern" in "file.txt").

 Example: grep -i "pattern" file.txt (performs case-insensitive search for


"pattern").

 Example: grep -r "pattern" directory (recursively searches for "pattern" in


"directory" and its subdirectories).

14. find: Search for files and directories.

17
 Example: find /path/to/search -name "filename" (searches for files named
"filename" in the specified path).

 Example: find /path/to/search -type d (lists directories in the specified path).

15. sort: Sort lines of text files.

 Example: sort file.txt (sorts lines in "file.txt" alphabetically).

 Example: sort -r file.txt (sorts lines in "file.txt" in reverse order).

 Example: sort -n file.txt (sorts lines in "file.txt" numerically).

 Example: sort -k2 file.txt (sorts lines in "file.txt" based on the second column).

File Content Viewing and Manipulation:


This category includes commands for viewing and manipulating the contents of files in the
Linux system.

1. less: View file contents one page at a time.

 Example: less large_file.txt (displays large_file.txt one page at a time).

2. more: View file contents one page at a time (similar to less).

 Example: more large_file.txt (displays large_file.txt one page at a time).

3. head: Display the beginning of a file.

 Example: head file.txt (displays the first 10 lines of file.txt).

 Example: head -1 file.txt (displays the first 1 line of "file.txt").

 Example: head -5 file.txt (displays the first 5 lines of "file.txt").

4. tail: Display the end of a file.

 Example: tail file.txt (displays the last 10 lines of file.txt).

 Example: tail -n 1 file.txt (displays the last 1 line of "file.txt").

 Example: tail -n 5 file.txt (displays the last 5 lines of "file.txt").

5. wc: Count lines, words, and characters in a file.

 Example: wc file.txt (displays line, word, and character count of file.txt).

18
 Example: wc -w file.txt (displays the number of words in "file.txt").

 Example: wc -c file.txt (displays the number of characters in "file.txt").

 Example: wc -l file.txt (displays the number of lines in "file.txt").

Text Editors:
Text editors are essential tools for editing files and creating new ones in a Linux environment.
Here are two popular text editors along with examples of how to use them:

1. Nano:

 Nano is a simple and user-friendly text editor available on most Linux systems.

 Opening a File: nano filename.txt (opens or creates a new file named


"filename.txt" in the nano editor).

 Saving Changes: After making changes, press Ctrl + O to save the file.

 Exiting Nano: Press Ctrl + X to exit nano.

 Navigation: Use the arrow keys to navigate through the file.

2. Vim (Vi Improved):

 Vim is a powerful and customizable text editor with extensive features.

 Opening a File: vim filename.txt (opens or creates a new file named


"filename.txt" in the vim editor).

 Entering Edit Mode: Press i to enter insert mode and start typing.

 Saving Changes: In normal mode, type :w and press Enter to save the file.

 Exiting Vim: In normal mode, type :q and press Enter to exit vim. If changes
were made and not saved, use :q! to force exit without saving.

 Navigation: Use the arrow keys or h, j, k, l to move the cursor. Use gg to move
to the beginning of the file and G to move to the end.

19
File Permission and Ownership:
In Linux, each file and directory has three types of permissions, which are represented by three
sets of letters or numbers:

1. Owner Permissions: These permissions apply to the user who owns the file or
directory.

2. Group Permissions: These permissions apply to the group associated with the file or
directory.

3. Other Permissions: These permissions apply to all other users on the system who are
not the owner and not in the group associated with the file or directory.

Each set of permissions consists of three characters, representing the ability to read, write, and
execute the file or directory:

 r (Read): Allows reading/viewing the contents of the file or directory.

 w (Write): Allows modifying or deleting the file or directory, or adding new files to a
directory.

 x (Execute): Allows executing the file or accessing contents of the directory (for
directories).

These permissions are represented in various ways:

1. Symbolic Notation:

 r: Read permission.

 w: Write permission.

 x: Execute permission.

 -: No permission.

For example, rwx indicates read, write, and execute permissions, while r-- indicates read-only
permissions.

2. Numeric Notation:

 Each permission is assigned a numeric value: read (4), write (2), and execute
(1).

20
 These values are then added together to represent the permissions.

 For example, rwx would be represented as 7 (4 + 2 + 1), while r-- would be


represented as 4 (4 + 0 + 0).

The numeric notation is calculated separately for the owner, group, and other permissions,
resulting in three-digit numbers.

Here are some examples of how file permissions are represented using both symbolic and
numeric notation:

Symbolic Notation:

1. rwxr-xr--: Owner has read, write, and execute permissions; group has read and execute
permissions; others have read-only permissions.

2. rw-rw-r--: Owner and group have read and write permissions; others have read-only
permissions.

3. rwxr--r--: Owner has read, write, and execute permissions; group and others have read-
only permissions.

4. ---------: No permissions for anyone (no read, write, or execute permissions).

Numeric Notation:

1. 755: Owner has read, write, and execute permissions (4 + 2 + 1 = 7); group and others
have read and execute permissions (4 + 1 = 5).

2. 644: Owner has read and write permissions (4 + 2 = 6); group and others have read-
only permissions (4).

3. 744: Owner has read, write, and execute permissions (4 + 2 + 1 = 7); group and others
have read-only permissions (4).

4. 000: No permissions for anyone (no read, write, or execute permissions).

Here are examples of how to change permissions of files and directories using the chmod
command:

1. Changing Permissions with Symbolic Notation:

21
 To grant read, write, and execute permissions to the owner of a file: chmod
u+rwx file.txt

 To revoke write permission from the group of a directory: chmod g-w directory

 To grant execute permission to others for a file: chmod o+x file.txt

 To grant read and write permissions to all (owner, group, and others) for a file:
chmod a+rw file.txt

 To set specific permissions for a file: chmod u=rw,g=r,o=r file.txt (Owner:


read/write, Group: read, Others: read)

2. Changing Permissions with Numeric Notation:

 To grant read, write, and execute permissions to the owner of a file: chmod 700
file.txt

 To revoke write permission from the group of a directory: chmod 755 directory

 To grant execute permission to others for a file: chmod 744 file.txt

 To grant read and write permissions to all (owner, group, and others) for a file:
chmod 666 file.txt

 To set specific permissions for a file: chmod 644 file.txt (Owner: read/write,
Group: read, Others: read)

22
Detailed view:

Umask value:
The umask value, short for "user file creation mask," is a set of permissions that determine the
default permissions applied to newly created files and directories by a user. It works by
subtracting the umask value from the maximum permissions (usually 777 for directories and
666 for files) to determine the actual permissions.

The umask value is typically exp ressed in octal notation and can be viewed or modified using
the umask command in a terminal.

Here's how it works:

 Each digit in the umask value represents the permissions that are masked (i.e.,
removed) from the maximum permissions.

 The first digit corresponds to the owner's permissions, the second to the group's
permissions, and the third to others' permissions.

 For example, a umask value of 022 means that write permissions (2) are masked for
both the group and others, but not for the owner.

Common umask values and their effects:

23
 022: Default for many distributions. Removes write permissions for group and others,
leaving read and execute permissions intact.

 027: Removes write and execute permissions for group and others, leaving read
permissions intact.

 077: Removes all permissions for group and others, leaving only the owner with read,
write, and execute permissions.

 002: Less common. Removes write permissions for others but allows all permissions
for the owner and group.

Interview Questions:

0022 and 0002 respectively

Others:

Here are examples of how to change ownership and group ownership of files and directories
using the chown and chgrp commands:

1. Changing Ownership with chown:

 To change the owner of a file: chown new_owner file.txt

24
 To change the owner and group of a file: chown new_owner:new_group
file.txt

 To change the owner of a directory and its contents recursively: chown -R


new_owner directory

2. Changing Group Ownership with chgrp:

 To change the group of a file: chgrp new_group file.txt

 To change the group of a directory and its contents recursively: chgrp -R


new_group directory

Time, Date, and Timezones:


Linux provides utilities for managing system time, date, and timezones, ensuring accurate
timekeeping and synchronization.

Setting Date:

 Use the date command to display or set the system date and time.

 Example: date (displays the current system date and time).

 Example: date MMDDHHMMYYYY (sets the system date and time to the
specified value).

Setting Timezones:

 Use the timedatectl command to view or change the system timezone.

 Example: timedatectl (displays the current system timezone).

 Example: sudo timedatectl set-timezone timezone (sets the system timezone


to the specified timezone).

 Example: timedatectl list-timezones (display a list of all available timezones.)

25
User and Group Administration Commands:
User and group administration commands in Linux are essential for managing user accounts
and groups on the system. These commands allow system administrators to create, modify, and
delete user accounts, as well as manage group memberships and permissions.

1. useradd / adduser:
 useradd: Command-line utility to create new user accounts in Linux.

 Example: sudo useradd username (creates a new user account named


"username").

 adduser: Interactive command for adding new user accounts with additional
configuration options.

 Example: sudo adduser username (interactively prompts for user details and
creates a new user account).

2. userdel:

 Command to delete user accounts from the system.

 Example: sudo userdel username (deletes the user account named


"username").

3. passwd:

 Command-line utility to change user passwords.

 Example: passwd username (allows the user to change their password).

4. chage:

 Command to change user password expiry information.

 Example: sudo chage -E 2024-12-31 username (sets the password expiry date
for the user account "username" to December 31, 2024).

5. groupadd / groupdel:

 groupadd: Command to create new groups on the system.

 Example: sudo groupadd groupname (creates a new group named


"groupname").

26
 groupdel: Command to delete groups from the system.

 Example: sudo groupdel groupname (deletes the group named "groupname").

6. usermod:

 Command to modify user account properties.

 Example: sudo usermod -aG groupname username (adds the user


"username" to the group "groupname").

7. id:

 Command to display user and group information for a specified user.

 Example: id username (displays user and group information for the user
"username").

8. groups:

 Command to display groups a user belongs to.

 Example: groups username (displays the groups the user "username" belongs
to).

9. lid:

 Command to display information about users and groups in a more user-friendly format.

 Example: lid username (displays detailed information about the user


"username").

10. su / sudo:

 su: Command to switch user accounts or become the superuser (root).

 Example: su username (switches to the user "username").

 sudo: Command to execute commands with superuser (root) privileges.

 Example: sudo command (executes "command" with root privileges).

27
DEMO: User Account Management and Permissions
Creation of User Accounts:

Create user accounts for Louis and Hyson. Verify the successful creation of both accounts.

Password Assignment:

Assign passwords to the Louis and Hyson accounts to ensure secure access. Verify the
successful assignment of passwords.

Group Membership:

Add Louis to the "presidents" group. Confirm the update of Louis's membership in the group.

Administrative Privileges:

Grant sudo access to the Louis account for administrative privileges.

External Server Access:

Access the server externally using Louis's credentials.

Account Expiration:

Set the expiration for Louis's account to 8 years.

Solution to Task
1. Creation of User Accounts:

sudo useradd Louis


sudo useradd Hyson

Explanation: The useradd command is used to create new user accounts. Here, we create user
accounts for Louis and Hyson using the sudo command to execute them with administrative
privileges.

Verification:

sudo cat /etc/passwd | grep Louis


sudo cat /etc/passwd | grep Hyson

28
Explanation: We use the cat command to display the contents of the /etc/passwd file, which
stores user account information. The grep command is used to filter the output and check if the
user accounts for Louis and Hyson have been successfully created.

2. Password Assignment:

sudo passwd Louis


sudo passwd Hyson

Explanation: The passwd command is used to assign passwords to user accounts. Here, we set
passwords for the Louis and Hyson accounts to ensure secure access.

Verification:

sudo tail /etc/shadow | grep Louis


sudo tail /etc/shadow | grep Hyson

Explanation: We use the tail command to display the last few lines of the /etc/shadow file,
which stores encrypted password information. The grep command is used to filter the output
and verify that passwords have been successfully assigned to the Louis and Hyson accounts.

3. Group Membership:

cat /etc/group | grep presidents


sudo groupadd presidents
sudo usermod -aG presidents Louis

Explanation: The first command checks if the group named "presidents" already exists in the
/etc/group file. We create a new group called "presidents" using the groupadd command.
Then, we add Louis to the "presidents" group using the usermod command with the -aG option
to append Louis to the group.

Verification:

sudo groups Louis OR


id Louis OR
sudo lid Louis

Explanation:

 We use the groups command to display the groups that Louis belongs to. This verifies
that Louis has been successfully added to the "presidents" group.

29
 The id command displays user and group information for the user "Louis", including
the groups that Louis belongs to.

 The lid command provides a more detailed and user-friendly view of user and group
information, including supplementary group memberships, for the user "Louis". We use
sudo to execute lid with administrative privileges.

4. Administrative Privileges:

1. Modify /etc/sudoers file:

 Open the /etc/sudoers file using a text editor like vi: sudo vi /etc/sudoers.

 Navigate to the section labeled ## Same thing without a password.

 Add the following line to grant 'Louis' user sudo access without a password:

Louis ALL=(ALL) NOPASSWD: ALL

 Save and exit the file.

OR
2. Create a separate file in /etc/sudoers.d/ directory:

 Run the following command to add the access:

sudo echo "Louis ALL=(ALL) NOPASSWD:ALL" | sudo tee


/etc/sudoers.d/Louis

 This command uses echo to output the required configuration line and tee to
write it to a file named "Louis" in the /etc/sudoers.d/ directory.

After granting sudo access, Louis can switch to the root user by running:

sudo su - Louis

This command switches to the user "Louis" with elevated privileges, allowing administrative
tasks to be performed without repeatedly entering a password.

External Server Access:

Option 1: Manually edit the SSH configuration file:

30
sudo vi /etc/ssh/sshd_config

 Find the line PasswordAuthentication no and change it to PasswordAuthentication


yes.

 Save and exit the file.

Option 2: Using sed command to modify the SSH configuration file:

sudo sed -i
"/^[^#]*PasswordAuthentication[[:space:]]no/c\PasswordAuthenti
cation yes" /etc/ssh/sshd_config

 This command uses sed to replace the line containing PasswordAuthentication no


with PasswordAuthentication yes in the /etc/ssh/sshd_config file.

Restart SSH Service:

After modifying the configuration, restart the SSH service to apply the changes:

sudo systemctl restart sshd

or

sudo service sshd restart

Accessing the Server Externally:

1. Open a new terminal from your local machine or MobaXterm.

2. Access the server using Louis's credentials:

ssh Louis@server_ip

3. Enter Louis's password when prompted.

This will establish an SSH connection to the server using Louis's credentials, allowing external
access with password authentication.

5. Account Expiration:

sudo chage Louis

 Minimum password age [0]: 90

31
 Explanation: Specifies the minimum number of days that must pass before the
password can be changed. Here, we set it to 90 days.

 Maximum Password Age [99999]: 99999

 Explanation: Specifies the maximum number of days the password is valid.


Setting it to 99999 days means the password will never expire based on age.

 Last Password Change (YYYY-MM-DD) [2024-05-12]:

 Explanation: Indicates the last date the password was changed. By default, it
shows the current date. You can leave it as is or specify a different date if needed.

 Password Expiration Warning [7]: 90

 Explanation: Specifies the number of days before password expiration that a


warning message is displayed. Here, we set it to 90 days before expiration.

 Password Inactive [-1]: 30

 Explanation: Specifies the number of days after the password has expired before
the account is disabled. Setting it to -1 means the account will not be disabled
due to inactivity.

 Account Expiration Date (YYY-MM-DD) [-1]: 2928

 Explanation: Specifies the date when the account will expire. Setting it to -1
means the account will not expire based on a specific date. Here, we set it to
2928 days (8 years) from the current date.

Verification:

sudo chage -l Louis

Explanation: We use the chage command with the -l option to display the account aging
information for Louis, including the expiration date. This verifies that the expiration date has
been successfully set for Louis's account.

32
System Information:
System information commands in Linux are used to gather various details about the system,
including user information, file locations, command descriptions, disk usage, and hostname.

1. uname: Print system information.

 Example: uname -a (displays detailed system information).

2. users: Displays a compact list of users currently logged in to the system..

 Example: users.

3. who: Display who is logged in.

 Example: who (displays the list of users currently logged in).

4. w: Display who is logged in and what they are doing.

 Example: w (displays detailed information about logged-in users).

5. uptime: Display system uptime.

 Example: uptime (displays system uptime and load average).

6. free: Display amount of free and used memory in the system.

 Example: free -m (displays memory usage in megabytes).

7. df: Display disk space usage.

 Example: df (displays disk space usage).

 Example: df -h (displays disk space usage in human-readable format).

8. whoami: Command to display the current username.

 Example: whoami

9. id: Command to display user and group information for the current user.

 Example: id

10. whereis: Command to locate binary, source, and manual page files for a command.

 Example: whereis command

11. whatis: Command to display a one-line description of a command.

33
 Example: whatis command

12. du: Command to estimate file and directory space usage.

 Example: du -sh directory

13. hostname: Command to display the hostname of the system.

 Example: hostname

Process Management:
Process management in Linux involves monitoring, controlling, and interacting with running
processes on the system. It includes tasks such as viewing processes, terminating them,
adjusting their priorities, and monitoring system resource usage.

1. ps: Display information about processes.

 Example: ps (displays a list of processes running in the current terminal


session).
 Example: ps aux (displays a snapshot of all running processes, including those
not attached to the current terminal session).

2. top: Display dynamic real-time information about running processes.

 Example: top (displays dynamic information about CPU and memory usage).

3. kill: Terminate processes by PID (Process ID).

 Example: kill 1234 (terminates the process with PID 1234).

4. killall: Terminate processes by name.

 Example: killall firefox (terminates all processes with the name "firefox").

5. sar: Collects, reports, and saves system activity information such as CPU, memory,
disk, and network usage.

 Examples:

 sar -u (displays CPU utilization statistics).

 sar -r (displays memory utilization statistics).

 sar -d (displays disk I/O statistics).

34
Task: Deployment and Verification of Apache HTTP Server.
Install httpd and Verify Installation:

 Install the Apache HTTP server (httpd) on your system.


 Check that httpd has been successfully installed by verifying its presence.

Start the HTTP Service:

 Start the httpd service on your system to make the web server operational.

Check Service Status:

 Verify the status of the httpd service to ensure it is running correctly.

Access HTTP Server on the Browser:

 Open a web browser and access the default page served by the httpd server to confirm
that it is accessible.

Service Management Commands:


Service management commands in Linux are used to control and interact with system services.
These commands allow users to start, stop, restart, enable, disable, and manage services
running on the system.

Commands:

1. systemctl:

 Description: Control the systemd system and service manager.

 Usage:

 Start a service: sudo systemctl start service_name

 Stop a service: sudo systemctl stop service_name

 Restart a service: sudo systemctl restart service_name

 Enable a service to start on boot: sudo systemctl enable service_name

 Disable a service from starting on boot: sudo systemctl disable


service_name

 Check service status: sudo systemctl status service_name

35
 List all services: systemctl list-unit-files

2. service:

 Description: Manage system services.

 Usage:

 Start a service: sudo service service_name start

 Stop a service: sudo service service_name stop

 Restart a service: sudo service service_name restart

 Check service status: sudo service service_name status

Task Solution:
1. Install httpd and Verify Installation:

 Installation Command: sudo yum install httpd

 Verification Command: rpm -q httpd

 Expected Output: httpd-x.x.x-x.amzn2.x86_64

2. Start the HTTP Service:

 Start Command: sudo systemctl start httpd

 Note: This command starts the Apache HTTP server service.

3. Check Service Status:

 Status Command: sudo systemctl status httpd

 Expected Output: Active (running) status indicating that the httpd service is
operational.

4. Access HTTP Server on the Browser:

 Ensure that the required port (typically port 80) is open in the security group.

 Open a web browser and enter the public IP address or domain name of your
Amazon Linux instance.

36
 Expected Outcome: The default page served by the Apache HTTP server should
be accessible.

Question:

Networking:
1. ping: Send ICMP echo requests to a host.

 Example: ping google.com (sends ICMP echo requests to google.com).

2. ifconfig: Display or configure network interfaces.

 Example: ifconfig (displays information about all network interfaces).

3. netstat: Display network connections, routing tables, interface statistics, masquerade


connections, and multicast memberships.

 Example: netstat -tuln (displays a list of listening TCP and UDP ports).

 Example: netstat -tulpn (displays a list of listening TCP and UDP ports along
with the PID and program name of each listening process).

4. traceroute: Print the route packets take to network host.

 Example: traceroute google.com (displays the route packets take to reach


google.com).

Note: Whatis Command

Usage: When you forget the function of a command, use whatis followed by the command
name to quickly remind yourself of its purpose.

Example:

whatis ls

37
Output:

ls (1) - list directory contents

Benefits:

 Quickly reminds you of a command's purpose without needing to access detailed


manual pages.

 Saves time and enhances efficiency in command-line navigation.

 Handy tool for both beginners and experienced users to refresh their memory on
command functionalities.

Interview Question: What is your experience with Linux systems?

I have extensive experience with Linux systems, particularly in the areas of system
administration, server management, and open-source technologies. Here are some key aspects
of my experience:

Interview Question: What is your experience with Linux systems?

Answer:

I have extensive experience with Linux systems, particularly in managing and configuring
various distributions such as Ubuntu, CentOS, and Amazon Linux. Here’s an overview of my
key experiences:

1. Server Deployment and Management: I have created and managed Linux servers,
including the setup of Amazon Linux instances on AWS. This involved tasks like
launching instances, configuring security groups, and ensuring proper SSH access.

2. System Administration: I am proficient in managing user accounts, permissions, and


groups using commands like useradd, passwd, chage, groupadd, and usermod. I am
skilled in configuring and managing services using systemctl, service, and chkconfig.

3. File System Structure: I have a solid grasp of the Linux file system structure, including
directories like /etc for configuration files, /proc for system information, and /var for
logs. I am familiar with commands for navigating and managing the file system, such
as ls, cd, chmod, touch, and mkdir.

38
4. Process Management: I can efficiently manage system processes using commands like
ps, top, kill, killall and sar. These skills help in monitoring system performance and
managing resources effectively.

5. Package Management: I am experienced in installing, updating, and managing


software packages using tools like apt-get/apt for Debian-based systems and yum/dnf
for Red Hat-based systems. I can also download packages using wget.

6. Server Deployment: I have hands-on experience in deploying and managing web


servers. For example, I can install and configure Apache HTTP Server (httpd) on
Amazon Linux, start the service, verify its status, and ensure it is accessible via a web
browser.

7. Security and Permissions: I am knowledgeable about Linux file permissions and


ownership, using commands like chmod, chown, and chgrp to secure files and
directories. I also manage sudo access and user privileges for enhanced system security.

8. Networking and SSH: I am skilled in configuring SSH for secure remote access,
including setting up password authentication and managing SSH keys. I can also access
servers externally and manage network settings and firewalls.

My experience with Linux systems has equipped me with the necessary skills to manage,
configure, and troubleshoot various Linux environments effectively, ensuring smooth and
secure system operations

Other Useful Linux Commands:

Introduction: In addition to the basic and service management commands, there are several
other commands that are incredibly useful for system administration, monitoring, networking,
and file management.

1. cal:

 Description: Displays a calendar.

 Example: cal (displays the current month's calendar).

2. script:

 Description: Records a terminal session.

39
 Example: script session.log (starts recording the terminal session to a file
named session.log).

3. telnet:

 Description: Connects to another host using the TELNET protocol.

 Example: telnet hostname (connects to the specified hostname).

4. history:

 Description: Displays the command history.

 Example: history (lists all previously executed commands in the current


session).

5. *cat /etc/release:

 Description: Displays the contents of the release files to identify the Linux
distribution and version.

 Example: cat /etc/*release (displays detailed information about the installed


Linux distribution).

6. watch:

 Description: Executes a program periodically and shows output.

 Example: watch df -h (displays disk space usage every 2 seconds).

7. restart:

 Description: Typically used to restart a service or the system.

 Example: sudo systemctl restart httpd (restarts the Apache HTTP server
service).

8. reboot:

 Description: Reboots the system.

 Example: sudo reboot (reboots the system immediately).

9. tar:

 Description: Archives files.

40
 Examples:

 tar -cvf archive.tar directory/ (creates an archive named archive.tar


from the directory).

 tar -xvf archive.tar (extracts the contents of archive.tar).

10. zip:

 Description: Compresses files into a ZIP archive.

 Example: zip archive.zip file1 file2 (creates a ZIP archive containing file1 and
file2).

11. unzip:

 Description: Extracts files from a ZIP archive.

 Example: unzip archive.zip (extracts the contents of archive.zip).

These commands expand your toolkit for managing Linux systems, offering capabilities for
system monitoring, networking, file management, and automation.

41

You might also like