You are on page 1of 65

1

Linux as Operating System

What is OS: -
“OS provides interface between user and hardware.”

Parts of OS: -
OS divides into two parts.
1. Environment
2. Kernel

Environment GUI

vmlinuz file Kernel CLI


(source code) (Command
Line Interface)

Text Based
Hardwar
e

Kernel Functions: -

1. Device Compatibility (HCL (Hardware Compatibility List) file)


2. Device Management
3. Job Scheduling
4. Queue Management
5. Interrupts Handling
6. Memory Address Allocation

Interrupts Types: -

1. Software Based Interrupts


2. Hardware Based Interrupts
3. User Based Interrupts
2

INode (Memory) Address Allocation: - (Unix Family Kernel)

In Linux, Solaris and UNIX OS

 All Storage Devices are called Block Devices


 All I/O Devices are called Character Devices
 File System Organized file name or INode.
 INode number is in UNIX family OS.
 nfs, ext2, ext3 are file systems in Linux.

Crash Dump Files: -


“Those files whose inode addresses accidentally misplaced.”

In Windows OS: -
Scandisk utility is used to check the file system. This utility only
checks the lost file address (crash dump files) and fix it only and no
recovery is done.

In UNIX family (UNIX, Linux and Solaris) OS:-


FSCK (file system check) utility is used to check the file system. It first
checks the the file system for crash dump files and then recover the
lost addresses. Recovery is done on the behalf of the kernel.

Note: -
In Solaris, UNIX and Linux we can recover crash dump files, on the
other hand in Windows OS recovery is not done, it only fix the lost
memory address files.

Distribution Version and Kernel Numbering Schema:-

There is a specific numbering system for Linux kernels, kernel development,


and Red Hat’s kernel versions. Note that these numbers bear no relation to the
version number of Red Hat’s Linux distribution. If this were true, you’d be using
Red Hat Linux 2.4 instead of 9.0. Red Hat distribution version numbers are
assigned by Red Hat, Inc., whereas most of the Linux kernel version numbers are
assigned by Linus Torvalds and his legion of kernel developers.

To See the Date your Linux kernel was compiled:-


Use the uname command with its –v command-line option.

To See the version of your Linux kernel:-


Use the –r option with uname command.

Linux 9.0 – 2003


Kernel version: 2.4.20-8
3

 Represents the major version (segment) 2, major segment indicates major


developments.
 Represents the minor version (segment) 4, minor segment indicates minor
developments devices etc.
 Represents the patch level 20.
 Represents the final or beta version, if the number after – is even (8) then it is
final version and if the number after – is odd (9) then it is beta version.
 20-8 is also called revision number.
 Even minor numbers are considered “stable” and generally fit for use in
production environments, while odd minor numbers (such as the current
Linux 2.5 source tree) represent versions of the Linux kernel under
development and testing.
 You will only find stable versions of the Linux kernel.
4

Types of Shells: -

1. Bourne Shell (BSh)


2. Korne Shell (KSh)
3. C Shell (CSh)

Bourne Shell (BSh) & Korne Shell (KSh):-


BSh is used to perform administrative tasks for the system.

C Shell (CSh):-
CSh is used to develop c or java development tasks (development purposes).

Shell Features: -

1. Job Controlling
2. Command Line Editing
3. History File
4. File Name Completion
5. Alias

 Command Line Editing, History File, File Name Completion and Alias
are the features of Korne Shell (KSh) and Bourne Shell (BSh).

1. Job Controlling: -

 It is available in all three shells (BSh, KSh and CSh).


 Multiple commands are concatenate and executed a single
commandl
 # man ls | col -b | lbr, this command is the concatenation of three
commands.
 man ls, is help command.
 col is filtration purpose

2. Command Line Editing: -

 This feature provides the facility to edit the command with the help of
back arrow key.

3. History File: -

 All commands history is maintained.


 History File is permanent file.
 History File size depends upon the number of commands which are
stored.
5

 BY default, 1,000 commands can be stored in history files.


 History File is user dependent.
 We can increase or decrease the command stored size.

4. File Name Completion: -

 When we don’t know the complete name of the existing file or


directory then we type some initial characters of the name and press
tab key. After this auto file name will be completed.

5. Alias: -

 Frequently used commands can be alias.


 We can give alias to any command.

Alias Command: -

Syntax:
alias alias-name = “command”

Example:
alias psa = “ps -aux | more”

 Ps -aux | more is a task manager command

Shell Modes: -

Every shell is divided into two basic modes.

1. Privilege Mode (Administrative Mode)


2. Monitor Mode (User Mode)

 # sign means Privilege Mode. For example, [root@localhost root]#, in this


root shows the login name, localhost is the host name, and root is the
home directory or present working directory and # shows the privilege
Mode.

 $ sign means Monitor Mode. For example, [ali@localhost ali]$

Switch from One Shell to another Shell: -

# bsh
6

Exit from a Shell: -

# exit

 In Linux 6.0 bsh is also called bash


 If we write exit in bash, then it shut down the system

Logout Command: -

# logout
7

Mounting

 CD Access or CD mount
 Floppy Access or Floppy mount
 All storage devices are called block devices.
 All block devices are mounted.
 Mount means attach a file system or transfer file system
 /mnt/cdrom is called mount point

Mounting: -
“Mounting is a process through which file system is attached with block
devices.”

Mount Command: -

Syntax:
mount device-name mount-point

Example:

mount /dev/cdrom /mnt/cdrom

Mount Point: -
Mount point is the location where the data can be read or write.

Floppy: -

Mount /dev/fd0 /mnu/floppy

 a: in Windows, /dev/fd0 in Linux


 b: in Windows, /dev/fd1 in Linux

Unmount: -
In unmount, OS release the resources. For this purpose umount command is
used to release the resources occupied.

Umount Command: -

Syntax:
umount device-name mount-point

Example:
umount /dev/cdrom /mnt/cdrom

Eject: -
1. umount
2. eject
8

Eject command: -

Syntax:
eject

It performs both activities, first it umount then it ejects the CD.

Partition Mount: -

1. # fdisk -l
2. # cd /mnt
3. # mkdir windows
4. # mount /dev/hda3 /mnt/windows/
9

Basic Commands

 There are 20 to 22 basic commands in Linux

1. To See the Contents of the directory: -

# ls

 ls command uses colors to differentiate the files and directories


 white color indicates the text or regular files
 blue color indicates the directory
 green color indicates the executable files

2. To View the Hidden Files: -

# ls -a

 -a is flag, which means all files.


 If a file or directory name is started from dot (.) then it is a hidden file or
directory.

3. File/Directory detailed Information: -

# ls -l

4. Hidden Files/Directory Details: -

# ls -al

5. Help for Commands: -

# man ls

 man means manual (help)


 we can get any command help from this command, by using the name of
the command. i.e. # man mkdir
 type Q to exit from help.

6. Clear Screen: -

# clear
10

7. File Creation of Zero Size: -

# touch file-name

 By default, size is zero.


 Touch command is used for backup or log files.
 There is no concept of extensions in Linux

8. Make Directory: -

# mkdir directory-name

9. Change Directory: -

# cd directory-name

10. Close Directory (one step back): -

# cd ..
 In some commands space is not necessary.

Absolute Path & Relative Path: -

Path: /root/redhat

 To switch a directory, we can use relative path and absolute path.

Relative Path: -

# cd root
# cd redhat
# cd ..
# cd ..

Absolute Path: -

# cd /root/redhat
# cd / (direct switch)

11. Present Working Directory Path: -

# pwd
11

12. Copy Command: -

# cp source-path desti-path
# cp abc redhat/

13. Directory Copy: - flag(-r)

# cp -r redhat test

14. Delete a File: -

# rm abc

15. Delete a Directory: -

# rm -r redhat

16. Delete file(s) or Directory Forcefully: -

# rm -rf test // directory delete


# rm -f abc // file delete
# rm -f abcd 123 xyz // 3 files delete
# rm -f a* // delete file which starts with a
17. Move (cut & copy) command: -

# mkdir redhat
# touch abc
# mv abc redhat/

Note: -
If we want to move any directory then in this case no flag will be used.

18. cat command: -

We can create a file with cat command but the difference


between touch and cat command is that touch command is used to create
an empty file. On the other hand, cat command is used to create a file and
to insert the contents of the file immediately at command line.
12

# cat > filename


---------- ---------- ---------------
----------- -------------- ------------------
----------- -------------- ------------------

press (ctrl+d) to save and exit


press (ctrl+c) to forcefully terminate a file

Note: -
In text mode, ctrl+z is used to minimize the current file.

19. Read a File: -

cat command is also used to read the file.

# cat filename

20. To show the Minimize File: - (running process)

# jobs

21. Maximized (Restore) the Minimized File: -

# fg %1

“1” is the file ID or process ID.

22. cat property: - (copy + read)

# cat abc > 123

 If existing file then overwrite the contents.


 If not then make a file and copy the contents.

23. Append: - (and existing file)

# cat abc 123 > xyz // for backup purposes.

24. more command: -

Page wise file read.

# more filename // scroll up only


13

25. less command: -

Scroll down or scroll up for file read

# less filename

26. head command: -

Read any file’s top 10 lines.

# head filename
# head -15 filename // flag for first 15 lines

27. tail command: -

Read last 10 lines of the file.

# tail filename
# tail -15 smb.conf

28. | (concatenation): -

It is used to concatenation of the multiple commands.

# ls | less

29. locate command: -

This command is used to search a file or directory.

# locate smb.conf

It shows the path & details of the search file, in the complete system.
Search speed is very fast.

30. grep command: -

A particular string or word is finding and also a specific folder


etc.

# ls | grep passwd
14

page wise process’ information

# ps -aux | more

if I want to see the xinetd process, then

# ps -aux | grep xinetd

31. vi (editor):- (Joe, emacs, pico)

# vi filename

To write:-
 Press insert key to insert mode.
 Then after insertion write
 To exit first press escape key (Esc), to remove insert mode
 Then :wq! Where w is for write, q is for quit (with save)
 :q! is used to quit only (without save)
 pico package must be installed for vi
15

Directory Structure
root partition (/)

File extensions are not used in Linux.

1. bin:- (binary directory)

Different types of files used in Linux.

 Some files are initialized for users.


 Some files are initialized for OS.

User based executable files are stored in bin. During booting process OS
initialized a user bin files. i.e. ksh, bsh, csh. All shells are stored in bin.

/bin/csh
/bin/ksh

2. sbin:- (system binary directory):-

All executable files which is loaded for OS are stored in sbin directory
(during booting), i.e. fsck.

/sbin/fsck

3. dev:- (devices directory)

In OS all installed devices are in dev directory.

/dev/cdrom
/dev/hda1
/dev/fd0

4. home:-

All users’ accounts that we create, are stored in home directory. All
users’ home directories are stored in home directory.

5. lib:- (library directory)

lib is used for all executed files syntax verification. All executed files
information is stored in lib directory.
16

6. misc:- (miscellaneous directory)

Miscellaneous data (songs, movies, pictures etc.) are stored in misc


directory. Data which is not personal is stored in misc directory.

7. opt:- (option directory)

All uninstalled packages or software are stored in opt directory.

8. root:- (root directory)

Other than root, all accounts are stores in home directory. Root user’s
home directory is stored in root directory.

9. usr:-

All OS commands ( after boot executable files) are stored in bin and
sbin directories which are present in usr directory. All user commands are
stored in bin directory, and all administration commands are stored in sbin
directory.

10. boot:-

OS based booting files are stored in boot directory, these files are
initialized at boot time, i.e., grub, vmlinuz etc.

11. etc:-

OS administrative configuration files are stored in etc directory, i.e.,


DNS, web server, ftp etc. It is mostly used for administration purposes.

12. lost+found:-

All crash dump files are stored in lost+found. All partitions have their
own lost+found directory.

13. mnt:- (mount directory)

After attachment of file system with block devices all contents of


mounted files are stored in mnt directory.

14. proc:- (Process directory)

All active process’ information is stored in proc directory. It is


interact with kernel.
17

15. tmp:- (Temporary Directory)

OS all temporary files are stored in tmp directory, i.e., job scheduling
is a temporary file.

16. var:- (Variable Directory)

Log files, cache directory, spool directories are examples of variable


files. All variable files are stored in var directory.

Commonly (widely) used Directories:-

etc, mnt, home, var


18

Administration Track

1. User Administration
2. System Administration
3. Network Administration

1. User Administration:-

Account Types:

a. System Accounts
b. Custom Accounts

a). System Accounts:-

System account is such account which is created by OS itself, i.e. root


account. All the demons, services or processes are managed by system
account, i.e. web server, DNS. System account initialized, authenticated
these processes.

b). Custom Account:-

By using the root account, we can create a user accounts. These


accounts are also called regular accounts.

1. Commands to create a Custom Account

1. useradd
2. adduser

# useradd user-name

# useradd lab

By default, some configurations load. These configurations are


four types.

1. user id (uid)
2. user group (group)
3. create home directory (homedir)
4. shell assignment (shell)
19

1. User ID (uid):-

First uid is started from 500 for the custom account. The
uid reserved for the custom accounts range from 500-60,000. And uid
reserved for the system accounts range from 0-499.

uid = 500

2. User Group (group):-

By default the name of the user will by the name of the group.
When ever a new user is created, then the group of that user will be
also created with the name of the user.

group = lab

3. Create home directory (homedir):-

In the third step, home directory of the user will be created in


the default home directory (/home/lab). Home directory name will be
the name of the user.

HomeDir = /home/lab

4. Shell Assignment (shell):-

In the last step shell is assigned to the user. By default shell is


bash. Shells are stored in the bin directory.

shell = /bin/bash

So these four configurations are set by default:-

uid = 500
group = lab
HomeDir = /home/lab
shell = /bin/bash

2. To Check the user id (uid) and group command

# id user-name

# id lab

uid = 500(lab) gid=500(lab) groups=500(lab)


20

3. To change the user default Configuration

a. New Account
b. Existing Account

a). New Account:- (-u, -g, -d, -s)

Use the below flags with the useradd command to change the new user’s
default configurations.

Flag Description

-u To change the user id (uid) default configuration.


-g To change the user group (group) default configuration.
-d To change the home directory (homedir) default configuration.
-s To change the default shell of the new user

To change the default uid of the new user:-

# useradd -u 600 test

To change the default group of the new user:-

# useradd -g lab test

To change the default home directory of the new user:-

# useradd -d /home/lab/test test

To change the default shell of the new user:-

# useradd -s /bin/csh test

Single complete command to change all defaults:-

# useradd -u 600 -g lab -d /home/lab/test -s /bin/csh test

b). Existing User:- (usermod command)

To change the existing user configurations, we use usermod (user modify)


command. Flag description is as under:
21

Flag Description

-u To change the user id (uid) configuration.


-g To change the user group (group) configuration.
-d To change the home directory (homedir) configuration
logically.
-s To change the shell of the existing user
-m physically change the home directory of the existing user.

# usermod -d /home/test test

In this case home directory is logically moved, but physically


directory does not move.

If we want to physically move the directory, we will use the following


flag with the usermod command.

# usermod -d /home/test -m test

4. Delete the user

# userdel user-name

# userdel test

home directory does not delete but the user will be deleted.

To delete user’s home directory with the user:-

If we want to delete user’s home directory with the user, then we will use –r
flag with the userdel command.

# userdel -r test
22

User’s Account Information


Passwd File

In windows user account information is stored in the “sam” file. But in Linux
user account information is stored in the “passwd” file. Passwd file is present in
the /etc directory (/etc/passwd).

# more /etc/passwd (read file)

when this command execute, passwd file opens in read mode and shows the all
users’ account informations.

Login-name: x : uid : gid :: home-directory-path : shell

Where : is called field separator,


First column shows the login name of the user.
Second column (x) shows authentication, x means password is compulsory.
Third column shows the user id (uid) of the user.
Forth column shows the group id (gid) of the user.
Fifth column is ::, comments are written inside the :: .
Sixth column shows the home directory path.
Seventh column shows the user shell.

-c flag is used to write a comment against any user.

Giving Comment to the user:-

# usermod -c “Tech Dept” adnan

* if we do not want the password of any user, then edit the passwd file and delete the
x from the specified user.

Setting Password to any user

Passwd command is used to set a password to any user.

# passwd user-name

# passwd lab1

after entering new password, confirm password appears to validate the new
password.
23

Only root can use user-name with passwd command, users can’t use the user-
name.

Users’ Passwords are stored in


/etc/shadow file

Users’ passwords are stored in shadow file, which is stored in etc directory. All
passwords are in corrupted form.

# more /etc/shadow

in shadow file

!! blank password.
$1$ password assigned
* password cannot be set.
!!$1$ password is locked

Account/password Lock
(Temporary)

-l flag is used with passwd command, to lock any account or password.

Syntax:
# passwd -l user-name

Example:
# passwd -l lab1

 In /etc/shadow file !!$$ means password is lock.

Account/Password Unlock

-u flag is used with passwd command to unlock a user account/password.

# passwd -u lab

 If shadow is enabled, then all passwords stored in shadow file.


 If shadow is disabled, then all passwords stored in password file.
24

Creating a Group

groupadd command is used to create a new group.

Syntax:
# groupadd group-name

Example:
# groupadd finance
# groupadd tech

To assign a group to existing User:-

# usermod -g finance adnan

 A user can have a multiple groups at one time.


 A user can be a member of maximum 15 groups
 There are two types of groups, primary group and secondary group
 -g flag is used with usermod command for primary group.
 -G flag is used for secondary group.

Add a primary Group:-

# usermod -g acc adnan

Add a secondary Group:-

# usermod -G finance, tech adnan

Delete a Group

groupdel command is used to delete a group. But the restriction is that it in


not the primary group of any user. Only secondary group can be deleted.

Syntax:
# groupdel group-name

Delete a Group Member

To delete a member of a group, edit the /etc/group file, and delete the
member from the file.
25

File & Folder Level


Permissions

Types of Permissions:-
There are two types of permissions

1. Local Permissions
2. Network Permissions

1. Local Permissions:-
Within a system or standalone system, permissions applied are called
local permissions.

2. Network Permissions:-
Over the network, permissions applied on a system are called network
permissions, i.e., shared device permissions.

Local Permissions

Types of Permissions in Linux:-

1. Read ( r )
2. Write ( w )
3. Execute ( x )

Sequence of permissions is important. We can check the file properties to see


the permissions.

To see the Properties:-

# ls -l

First column of properties is the permissions of the file or directory. There


are 10 slots of the permission column. We divide these ten slots into 4 segments.

- --- --- ---


1 slot 3 slots 3 slots 3 slots

 First segment contains only the one slot (first slot only).
 Second segment contains three slots (next three slots).
 Third segment contains three slots (next three slots of remaining).
 Forth segment contains also three slots (last three slots).
26

1st Segment:-

 If the slot is “–“, then it is a file.


 If the slot is “d”, then it is a directory.
 If the slot is “l”, then it is a link file (shortcut).

2nd Segment:-

2nd segment shows the owner’s (file creator) permissions.

 rwx means read, write and execute (all permissions) permissions.


 _wx means only write and execute permissions.
 _ _ x means only execute permission.
 r _ x means only read and execute permissions.
 rw_ means only read and write permissions.
 _ _ _ means no permissions.

3rd Segment:-

3rd segment shows the owner’s primary group permissions.

 rwx means read, write and execute (all permissions) permissions.


 _wx means only write and execute permissions.
 _ _ x means only execute permission.
 r _ x means only read and execute permissions.
 rw_ means only read and write permissions.
 _ _ _ means no permissions.

4th Segment:-

4th segment shows the others permissions, other than owner’s primary group
permissions. Others are also called world users.

 rwx means read, write and execute (all permissions) permissions.


 _wx means only write and execute permissions.
 _ _ x means only execute permission.
 r _ x means only read and execute permissions.
 rw_ means only read and write permissions.
 _ _ _ means no permissions.

To Check the Permissions of a File/Directory:-

# ls -l file-name
# ls -l abc
27

To Change the Permissions:-

chmod command is used to change any file or directory permissions.

Methods of Change Permissions:-

1. Identifier Method
2. Number System Method

1. Identifier Method:-

Identifiers which are used are shown below:

 ‘u’ for Owner


 ‘g’ for group
 ‘o’ for others
 ‘a’ for all

There are three permissions read, write and execute are available in
Linux.

Actions:-

 Add permissions ‘+’


 Remove permissions ‘-‘

Syntax:

# chmod identifier action permission file/dir-name

Example:-

# chmod g+x abc

This will add a owner’s primary group permission execute on abc file.

Example To Add & Remove the Permissions:-

# chmod u-x, g-x, o+w abc

Problem:-

Give the read, write and execute permissions to the owner, give read
and write to primary group and give read permissions to the others.
28

Owner = rwx
Group = rw_
Others = r_ _

Solution:-

(1) # chmod u+rwx, g+rw, o+r abc


(2) #chmod a+r, u+wx, g+w abc

output:-

_rwxrw_r_ _

2. Number System Method:-

In number system following numbers are assigned to each permission.

 r=4
 w=2
 x=1

Full Access or Full Permission:-

4+2+1 = 7

 7 means full access (rwx) as 4+2+1=7


 rw_ is equivalent to 6, as 4+2=6
 r_ _ is equivalent to 4
 r_x is equivalent to 5, as 4+1
 _wx is equivalent to 3, as 2+1=3
 _ _ x is equivalent to 1
 0 means no permissions (access)

Example:-

Required Result: _rwx rw_ r_ _

# chmod 764 abc

Example:-

Present Permissions Status: _ rwx rw_ r_ _


Required Result: _ rw_ r_ _ r_x

#chmod 645 abc


29

Owner & Group


Permissions

-rw-rw—r-- root root abc


owner default-group file

Change Ownership:-

“chown” command is used to change the ownership.

Syntax:
# chown user-name file-name

Example:
#chown adnan abc

output: -rw-rw—r-- adnan root abc

# id adnan

Change Group:-

“chgrp” command is used to change the group.

Syntax:
# chgrp group-name file-name

Example:
# chgrp tech abc

Single Command:-

Syntax:
# chown user-name : group-name file-name

Example:
# chown adnan : tech abc

Special Permission:- (Sticky bit)

It is used on that directory or file on which everyone has full control. i.e. ,
tmp directory.
30

 Delete permission is not given. One user cannot delete other user’s files.
 1 is used for numeric value of sticky bit.
 Its symbol is “t”. For example, -rwxrwxrwt.

Add a Sticky bit:-

If we want to add a sticky bit on the data directory, then we will execute the
following command.

# chmod 1777 data

where “1” is to add a sticky bit.

Remove a Sticky Bit:-

# chmod 777 data


Or # chmod 0777 data

 Sticky bit is not applicable on owner of the file or directory.

Default Permissions

 In windows OS everyone has by default full control on a file or directory.


 In Linux by default permission on a file is 644 (- rw- r- - r- -).
 And by default permission on a directory is 755 (d rwx r-x r-x).
 Default permissions depend upon umask (user mask) value.
 Default umask is 022
 In the case of directory 777 – 022 = 755
 And in case of file 666 – 022 = 644
 Full access umask is 000.
 By default root has a umask 022
 And regular account’s umask is 002.
 027,022,002 have some common umask used in Linux.
 In case of directory we subtract the umask value from 777.
 And in the case of a file we subtract the umask value from 666.
 If the resultant value is less than 0, then this will be considered to 0

To see the Umask value:-

# umask

To Change the umask:-

# umask 002
31

Configuring NFS

How to setup NFS Server and How to mount and unmount


the Shared Directories from NFS client.
We will need 2 servers, one for NFS Server and the other as an NFS Client.
Create a Parent Directory for NFS Shares:
# sudo mkdir /exports
Create Subdirectories as NFS Shares:
# sudo mkdir /exports/backup
# sudo mkdir /exports/documents

Installing NFS Server Package:


# sudo apt install nfs-kernel-server
32

Verifying NFS Service Status:


# systemctl status nfs-kernel-server
Upon executing this command, you should observe an indication that the NFS service is
active.

Let's inspect the contents of the /etc/exports file, which serves as the configuration file for
NFS exports. Notably, lines commencing with the hash symbol (#) are comments and
hold no operational significance. In this instance, the file appears to be empty, indicating
that there are currently no specific NFS export configurations in place.
To navigate and examine the contents, use the following command:
# cat /etc/exports
33

To edit the NFS export configurations, we will employ the Nano text editor. Execute the
following command:
# sudo nano /etc/exports
This command opens the /etc/exports file in the Nano text editor, allowing you to add,
modify, or remove NFS export configurations.

Modifying /etc/exports for NFS Share Configurations:


To configure NFS shares, add two lines to the /etc/exports file. Each line should
commence with the full path to the directory intended for sharing, followed by the IP
address of the NFS client permitted to connect to the NFS Server and access the shared
directories. Alternatively, to make it accessible without restrictions, omit the IP address.
Within the parentheses, options are available, including "rw" for read-write access.
Adjust it to "ro" if you prefer read-only access, preventing changes to the content within
the shared directories. Additionally, consider using the "no_subtree_check" option to
disable the parent directory of the export from being part of the file handle for security
purposes.
To save and exit the file after making changes, follow these steps:
1. Press Ctrl + O to write the changes.
2. Press Enter to confirm.
3. Press Ctrl + X to exit Nano.
34

Now that we've configured NFS shares, it's imperative to restart the NFS Server for the
changes to take effect. Following that, we will inspect the status to ensure smooth
operation.
Restart the NFS Server:
# sudo systemctl restart nfs-kernel-server
Verify the NFS Server status:
# sudo systemctl status nfs-kernel-server
This ensures that the recent configurations are active and the NFS Server is running
seamlessly.
Next, navigate to the /exports directory and create two text files. Populate each file with
content, save the changes, and exit. This can be accomplished with the following
commands:
# cd /exports
# sudo nano backup/test1.txt
Enter the desired content, save the file (Ctrl + O, Enter, Ctrl + X), and repeat the process
for the second file.
35

test1.txt file has “hello” text inside it.

test2.txt file has “hy” text inside it.


36

Installing NFS Client Package:


# sudo yum install nfs-utils

Identifying NFS Server IP Address:


# ip addr show
37

To confirm the directories shared by the NFS Server, execute the following command:
# showmount --exports <NFS_Server_IP>
Replace <NFS_Server_IP> with the actual IP address of your NFS Server. This
command will provide a list of directories being shared by the server.

Creating Directory Structure for NFS Mounts:


To facilitate NFS mounts, we will organize a parent directory and subdirectories. Each
subdirectory will correspond to one of the shared directories from the NFS Server.
Execute the following commands:
# sudo mkdir /mnt/nfs
# sudo mkdir /mnt/nfs/backup
# sudo mkdir /mnt/nfs/documents
38

The /mnt directory is a system standard and may already exist on your file system,
eliminating the need to create it.
These directories are presently empty as no mounts have been initiated. They serve as the
designated mount points for the NFS shared directories.

Mounting NFS Shared Directory Locally:


# sudo mount <NFS_Server_IP>:/exports/backup /mnt/nfs/backup
Replace <NFS_Server_IP> with the actual IP address of your NFS Server. This
command mounts the specified directory, in this case, /exports/backup from the NFS
Server, under the local directory /mnt/nfs/backup.
To confirm the successful mount, utilize the command:
# df -h
Inspect the output for the entry corresponding to the NFS shared directory
(/mnt/nfs/backup). This verifies that the directory from the NFS Server is now accessible
locally.

Verifying Contents of NFS Mounted Directory:


To inspect the contents of an NFS mounted directory in detail, use the following
command:
39

# ls -l /mnt/nfs/backup
This command provides a comprehensive listing of files and subdirectories within the
/mnt/nfs/backup directory, presenting details such as permissions and modification time.
Upon execution, the output will showcase any existing files and subdirectories. Confirm
the presence of the test1.txt file, which was created as a test on the NFS Server. The
contents of this file confirm the successful functionality of NFS.

Unmounting the previously mounted NFS exports is a standard practice once the required
tasks are completed and access to the shared directories is no longer needed. To initiate
the unmounting process, please execute the following commands:
For the backup directory:
# sudo umount /mnt/nfs/backup
For the documents directory:
# sudo umount /mnt/nfs/documents
Upon successful execution of these commands, the specified NFS exports, namely the
backup and documents directories, will be unmounted.

Configuring Apache

How to Configure the Apache Web Server on an Ubuntu?

Introduction
Apache HTTP Server is a free and open-source web server that delivers web content through the
internet. It is commonly referred to as Apache and after development, it quickly became the most
40

popular HTTP client on the web. It’s widely thought that Apache gets its name from its
development history and process of improvement through applied patches and modules but that
was corrected back in 2000. It was revealed that the name originated from the respect of the
Native American tribe for its resiliency and durability.

Prerequisites
Before you begin exploring your Apache configurations,
you should have Apache installed on your server.

Apache on Ubuntu:
Open a terminal window and type the following commands:
$ sudo apt update
$ sudo apt install apache2

During the installation process, you may be prompted to confirm by typing 'Y' and pressing
Enter.

Start and Enable Apache:


After installation, start the Apache service and enable it to start on boot:
$ sudo systemctl start apache2
$ sudo systemctl enable apache2

Check Apache Status:


You can check the status of the Apache service to ensure that it's running without any issues:
$ sudo systemctl status apache2

If Apache is running, you should see an output indicating that the service is active and running.

Access Apache Default Page:


Open a web browser and enter your server's IP address or domain name in the address bar. If
Apache is installed successfully, you should see the default Apache page. http://your_server_ip

The Apache File Hierarchy


Apache keeps its main configuration files within the /etc/apache2 folder. Executing
the following command will list all of the files within this folder:

There are a number of plaintext files and some subdirectories within this directory. Here are some
useful locations to be familiar with:
 apache2.conf: This is the main configuration file for the server. Almost all
configuration can be done from within this file, although it is recommended to use
41

separate, designated files for simplicity. This file will configure defaults and be the
central point of access for the server to read configuration details.
 ports.conf: This file is used to specify the ports that virtual hosts should listen
on. Be sure to check that this file is correct if you are configuring SSL.
 sites-available/ and sites-enabled/: The sites-
available directory contains virtual host file configurations. Configurations
within this folder will establish which content gets served for which requests. This is
enabled through linking to the sites-enabled directory, which stores activated
virtual host configuration files. When Apache starts or reloads, it reads the
configuration files and links from within the sites-enabled directory as it
compiles a full configuration.
 conf-available/ and conf-enabled/: These directories house configuration
fragments that are unattached to the virtual host configurations files.
 mods-enabled/ and mods-available/: These directories define modules that
can be optionally loaded. The directories contain two components: files ending
in .load, which contain fragments that load particular modules, and files ending
in .conf, which store the configurations of these modules.
Apache configuration does not take place in a single monolithic file, but instead happens through
a modular design where new files can be added and modified as needed.

Exploring the Apache2.conf File


The main configuration details for your Apache server are held in
the /etc/apache2/apache2.conf file. This file is divided into three main sections:

 Configuration for the global Apache server process


 Configuration for the default server
 Configuration of virtual hosts.

Open this file with your preferred text editor. The following example uses nano:

In Ubuntu and Debian, this file is used to configure global definitions. The configuration of the
default server and virtual hosts are handled by using the Include directive.
The Include directive allows Apache to read other configuration files into the current file at the
location that the statement appears. The result is that Apache dynamically generates an
overarching configuration file on startup.
Found within this file are a number of different Include and IncludeOptional statements.
These directives load module definitions, the ports.conf document, the specific configuration
files in the conf-enabled/ directory, and the virtual host definitions in the sites-
enabled/ directory:
42

Global Configurations
There are some options you may want to modify in the Global Configuration:

Timeout
By default, this parameter is set to 300. This means that the server has a maximum of 300
seconds to fulfill each request. This parameter can safely be dropped to something
between 30 and 60 seconds.

KeepAlive
This option, if set to On, will allow each connection to remain open to handle multiple requests
from the same client. If this is set to Off, each request will have to establish a new connection,
which can result in significant overhead depending on your setup and traffic situation.

MaxKee AliveRequests
This controls how many separate requests each connection will handle before dying. Keeping this
number high will allow Apache to serve content to each client more effectively. The default
setting is set to 100. Setting this value to 0 will allow Apache to serve an unlimited amount of
requests for each connection.

KeepAliveTimeout
This setting specifies how long to wait for the next request after finishing the last one. If the
timeout threshold is reached, then the connection will die. This means that the next time content
is requested, the server will establish a new connection to handle the request for the content that
makes up the page the client is visiting. The default is set to 5.
After examining the contents of this configuration file, you can close out of it by
pressing CTRL+X.
43

Virtual Host File


The default virtual host declaration can be found in a file called 000-default.conf within
the sites-available/ directory. You can learn about the general format of a virtual host file
by examining this file.

Open the file with the following command:

The default virtual host is configured to handle any request on port 80, the standard HTTP port.
This is defined in the declaration header where it says *:80, meaning port 80 on any interface.
However, this does not mean that it will necessarily handle each request to the server on this port.
Apache uses the most specific virtual host definition that matches the request. If there was a more
specific definition, it could supersede this definition. After examining the file, you can close out
of it by pressing CTRL+X.

Virtual Host Configuration Options


The following options are set within the virtual host definition outside of any other lower level
sub-declaration. They apply to the whole virtual host. To start, open up
the security.conf file within the conf-available/ directory:

This file contains the Server Signature directive, which allows you to specify a contact
email that should be used when there are server problems. You can change the default option
44

from On to EMail to reveal the server admin email address. Make sure you are willing to receive
the mail if you adjust this setting:

Exit the file by pressingCTRL+X. After editing a configuration file, a prompt will ask you to
confirm your changes. Press Y to save the changes to your file or press N to discard them.
Within your virtual host file, you can add a ServerName directive that specifies the domain
name or IP address that this request should handle. This is the option that would add specificity to
the virtual host, allowing it to override the default definition if it matches
the ServerName value.
Run the following command to open your virtual host file, making sure to replace
the your_domain variable with your actual domain name:

Append your_domain to the ServerName directive:

Likewise, you can also make the virtual host apply to more than one name by using
the ServerAlias directive. This provides alternate paths to get to the same content. A good
use case for this is adding the same domain, preceded by www:
45

The DocumentRoot directive specifies where the content that is requested for this virtual host
will be located. On Ubuntu, the default virtual host is set up to serve content out of
the /var/www/ directory:

Directory Definitions
Within the virtual host definition, there are definitions for how the server handles different
directories within the file system. Apache will apply all of these directions in order from shortest
to longest, so there is again a chance to override previous options.
Open the apache2.conf file with this command:
46

The first directory definition applies rules for the /, or root, directory. This will provide the
baseline configuration for your virtual host, as it applies to all files served on the file system.
Notice the directory configuration options, along with some helpful comments, contained within
this file. This default configuration denies access to all content unless specified otherwise in
subsequent directory definitions.
The Require directive can restrict or open access to different resources within your server.
The AllowOverride directive is used to decide whether an .htaccess file can override
settings if it is placed in the content directory. This is not allowed by default, but can be useful to
enable in a variety of circumstances. After examining the contents of this file, you can close out
of it by pressing CTRL+X.

Alias and ScriptAIias Statements


Directory definitions are sometimes preceded by Alias or ScriptAlias directives. Open
your virtual host configuration file with this command and replace the your_domain variable
with your domain name:

The Alias directive maps a URL path to a directory path. For example, in a virtual host that
handles requests to your_domain the following would allow access to content
47

within /usr/local/apache/content/ when navigating


to your_domain.com/content/:

The ScriptAlias directive operates in the same way, but is used to define directories that will
have executable components in them:

Remember to define the directory with access privileges as discussed in the previous section.
After completing your edits on the file, exit the file by pressing CTRL+X. If you made any
changes to this file, press Y to save the changes to your file or press N to leave the file as it was
before any changes to the configuration.

Enabling Sites and Modules


Once you have a virtual host file that meets your requirements, you can use the tools included
with Apache to transition it into live websites. To create a symbolic link in the sites-
enabled directory to an existing file in the sites-available directory, issue the following
command. Make sure to replace your_domain with the name of your own virtual host site
configuration file:

After enabling a site, issue the following command to tell Apache to reload its configuration files,
allowing the change to propagate:
48

There is also a companion command for disabling a virtual host. It operates by removing the
symbolic link from the sites-enabled directory. For example, with your virtual host site
enabled, you can disable the default 000-default site:

Modules can be enabled or disabled by using the a2enmod and a2dismod commands
respectively. They work in the same way as the a2ensite and a2dissite versions of these
commands. For example, to enable the info module, you can use the following command:

Remember to restart Apache after modifying configuration files and enabling or disabling
modules.

Conclusion
Apache is versatile and very modular, so configuration needs will be different depending on your
setup. After reviewing some general use cases above, you should have a good understanding of
what the main configuration files are used for and how they interact with each other. If you need
to know about specific configuration options, the provided files are well commented and Apache
provides excellent documentation. Hopefully, the configuration files will not be as intimidating
now and you’ll feel more comfortable experimenting and modifying to suit your needs.

Source: Documentation: Apache HTTP Server - The Apache HTTP Server Project

Configuring Samba

How to Install and Configure Samba on Ubuntu


Introduction
Samba is an open-source utility that enables file sharing between machines running on a
single network. It enables Linux machines to share files with machines running different
operating systems, such as Windows.

Most Linux package managers have Samba in their default repository. To configure
Samba on Ubuntu, follow the steps below:

Step 1: Install Samba


1. Start by updating the package registry:
49

Command: $ sudo apt update

2. Next, use apt to install Samba. Include the -y argument to auto-approve any queries
during the installation:
Command: $ sudo apt install samba -y

3. Verify the installation with:


Command: $ whereis samba

The output prints the directory containing Samba. Another method of verifying the
installation is by checking the Samba version:
Command: $ samba -v

The output shows that the system installed Samba version 4.16.4.

4. Lastly, confirm that Samba is running with:


Command: $ systemctl status smbd
50

The output shows that the smbd service is enabled and running.

Step 2: Create a Shared Directory


1. To share files with Samba, create a directory containing files for sharing. Use mkdir -p
to create the directory under /home:
For example, make a directory called sharing with:
Command: $ sudo mkdir -p /home/sharing

2. Use Is to verify the outcome.


Command: $ ls

Step 3: Configure Samba's Global Options


Configure Samba by editing the smb.conffile located in /etc/samba/smb.conf.
Access the file with Vim:
Command: $ sudo vim /etc/samba/smb.conf
Next, scroll down to the Global Settings section. Use this section to configure the Samba
server's behavior, name, role, and network interfaces.

Note: Certain settings in the smb.conffile are marked as comments. To enable and tweak
those settings, uncomment them.
51

The key parameters to consider are in the following subsections:


Browsing/identification
• The workgroup parameter enables file sharing between a group of computers over a
local area network. Ensure the workgroup settings correspond to the ones on Windows.
• The server string setting identifies the Samba server. In our example, the server is
named samba_server.

Note: To set the workgroup settings on Windows 10, open the Control Panel and access
the System and Security settings. The workgroup parameter is under the System section.

To configure the identification settings, uncomment the workgroup and server string
parameters and add these values:
workgroup = WORKGROUP
server string = samba_server

Networking
Use the Networking subsection to configure network interfaces that Samba binds to.
Networking contains two parameters:
• The first parameter, interfaces, sets the network interface for Samba to bind to.
• The second parameter, bind interfaces only, ensures that Samba only binds to the
interfaces listed in the file. The parameter should always be set to yes.

To set the interfaces parameter, first check the available interfaces with the ip command:
Command: $ ip link
52

The example output indicates Samba binds to two interfaces: Io, the loopback interface,
and enpOs3, the network interface.

For example, in this case, the settings are:


interfaces = lo enp0s3
bind interfaces only = yes
Note: The network interfaces Samba binds to may differ from one machine to another.

Debugging
The Debugging subsection has four parameters. Set them as follows:
log file = /var/log/samba/log.%m
max log size = 1000
logging = file
panic action = /usr/share/samba/panic-action %d

Authentication, Domain, and Misc


The most significant Authentication parameter is server role. This parameter determines
the server type for Samba.
1. Set Samba as a standalone server:
server role = standalone server
53

The following is an extensive list of other authentication settings:

obey pam restrictions = yes


unix password sync = yes
passwd program = /usr/bin/passwd
passwd chat = *Enter\snew\s*\spassword:* %n\n *Retype\snew\s*\spassword:* %n\n
*password\supdated\ssuccessfully* .
pam password change = yes
map to guest = bad user

2. Do not change any settings in the Domain subsection, but scroll down to Misc and set
the following:
usershare allow guests = yes
54

Keep all other Global Settings unchanged.

3. Save and exit the file and run the Samba utility testparm to check for syntax errors:
Command: $ testparm

The output shows the Loaded services file 0K message, which signifies no syntax errors.
With Global Settings configured, the Samba server is ready to use.

Still, not configuring the users and the directory limits the Samba functionality.

Ste 4: Set Up a User Account


1. To create a user account, set a username and password with:
Command: $ sudo smbpasswd -a username

Note that the username should belong to a system user. For instance, in this example, the
system account on the Ubuntu system is saraz. Hence, the username is the same:

Command: $ sudo smbpasswd -a saraz

2. To add a new user to Samba and the system, use adduser:


Command: $ sudo adduser username
For instance, add new_userto the system with:
Command: $ sudo adduser new_user
55

3. After entering and confirming the system password for new_user, create a new Samba
user with:
Command: $ sudo smbpasswd -a new_user

Next, both users need to have read, write and execute access to the sharing directory.
However, saraz has these permissions by default. On the other hand, new_userdoes not.

4. To grant read, write, and execute permissions to the sharing directory, run setfacl:
Command: $ sudo setfacl -R -m "u:new_user:rwx" /home/sharing
The command doesn't produce any output.

Step 5: Configure Samba Share Directory Settings


1 . Access the configuration file once again to add the previously made sharing directory.
Go to the end of the file and add:
[sharing]
comment = Samba share directory
path = /home/sharing
read only = no
writable = yes
browseable = yes
guest ok = no
valid users = @saraz @new_user

Each line grants specific permissions to access the directory. For instance:
 [sharing}. Represents the directory name. This is the directory location Windows users
see.
 comment. Serves as a shared directory description.
 path. This parameter specifies the shared directory location. The example uses a
directory in /home, but users can also place the shared files under /samba.
 read only. This parameter allows users to modify the directory and add or change files
when set to no.
 writeable. Grants read and write access when set to yes.
 browsable. This parameter allows other machines in the network to find the Samba
server and Samba share when set to yes. Otherwise, users must know the exact Samba
server name and type in the path to access the shared directory.
56

 guest 0k. When set to no, this parameter disables guest access. Users need to enter a
username and password to access the shared directory.
 valid users. Only the users mentioned have access to the Samba share.

2. Save the changes and exit the file.


3. Rerun testparm:

The output confirms that the Samba is adequately configured. For a more verbose output,
hit enter:

Step 6: Update the Firewall Rules


Command: $ sudo ufw allow samba

Step 7: Connect to the Shared Directory


1. Before connecting to the Samba server, restart the services with:
Command: $ sudo systemctl restart smbd
The command prints no output.
2. To connect to the shared directory via GUI, access the default file manager and choose
the Other Locations option:
57

3. Type the following into the Enter server address... box and select Connect:
Command: $ smb://ip-address/sharing
58

5. This adds the sharing directory to the Windows shares location:

Comparative analysis of OS

Comparison Between Windows and Linux

Windows:

Important Attributes:

User Interface: Graphical User Interface (GUI) with the Start menu.
Compatibility: Extensive compatibility with a wide range of software and hardware.
Market Share: Dominates the desktop environment.

Key Features:

DirectX: Primary platform for gaming due to DirectX support.


Active Directory: Powerful network management through Active Directory.
User-friendly: Generally user-friendly, especially for beginners.

Pros:
Compatibility: Vast compatibility with software and hardware.
59

Software Availability: Abundance of software applications.


Gaming: Preferred platform for gaming.

Cons:

Cost: Windows licenses typically come at a cost.


Security: Historically more susceptible to malware.

Linux:

Important Attributes:

Open Source: Linux is opensource, allowing users to modify and distribute their
versions.
Diversity: Various distributions (distros) catering to different needs.
Key Features:
Security: Known for robust security features.
Stability: Generally stable and reliable, with long uptimes.
Customization: High degree of customization and flexibility.

Pros:

Open Source: Free and opensource.


Security: Strong security features.
Stability: Reliable performance and uptime.

Cons:

Compatibility: Some software may not be available for Linux.


Learning Curve: Can have a steeper learning curve, especially for beginners.

Comparison:
Windows vs. Linux:
1. Cost:
Windows: Typically involves licensing costs.
Linux: Generally free and opensource.

2. User Interface:
Windows: GUI driven with a familiar desktop environment.
Linux: Diverse, with options for GUI and command line interfaces.

3. Software Availability:
Windows: Abundance of commercial software.
Linux: Growing availability; some proprietary software may be lacking.

4. Security:
60

Windows: Historically more targeted, but regular updates improve security.


Linux: Known for robust security; fewer malware threats.

5. Customization:
Windows: Limited compared to Linux.
Linux: Highly customizable, allowing users to tailor the system to their needs.

6. System Resources:
Windows: Generally, requires more system resources.
Linux: Can run on older or less powerful hardware.

7. Usage:
Windows: Dominant in desktop environments.
Linux: Widely used in servers, embedded systems, and increasingly on desktops.

Ultimately, the choice between Windows and Linux depends on specific requirements,
preferences, and use cases. Windows is often preferred for its user-friendly interface and
extensive software support, while Linux excels in customization, security, and resource
efficiency.

Configuring DHCP
Configuring DHCP Server on ubuntu
DHCP(dynamic host configuration protocol) server is used to assign dynamic IP
addresses to other machines in the network.
We can assign ips in 2 different ways, either manually or through DHCP. DHCP
server is very useful in large networks where a lot of machines are there. So, it assigns
unique IP addresses to every machine.
Update the repositories by using this command
# sudo apt update
This command should update repositories
61

# sudo apt upgrade


This should update your system

To install the server, we would need the package which is called isc-dhcp-server.
To install this package type:
# sudo apt install isc-dhcp-server
This should install the server on your system.

The enxt step is to navigate to directory where configuration files are present.
62

Here we will create our own configuration file, before that we will create a backup of the
default file so we can restore it incase of a mistake.
# sudo cp dhcpd.conf dhcpd.conf.backup
Now let’s create a new configuration file
# sudo touch dhcpd.conf

In order to edit the file


# sudo nano dhcpd.conf
This should open the terminal editor which you can use to edit the file.
63

Press ctrl+s to save and ctrl+x to exit.


Our next step is to assign the DHCP server on a network interface that it will be running
on.
Open the isc-dhcp-server file and you will see the ipv4 interfaces, currently empty.

#ip addr
And you should see the list of all network interfaces which are available.
64

The status you will see that it fails, there are usually two reasons, the firewall issue and
the network interface does not have an ip of itself.
We need to allow port 67 on the system
# ufw allow 67/udp
#ufw enable
65

You might also like