DevOps Linux
DevOps Linux
What is DevOps?
For any software development, release and maintenance, there are two groups of engineers will
work in the company.
1) Development Group
1)Development Group:
The people who are involved in below phases of SDLC are considered as Development Group.
1. planning
2. coding
3. build
4. Testing
2)Operations Group:
The people who are involved in below phases of SDLC are considered as Operations Group.
1) Release
2) Deploy
3) Operate
4) Maintenance
Release Engineers
Configuration Engineer
System Admin
Database Admin
Network Admin etc
To understand this new DevOps culture, we have to aware already existing SDLC Models.
SDLC
Software Development Life Cycle
SDLC is a process followed for a software project, within a software organization. It consists of a
detailed plan describing how to develop, maintain, replace and alter or enhance specific software.
In simple term we can say SDLC is a process which contains all the phases from planning to
maintenance of software Development.
1) Waterfall Model
2) Prototype Model
3) Incremental/Iterative Model
4) Spiral Model
5) RAD Model
6) Big-Bang Model
7) Fish Model
8) V Model
9) Agile Model
In this model, each phase must be completed before the next phase can begin and there is no
overlapping of phases.
i.e. all phases will be performed one by one just like flowing of water fall downwards.
1. It is very rigid model bcz it won't accept requirement changes in the middle.
2. Client satisfaction is very low because most of the times client will add new requirements in
the middle, which won't be supported.
3. Total project development time is more because testing should be done after complementing
development only.
4. The cost of bug fixing is very high because we cannot identify bugs in the early stages of life
cycle.
5. Not suitable if the requirements keep on changing.
6. Not suitable for large projects.
2) Agile Model:
This is the most frequently used and hot cake model for software development. Agile Model is divided
into several sub models:
Among all these models Scrum model is the most popular and frequently used model.
Scrum Model:
Water-fall vs Scrum:
1) In water fall model, before starting next phase, the previous phase should be completed. It is very
rigid model and won't accept requirement changes in the middle.
2) But scrum model is not linear sequential model. It is iterative model. Total software will be
developed increment by increment and each increment is called a sprint. Sprint is a
deliverable/shippable product in scrum model.
Points to Remember:
1. Scrum is an agile model that allows us focus on delivering highest quality software in shortest
time.
2. In this model software development follows increment by increment
3. Each increment will take one to 3 weeks duration.
4. 7 to 9 members are responsible in every sprint.
1. The chances of project failure are very high if individuals are not committed or cooperative.
2. Adapting scrum model for large teams is very big challenge
3. Must require experienced and efficient team members
4. If any team member leaves in the middle of project, it can have a huge negative impact on the
project.
Similarities:
1. Both are software development methodologies. Agile is there in the market for the last 20
years, but DevOps is recent methodology.
2. Both models concentrating on rapid development of software project.
Differences:
1. The differences between these models will starts after development of the project. Agile
methodology always talks about software development, testing and deployment. Once
deployment completed agile methodology has no role. But DevOps model will continue after
deployment also and it is also responsible for operations and monitoring.
2. In Agile Model, separate people are responsible for developing, testing, and deploying the
software. But, in DevOps, the DevOps engineer is responsible for everything; development to
operations, and operations to development.
3. Agile model won't force us to use automation tools. But DevOps model is completely based on
automation.
4. Agile model always giving highest priority for speed, whereas DevOps giving priority for both
speed and automation.
5. In Agile, client is responsible to give the feedback for the sprint. But in DevOps, immediate
feedback is available from the monitoring tools.
Summary:
Implementation Of DevOps:
2. Establish clear goals and metrics: Define the goals and objectives of your DevOps initiative.
3. Automate processes: Automation is a fundamental aspect of DevOps. Automate repetitive tasks,
such as building, testing, and deploying software, to increase efficiency and reduce errors. Use
tools like continuous integration/continuous delivery (CI/CD) pipelines to automate the software
delivery process.
4. Embrace infrastructure as code (IAC): Infrastructure as code allows you to manage and provision
infrastructure resources programmatically. Use tools like Terraform or CloudFormation to define
and manage your infrastructure, making it more reliable, reproducible, and scalable.
5. Adopt continuous integration and continuous delivery: Implement continuous integration (CI) to
regularly merge code changes into a shared repository and run automated tests. Continuously
deliver (CD) your applications by automating the deployment process, allowing for faster and
more frequent releases.
6. Implement monitoring and feedback loops: Monitor the performance and health of your
applications and infrastructure in real-time. Use monitoring tools and establish feedback loops to
gather insights, identify issues, and make data-driven decisions for continuous improvement.
Tools And Technologies need to learn:
1. Linux
2. Cloud (AWS)
3. IAC (Terraform)
4. Version Control System (GIT and GITHUB)
5. Configuration Management Tool (Ansible)
6. Containerization (docker)
7. Build Tool (Maven)
8. CI/CD (Jenkin)
Linux/Unix
Prerequisite to for this course:
Before we start the Linux Operating System, we will look some basic concept related to Computer
Science.
What is a computer?
A computer is a device that accepts information (in the form of digitalized data) and
manipulates it for some result based on a program, software, or sequence of
instructions on how the data is to be processed.
It has mainly two components:
1] Software
2] Hardware
1] Software:
Software is collection of specialized programs which takes user input, process
algorithm on it and provide desired output to end user.
Types of software:
Application software.
Operating systems or system software.
Firmware.
Application software:
Application software is nothing but a software which will full fill business
requirement or end users need.
Ex: Zoom, MS-word, notepad, google chrome, VLC media player.
Operating system:
2] Hardware:
Hardware refers to the external and internal devices and equipment that
enable you to perform major functions such as input, output, storage,
communication, processing, and more.
Ex: Keyboard, Mouse, CPU, Printer.
RAM:
ROM stands for read-only memory. It is a chip containing data installed by the
manufacturer that is not typically replaced or upgraded. It stores the BIOS.
ROM is non-volatile memory, which means it does not need power to keep the data
inside it.
Hard Disk:
The hard drive (sometimes called the hard disk) is the main storage device in
your computer.
Like RAM, it can be added to and changed, and like ROM it is non-volatile, but it
is slow.
You can store files and folder here.
operating system is also stored on the hard drive.
BIOS:
Booting:
Booting is basically the process of starting the computer. When the CPU is first switched on it
has nothing inside the Memory. In order to start the computer, load the Operating System into the
Main Memory and then Computer is ready to take commands from the User.
There are 6 major reasons one should learn Linux operation system.
Most of the infrastructure that powers the internet, including routers and
servers, is based on Linux.
Most of the OS for handheld devices are having Linux based architecture.
If you want to learn more about how the software that drives your system
works, Linux is a good choice.
The source code to the kernel and other utilities is available for anyone to
look at.
https://github.com/torvalds/linux
The biggest reason is that the tools you need to build programs, such as
editors, compilers, debuggers, IDEs, and interpreters either come with Linux
distros for free or can be downloaded through a package manager.
To learn technologies like Cloud Computing, GIT, Containerization Linux knowledge is must.
What is UNIX?
Flavours of UNIX
Components of UNIX
Online Terminal Demo with some basic commands
What is UNIX?
It is an operating system, by using that, users/applications can communicate with hard ware
components.
It was developed/created in 1960s.
With lot of extensions and improvements to base version, several flavours introduced by
organization/companies (flavours like Red hat Linux, ubuntu, CentOS etc)
Features of UNIX:
As UNIX is open source, multiple flavours are available with lot of extensions and
Improvements.
Ubuntu
RedHat
Centos
Fedora
Slackware
open salaries
Sues Linux Enterprise server (SLES)
Open Sues
All these flavours have lot of similarity. Hence if we are perfect with one flavour, we can work on any
other flavour very easily.
Features of Linux
Multiuser Capability:
In Multiuser system same computer resources such as Hard disk, memory is accessible to many
user’s
Multitasking Capability:
It is capable of carrying out more than one job at the same time.
Communication:
The communication may be within the network of a single main computer, or between two or
more such computer networks. Users can easily exchange mail, data, programs through such
networks.
Distance poses no barrier to passing information.
Data gets share with in fraction of second, doesn’t matter receiver is 2 feet away or thousand
miles.
Security:
Portability
portability means, Linux OS get installed and work fine on each and every device irrespective
of their built-in hardware.
Components of Linux
Hardware:
Hardware is the physical components of a computer, such as the motherboard, processor, memory,
storage drives, and other devices. It is the hardware that hosts and supports software or programs that
provide instructions for the computer to complete its tasks. Hardware can also include external
input/output devices such as keyboards, mice, monitors, printers, and speakers.
Kernal:
1. It is the core component of UNIX operating system.
2. It is responsible to execute our commands.
3. It is responsible to interact with hardware components.
4. Memory allocation and processor allocation will take care by kernel
Shell:
Application:
Application program, software designed to handle specific tasks for users. Such software directs the
computer to execute commands given by the user and may be said to include any program that
processes data for a user.
1) Normal or Ordinary files: These files contain data. It can be either text files (like abc.txt) OR binary
files (like images, videos etc).
2) Directory Files: These files represent directories. In windows, we can use folder terminology where
as in Linux we can use directory terminology. Directory can contain files and sub directories.
3) Device Files: In Linux, every device is represented as a file. By using this file, we can communicate
with that device.
Note: c, b and s are representing system files and mostly used by super user (also known as root user
or admin user)
2) $ cd .
3) $ cd ..
If we are not passing any argument, then changes to user home directory.
5) $ cd ~
6) $ cd - -
1. bin Directory: bin means binary. This directory contains all binary executables related to our
a. linux commands and those used by both normal user and root user.
2. sbin Directory:
a. sbin means systembin. It contains all binary executables related to super user OR root
b. commands.
c. Eg: Disk partitioning, network management etc.
3. boot:
a. This directory contains the files which are required to boot Linux os.
b. Eg. GRUB, kernal
4. dev Directory:
a. dev means device.
b. In Linux, everything is treated as a file including devices also.
c. i.e every device is represented as a file. By using these files, we can communicate with
the
d. devices. All device related files will be stored inside dev directory.
e. Eg.
i. tty --> Terminal related File
ii. fd -->Floppy Drive related File
iii. hd -->Hard Disk related File
5. etc Directory: (Edit text configuration)
a. This directory contains all system configuration files. These configurations can be used
to
b. customize behaviour of Linux os.
c. All user’s information available in /etc/passwd file.
d. All groups information available in /etc/group file.
e. Hosts information (ip address and dns names) available in /etc/hosts file.
6. tmp Directory:
a. tmp means temporary. It contains all temporary files created in the current session.
b. If any file is required only for the current session, then create that file inside tmp
directory.
c. These files will be deleted automatically at the time of system shutdown.
d. If any file which is required permanently, then it is not recommended to create inside
tmp directory
7. home:
i. As linux is multi user operating system, for every user a separate directory will
be created to hold his specific data like videos, images, documents etc.
ii. All these user directories will be stored inside home directory.
8. lib Directory:
i. lib means library. It contains Linux os libraries which are required by our
commands and applications.
9. media Directory:
i. The files of automatic mounting will be placed inside media directory.
10. mnt Directory:
i. mnt means mounting.
ii. We have to attach external file system files from Pen drive, CD, external hard
disk etc to the Linux File System. Then only we can use those external files. This
attachment process is called mounting.
iii. In the old operating systems, we have to perform mounting manually. But in
recent operating systems, mounting is performing automatically and we are
not required to perform manually.
iv. The files of manual mounting will be placed inside mnt directory.
11. opt:
i. opt means optional.
ii. This directory contains all 3rd party software installation files.
iii. Eg: If we are installing any software explicitly like google chrome, then the
corresponding installation files will be stored inside opt directory.
12. proc Directory:
i. proc means processes.
ii. In Linux, multiple processes are running simultaneously.
iii. For every process a unique id will be there, which is also known as PID (Process
ID).
iv. The data related to current running processes will be stored inside proc
directory. For every process a separate directory will be created inside proc to
maintain that data.
v. The name of this directory is same as PID.
13. root Directory: It is the home directory of super user.
14. run: It keeps run time data.
i. It means whenever we are running an application, those application needs
some dependency or libraries or data that data resides here and once that
application get closed its run time data will also get erased.
15. srv :
a. it contains services files.
b. Eg. If I configure a Apache server on my system, then all services file will be resides in
srv .
16. sys: it contains information of Hardware and system information.
17. usr Directory:
i. usr means user. This directory contains all user related software’s and help
data.
18. var Directory:
i. var means variable data. If any data which is keep on changing, such type of
data will be stored inside var directory. log files will be stored inside var
In order to learn Linux, we need to install Linux Operating system on virtual Machine. Before we
install virtual machine, we must have some idea about virtualization process.
Virtualization
Virtualization is a process where a software-based representation of something rather than
Type 1, provides direct interaction to the hardware, and it can run directly on the host’s hardware and
control it.
In type 2, an operating system is needed to interact with the hardware. The Hypervisor is
Command
In Linux mostly we are going to fire cmd in terminal to fulfil our requirement.
option - option is optional, we do use option in cmd to filter out put as per our requirement.
Argument – It generally contain the file/folder on which you want to perform the command.
We can use ls command to list out all files and directories present in the given directory. We can get
1) ls It will display all files and directories according to alphabetical order of names.
3) ls | more to display content line by line (To come out we have to use q)
5) ls -t : To display all files based on last modified date and time. Most recent is at top and old are at
bottom.
6) ls -rt : to display all files based on reverse of last modified date and time. Old files are at top and
7) ls -a : means all To display all files including hidden files. Here . and .. also will be displayed.
8) ls -A : means almost all To display all files including hidden files except . and ..
directory --> /
executable file --> *
link file --> @
10) ls -i :
11) ls -R
R means Recursive.
It will list all files and directories including sub directory contents also. By default, ls will
display only direct contents but not sub directory contents.
12) ls -s
2]date Command:
Various Options:
3]cal Command:
Note: cal command can provide support only for the years 1 to 9999 (In some flavours).
Working with Directories
1) Creation of Directories
1. mkdir dir1
a. To create a directory
2. mkdir dir1 dir2 dir3
a. To create multiple directories
3. mkdir dir1/dir2/dir3
a. To create dir3. But make sure dir1 and in that dir2 should be available already.
4. mkdir -p dir1/dir2/dir3
• -p means path of directories.
• All directories in the specified path will be created.
• First dir1 will be created and in that dir2 will be created and within
that dir3 will be created.
Wildcard characters
Wildcards (also referred to as meta characters) are symbols or special characters that represent
other characters.
Q1]. Create 5 directories named with dir2, dir3, dir4 and dir5. In these directories create empty files
with a.txt, b.txt, c.txt and d.txt.
Ans:
$ mkdir dir{2..5}
$ touch dir{2..5}/{a..d}.txt
Note: In above example instead of creating each file and folder manually we used wildcard
1) $ rmdir dir1
If the directory is not empty then to remove that directory, we should use rm command. All
internal content also will be removed. rm command can work for files also. Hence rm is recommended
to use than rmdir.
rnikrad@localhost~$ rm Anil
Whenever we are using rm command for directories, we should use -r or -R option. Here case is
not important
$ rm -r Anil
$ rm -R Anil
Note: In Linux operating system, there is no way to perform undo operation. Once we delete a
file or directory, it is impossible to retrieve that. Hence while using rm command, we have to take
special care.
The following command is the most dangerous command in linux, because it removes total file
system.
rm -r /
1. interactive Option(-i)
While removing files and directories, if we want confirmation then we have to use -i option.
rnikrad@localhost~$ rm -ri Anil
rm descend into directory 'Anil'? y
rm remove regular empty file 'Anil/c.txt'? y
rm remove regular empty file 'Anil/d.txt'? y
rm remove regular empty file 'Anil/a.txt'? y
rm remove regular empty file 'Anil/b.txt'? y
rm remove directory 'Anil'? y
2. force removal(-f)
While removing files and directories, if we don't want any error messages, then we should
use -f option. It is opposite to -i option.
rnikrad@localhost~$ rm -r dir99
rm cannot remove 'dir99' No such file or directory
rnikrad@localhost~$ rm -rf dir99
rnikrad@localhost~$
Even dir99 is not available, we won't get any error message, because we used -f option.
3. verbose Option(-v)
If we want to know the sequence of removals on the screen we should go for - v option.
rnikrad@localhost~$ rm -r dir7
rnikrad@localhost~$ rm -rv abc
removed 'abc/c.txt'
removed 'abc/d.txt'
removed 'abc/a.txt'
removed 'abc/b.txt'
removed directory 'abc'
Consider above diagram. Let’s assume your present working directory is abc .
In this case relative path for a.txt will be ‘Sunil/a.txt’ and absolute path will be /abc/Sunil/a.txt
1] Creation of Files:
touch command:
By using touch command, we can create a empty file, but t if File is already available then
content of the file won't be changed. But last modified date and time (i.e., Timestamp) will be
updated.
Note: We can use touch command for the following two purposes:
cat Command:
we use cat command to create a file, once we hit command, we need to pass data, then need to
If file1.txt is not already available, then file1.txt will be created with our provided data. If
file1.txt is already available with some content, then old data will be over written with our
provided new data.
We can use cat command to see content of file as well
Note: < symbol is option here and file must be there with that name
Instead of overwriting, if we want append operation then we should use >> with cat command.
vi editor:
The default editor that comes with the UNIX operating system is called vi (visual editor).
Using vi editor, we can edit an existing file or create a new file from scratch.
we can also use this editor to just read a text file.
Syntax: vi [filename]
$ ls -l /etc | wc
First ls got executed and the output of this command will become input to wc command.
tee Command:
tee command is just like T-Junction or T-Pipe. It will take one input but provides two outputs.
Requirement: The output of the ls command should be saved to abc.txt and should be provided as
input to wc command:
ls -l 1>abc.txt | wc
This command won't work because if we are using redirection in the middle of piping, it will break
piping concept.
In piping, if we want to save the output of one command to a file and if we want to pass that output
Eg 1: To save the output of ls command to a file and to display to the terminal simultaneously.
$ ls –l ➔It will display to the terminal
$ ls -l > abc.txt → It will save to the abc.txt but won't display to the terminal.
$ ls -l | tee abc.txt
We can execute multiple independent commands in a single line by using the following two
ways:
1 st Way: By using semicolon (;)
cmd1; cmd2; cmd3;…. cmdn
First cmd1 will be executed and then cmd2 followed by rest of the commands. If any command
fails in the middle, still rest of the commands will be executed.
Ex : date;whoami
2 nd Way: By using &&
cmd1 && cmd2 && cmd3 &&..... && cmdn First cmd1 will be executed and then cmd2
followed by rest of the commands. If any command fails in the middle, then rest of the
commands won't be executed.
Command Aliasing
Alias means another alternative name or nickname.
We can give our own more convenient nicknames for unix commands. This concept is called command
aliasing.
Note: we can use type command, to check whether the command is already available or not.
Syntax :
$ alias
Remove alias
$unalias [alias_name]
Note: we can use alias for lengthy commands where it will make our life easier.
By default, whatever alias we create, those will be persist till our current terminal session is going on,
once we close terminal alias will get vanished. To overcome this issue, we need to persist aliases
permanently.
How to persist aliases permanently?
Whatever aliases we created, are by default available only in the current session. Once we close the
terminal, all aliases will be lost. But we can make our created aliases permanently in our system by
using the following way:
We have to define our aliases in .bashrc file present in our home directory.
Vi .bashrc
cls='clear'
alias ddd='date;date;date'
Note: To reflect these aliases, compulsory we have to close and open terminal
SORT command is used to sort a file, arranging the records in a particular order. By default, the sort
command sortsfile assuming the contents are ASCII. Using options in the sort command can also be
used to sort numerically.
SORT command sorts the contents of a text file, line by line.
sort is a standard command-line program that prints the lines of its input or concatenation of all files
listed in its argument list in sorted order.
The sort command is a command-line utility for sorting lines of text files. It supports sorting
alphabetically, in reverse order, by number etc.
By default, the entire input is taken as the sort key. Blank space is the default field separator.
Note: This command does not actually change the input file.
In above example sorting is based on alphabetical order.
If we want to sort based on reverse of alphabetical order, then we should use -r option.
If the file contains alphanumeric data, then first numbers will be considered and then alphabet
symbols.
If the file contains only numbers, then the sorting is not based on numeric value and it is just based
on digits.
If we want to sort based on numeric value then we have to use -n option. -n means numeric value
By default, sort command will display duplicate lines. If we want only unique lines then we have to
use -u option.
-k means KEYDEF (key definition). Based on which key (column) we have to sort.
here 5n means 5 column and n means numeric data (5 number column data type) Sort
based on Month:
6 th column provides total date. If we want consider only month then we should use M.
uniq command in Linux
The linux uniq command is basically used to remove all repeated lines in a file. This command is
used when aline is repeated multiple times and replace these multiple lines with one line. This
command is designed to work on sorted files.
Syntax : $ uniq [option] [input-file] [output-file]
Note : To use uniq command , compulsory the file should be sorted, otherwise it won’t work properly.
Comparing Files
We can compare data of two files by using the following commands:
1) cmp
2) diff
3) sdiff
4) comm
Note: All above commands will compare data inside the file’s not the filename.
1) cmp Command:
If content is same then we won't get any output. If the content is different, then it provides
information about only first difference. byte number and line number will be provided.
Ex:
In Above Ex. 36th byte is having miss match.
Note: cmp command won't show all differences and show only first difference.
2) diff Comamnd:
diff stands for difference. This command is used to display the differences in the files by comparing
the files line by line. Unlike its fellow members, cmp and comm, it tells us which lines in one file have
to be changed to make the two files identical.
The important thing to remember is that diff uses certain special symbols and instructions that are
required to make two files identical. It tells you the instructions on how to change the first file to
make it match the second file.
a: add
c: change
d: delete
3)sdiff Command: We can use sdiff command for side-by-side comparison (parallel comparison)
4) comm Command:
comm compare two sorted files line by line and write to standard output; the lines that are common
and the lines that are unique.
Suppose you have two lists of people and you are asked to find out the names available in one and
not in the other, or even those common to both. comm is the command that will help you to achieve
this. It requires two sorted files which it compares line by line.
We can use wc command to count number of lines, words and characters present in the given file.
Syntax : wc [filename]
Eg: $ wc a.txt
• 4 →Number of Lines
• 26 →Number of words
• 166 → Number of characters (File size in bytes)
Ex:
An i-node is a data structure … … that stores all the information about a file except its name and its
actual data.
I-nodes stores metadata about the file it refers to. This metadata contains all the information about
the said file.
• Size
• Permission
• Owner/Group
• Location of the hard drive
• Date/time
• Other information
Every used i-node refers to 1 file. Every file has 1 i-node. Directories, character files, and block
devices are all files. They each have 1 i-node.
For each file in a directory, there is an entry containing the filename and the i-node number
associated with it.
I-nodes are unique at the partition level. You can have two files with the same i-node number given
they are on different partitions. I-nodes information is stored in a table-like structure in the strategic
parts of each partition, often found near the beginning.
Consider above dig. Its show’s a hard disk where there are 4 partitions. partitions A, B, C, D. Each
partition is having Linux file system created, whenever we create partition on disk it will
automatically divided space of that partition into blocks. each block size is 2 kilo bytes. from the total
no of blocks 1 % blocks get reserved for i-node data structure table, rest all blocks will contain actual
data of files and this blocks i-node number get store in i-node data structure table.
Whenever we search for a file kernel first check in file data structure table, where it will find i-node
for that file, then kernel will go to i-node data structure table and will read all meta data of the file.
consider a file “a.txt” which is containing some data, there is some data about the file a.txt like size,
owner, permission, creation date and time these all comes under meta data.
• ls -i
• -i stands for i-node number.
df -ih
Viewing file’s content
In Linux to see files content we have head, less, more and less command.
head:
We can use head command to view top few lines of content.
head file1.txt
tail file1.txt
tail -n +4 file1.txt
A ribbon at a time.
A dominie in gray
Ans: To see data from line nuber 10 to 15 we have to combine head and tail cmd by using pipe
concept as below.
here head -15 will give you data line nuber 1 to 15 by using pipe we are sending that data to tail
cmd and tail cmd will give exact last 6 line means line number 10 to 15.
more Command:
We can use more command to view file content page by page.
more file1.txt
By using more command, we can view file content page by page only in forward direction.
If we want to move either in forward direction or in backward direction then we should go
for less command.
less file1.txt
A ribbon at a time.
A dominie in gray
Question: we want to see data from exact line number 10 to line number 15 by using head and tail
cmd.
Ans: To see data from line nuber 10 to 15 we have to combine head and tail cmd by using pipe
concept as below.
head -15 abc.txt|tail -6
here head -15 will give you data line nuber 1 to 15 by using pipe we are sending that data to tail
cmd and tail cmd will give exact last 6 line means line number 10 to 15.
File Permissions
Linux is a multi-user operating system, so it has security to prevent people from accessing each
other’s confidential files.
Whenever you hit ‘ls -l’ cmd each file will be listed on a separate line in a long format. There is an
example in the window below.
File Permissions describe the allowed operations by various users. With respect to file
permissions, all users are categorized into the following 4 types.
This project divided into multiple modules. In each module multiple developers are working.
1. CUSTOMER MODULE
A, B, C, D ARE WORKING
2. EMPLOYEES MODULE
X, Y, Z ARE WORKING
3. BRAND’S MODULE
M, N ARE WORKING
4. Delivery MODULE
G, H ARE WORKING
DEVELOPER 'A' CREATED ONE FILE demo.txt
For demo.txt
group: B,C,D (The persons who are working in the same module)
Above permission use gets diverse in case of normal file and directory file.
Below table show how same permission allow different operation on file and directory.
Operations related to permissions:
We can perform the following 3 operations.
Eg: For user add execute permission,for group add write permission,for others remove read
permission
Note: Only owner and super user (root) can change file permissions.
Total 9 permissions. First 3 are user permissions, next 3 are group permissions and next 3 are others
permissions.
user can perform both read and write operations but not execute operation
group members can perform only read operation and cannot perform write and execute operations
other members can perform only read operation and cannot perform write and execute operations.
Note: If the user not having execute permission on any directory, then he cannot perform read and
write operations also, because to perform these operations he should enter into that directory
which is not possible.
Note: If the user not having read permission on any file, then he cannot execute that file even
though he has executed permission.
Numeric Permissions:
Note:
4 -->Read Permission
2 --> Write Permission
1 --> Execute Permission
It is easier to remember
5 -->4+1 -->r-x
3 -->2+1 --> -wx
6 --> 4+2 --> rw-
1. Write command for the following permissions
rnikrad@rnikrad:~/Desktop$ ls -l demo.txt
$ chmod 7 demo.txt
rnikrad@rnikrad:~/Desktop$ ls -l demo.txt
7 means 007
umask Command:
umask means user mask. Hiding permissions. Based on umask value,default permissions will
be there for files and directories.
0022
First 0 is sticky bit mostly used in admin related activities. We have to consider only last 3 digits as
umask value.
= 777 - 022
= 755 (user --> rwx, group --> read & execute others --> read &
execute)
rnikrad@rnikrad:~/Desktop$ ls -l file1.txt
=777-022
umask -S 0023
cut, cp, mv and tr Commands
The file should contain column formatted data, i.e tabular data.
emp.data
eno|ename|esal|eaddr|dept|gender
100|sunny|1000|mumbai|admin|female
200|bunny|2000|chennai|sales|male
300|chinny|3000|delhi|accounting|female
400|vinny|4000|hyderabad|admin|male
500|pinny|5000|mumbai|sales|female
Whenever we are copying one directory to another directory, compulsory we should use -r option.
$ cp -r dir1 dir2
total dir1 will be copied to dir2
Note:
If the destination directory (dir2) already available then total dir1 will be copied to dir2.If the
destination directory (dir2) not already available, then destination directory will be created and all
files of source directory will be copied to destination directory but source directory won't be copied.
Que) Write Command to Copy Data from a.txt, b.txt, c.txt to d.txt?
Note: If dir2 is already available then dir1 will be moved to dir2. If dir1 is not already available then
dir1 will be renamed to dir2.
tr Command
tr means translate.
It will replace lower case vowels with upper case vowels in demo.txt
Every lower-case alphabet symbol will be replaced with upper case alphabet symbol.
Every lower-case character will be replaced with upper case character and every upper
-d means delete
-s means squeeze-repeats
Locate command
locate command in Linux is used to find the files by name. There is two most widely used file
searching utilities accessible to users are called find and locate. The locate utility works better and
faster than find command counterpart because instead of searching the file system when a file
search is initiated, it would look through a database.
This database contains bits and parts of files and their corresponding paths on your system. By
default, locate command does not check whether the files found in the database still exist and it
never reports files created after the most recent update of the relevant database.
In above example locate command provided us absolute path of the file. This path is present in the
mlocate .db
This database will be updated only once per day. If we are creating or removing files and
directories, to reflect these changes we have to update database explicitly by using updatedb
command. But admin privileges must be required.
Option:
Find Command
The find command in UNIX is a command line utility for walking a file hierarchy. It can be used to find
files and directories and perform subsequent operations on them.
By using the ‘-exec’ other UNIX commands can be executed on files or folders found.
Syntax:
We can use find command to find files and directories present in our system. It provides more search
options when compared with locate command like:
1. Search only files
2. Search only directories
3. Search by name
4. Search by size
5. We can use search results automatically for some other commands
6. We can restrict maxdepth etc.
1. $find:
It will find all files and directories in current working directory and below in Linux file system. This is
the default behaviour. We can find all files and directories in the specified directory and below.
$ find /dev
$ find /etc
2. maxdepth Option:
usually find command will search in all depth levels. But we can specify the required depth level by
using maxdepth option.
Note:
-maxdepth Valid
--maxdepth Invalid
Find by Type:
We can find only files or only directories by using type option.
-type f means only files
Note:
We can use these options simultaneously, but we should use first -maxdepth and then -type.
Find by Name:
we can find files and folders bases on their size also, for that we need to use -size option
To list out all file names where size is over 200kb but less than 4MB.
To list out all file names where file size is less 200kb or more than 4MB.
Note: you can find empty files or folders by using -empty option.
The find command is comprised of two main parts, the expression and the action. When we initially
use find, we usually start with the expression part. This is the part that allows us to specify a filter
that defines which files to select.
This command will result in a list of mp3 files in the Music directory and all its subdirectories. The
action part in this example is the default action, -print. This action prints the resulting paths with
newline characters in between. It’ll run if no other action is specified.
In contrast, the -exec action allows us to execute commands on the resulting paths. Let’s say we want
to run the file command on the list of mp3 files we just found to determine their filetype. We can
achieve this by running the following command:
Audio file with ID3 version 2.4.0, contains:MPEG ADTS, layer III, v1, 128 kbps, 44.1 kHz,Stereo
Audio file with ID3 version 2.4.0, contains: MPEG ADTS, layer III, v1, 128 kbps, 44.1 kHz
Let’s discuss the arguments passed to the -exec flag, which include:
1) A command: file
2) A placeholder: {}
3) A command delimiter: \;
Now we’ll walk through each of these three parts in-depth. Any command that cannot be executed
by our shell is acceptable here. We should note that this isn’t our shell executing the command,
rather we’re using Linux’s exec directly to execute the command. This means that any shell
expansion won’t work here, as we don’t have a shell. Another effect is the unavailability of shell
functions or aliases.
As a workaround for our missing shell functions, we can export them and call bash -c with our
requested function on our file.
To see this in action, we’ll continue with our directory of Mahler’s mp3 files. Let’s create a shell
function that shows the track name and some details about the quality:
function mp3info () {
TRACK_NAME=$(basename "$1")
If we try to run the mp3info command on all of our files, -exec will complain that it doesn’t know
about mp3info:
As mentioned earlier, to fix this, we’ll need to export our shell function and run it as part of a
spawned shell:
$ export -f mp3info
01 - Das Trinklied vom Jammer der Erde : 128 kbps 44.1 kHz Stereo
Note that because some of our file names hold spaces, we need to quote the results
placeholder.
The Delimiter
We need to provide the find command with a delimiter so it’ll know where our -exec
arguments stop.
The delimiter determines the way find handles the expression results. If we use the semi colon (;),
the -exec command will be repeated for each result separately. On the other hand, if we use the
plussign (+), all of the expressions’ results will be concatenated and passed as a whole to the -exec
command, which will run only once.
Let’s see the use of the plus sign with another example:
./Gustav Mahler/01 - Das Trinklied vom Jammer der Erde.mp3 ./Gustav Mahler/02 -
Der Einsame im Herbst.mp3 ./Gustav Mahler/03 - Von der Jugend.mp3 ./Gustav Mahler/04 -
However, we may prefer using the semi-colon delimiter in one of the following cases:The tool run by
-exec doesn’t accept multiple files as an argument.
Running the tool on so many files at once might use up too much memory.
We want to start getting some results as soon as possible, even though it’ll take more time to get all
the results.
grep command
Grep is an essential Linux and Unix command. It is used to search text and strings in a given file. grep
filter searches a file for a particular pattern of characters, and displays all lines that contain that
pattern. The pattern that is searched in the file is referred to as the regular expression.
Syntax:
We can use grep command to search the given pattern in a single or multiple files.
2. Perform a case-insensitive search for the word ‘bar’ in Linux and Unix:
3. Look for all files in the current directory and in all of its subdirectories in Linux for the word
‘httpd’:
$grep -R 'httpd’.
4. Search and display the total number of times that the string ‘nixcraft’ appears in a file
named frontpage.md:
By default, grep command will consider case. If we want to ignore case then we should use
use -i option.
10. Display before, after and surrounding lines including Search Results:
We have to use -A, -B,-C options
-A means after
-B means before
-C means before and after
Search Multiple Content in a File:
Instead of using -e option, we can use egrep command directly. It is extended grep. It interprets
patterns as an extended reqular expression.
It will take a group of fixed strings and search for those in the given file. Strings should be separated
by new line.
Instead of using, -F option, we can use directly fgrep.
Note: fgrep can be used only for Strings and cannot be used for regular expressions.
Normal grep command cannot understand some regular expression patterns like | symbol. But
egrep command can understand any regular expression pattern. Hence egrep is the more powerful
than normal grep command.
In this case, (java|unix) is treated as regular expression. It will search for either java or Unix. egrep
and fgrep are deprecated and hence it is recommended to use grep -E and grep -F commands. If
strings are available in the file, then we can use -f option to specify file name
-o: Print only the matched parts of a matching line, with each such part on a separate output line.
Sudoer File
What is a Sudoers File?
A Sudoers file is just like any other file on a Linux Operating System. But it plays a vital role in
managing what a “User” or “Users in a Group” can do on the system.
But, let us take an example of — you as a system admin have to manage all the users and their
controls. You have a website hosted on Apache in one of your servers. You already have a Web-
Admin to manage it. A user should be created for him on the Web-Server. This User should be
allowed to do two things which a normal user cannot:
Root User which has got all the permissions on the system including Apache.
A normal user, which by default won’t be able to edit any config Start a Service or files on the
system.
This is when a sudoers file will come handy to you. In Sudoers file we can exactly define:
Web-Admin user can only start Apache Service &He can only edit Apache Config file.Playing with
the Sudoers File
Primarily we can see five sections in the file — the first three sections in the file are related to ALIAS
of Host, User and Cmd.
We will talk about ALIAS later, first let us talk about the core section:
Note: ‘#’ indicates comment in the file, OS will ignore this line while executing.
Read it as — User Root can Run Any Command as Any User from Any Group on Any Host.
The first ALL is used to define HOSTS. We can define Hostname/Ip-Address instead of ALL.
ALL means any host.
Second ALL : Third ALL is User:Group. Instead of ALL we can define User or User with the
group like User:Group. ALL:ALL means All users and All groups.
Last ALL is the Command. Instead of ALL, we can define a command or set of commands. ALL
means all commands.
Directly give him the permission to execute the command by modifying the permission of
the file.
Allow him to execute the command as another user which already has the permission to
execute this command.
We will use another example to clearly understand the fields in the syntax:
Read this as — User “sysadmin” can Run the command “/usr/bin/cat /etc/shadow” as ROOT user
on all the HOSTS.
Linux is designed to serve many users at the same time. Users have their own shells through
which they interact with the operating system.
As a system administrator, you can manage user logins on your system. You can add or
remove users, as well as add and remove groups.
Any utility to manage a user or group makes use of certain default files, called configuration
files and directories to set up the new account.
Below is the list of files and purpose:
/etc/passwd
When you add a user, an entry for that user is made in the /etc/passwd file, commonly
known as the password file. Each entry takes up one line that has several fields separated by
colons.
A corresponding password file, called /etc/gshadow, is also maintained for groups that require
passwords.
Note:
Each time a user logs in, two profile scripts are executed, a system profile script that is the
same for every user, and a user login profile script that can be customized to each user’s
needs.
/etc/skel:
When you first add a user to the system, you must provide the user with skeleton versions of
their login, shell, and logout initialization files.
For the BASH shell, these are the .bash_ profile, .bashrc, and .bash_logout files.
The useradd command and other user management tools add these files automatically,
copying any files in the directory /etc/skel to the user’s new home directory.
The /etc/skel directory contains a skeleton initialization file for the .bash_profile, .bashrc, and
.bash_logout files.
As a superuser, you can configure the .bash_profile or .bashrc file in the /etc/skel directory
any way you want. Usually, basic system variable assignments are included that define
pathnames for commands and command aliases.
The PATH and BASH_ENV variables are defined in .bash_profile. Once users have their own
.bash_profile or. bashrc file, they can redefine variables or add new commands as they
choose.
/etc/login.defs:
System wide values used by user and group creation utilities such as useradd and usergroup
are kept in the /etc/login.defs file.
Here you will find the range of possible user and group IDs listed.
UID_MIN holds the minimum number for user IDs and UID_MAX the maximum number.
Various password options control password controls—such as PASS_MIN_LEN, which
determines the minimum number of characters allowable in a password.
EX:
engines:x:100: chris,robert,valerie,aleina
Linux provides the useradd, usermod, and userdel commands to manage user accounts.
All these commands take in their information as options on the command line.
If an option is not specified, they use predetermined default values. These are command line
operations.
useradd:
With the useradd command, you enter values as options on the command line, such as the name of
a user, to create a user account. It then creates a new login and directory for that name using all the
default features for a new account.
Option Description
-d dir Sets the home directory of the new user.
-e mm/dd/yy Sets an expiration date for the account (none, by default). Specified as month/day/year.
-f days Sets the number of days an account remains active after its password expires
-g group Sets a group.
-m Creates user’s home directory, if it does not exist
-M Does not create user’s home directory
-s shell Sets the login shell of the new user. This is /bin/bash by default, the BASH shell.
-u userid Sets the user ID of the new user. The default is the increment of the highest number used
so far
usermod:
The usermod command enables you to change the values for user.
You can change the home directory or the user ID. You can even change the username for
the account.
The usermod command takes the same options as useradd, listed previously in above table.
userdel:
When you want to remove a user from the system, you can use the userdel command to
delete the user’s login.
With the -r option, the user’s home directory will also be removed.
In the next example, the user chris is removed from the system:
# userdel -r chris
You can also manage groups with the groupadd, groupmod, and groupdel commands.
In the following example, the groupadd command creates the engines group:
# groupadd engines
You can delete a group with the groupdel command. In the next example, the engines group is
deleted:
# groupdel engines
groupmod
You can change the name of a group or its ID using the groupmod command.
Enter groupmod -g with the new ID number and the group name. To change the name of a group,
you use the -n option.
Enter groupmod -n with the new name of the group, followed by the current name. In the next
example, the engines group has its name changed to trains:
Password Tools
passwd command in Linux is used to change the user account passwords. The root user reserves the
privilege to change the password for any user on the system, while a normal user can only change
the account password for his or her own account.
-d, –delete: This option deletes the user password and makes the account password-less.
-e, –expire: This option immediately expires the account password and forces the user to
change password on their next login.
-i, –inactive INACTIVE_DAYS: This option is followed by an integer, INACTIVE_DAYS, which
is the number of days after the password expires that the account will be deactivated.
-l, –lock:
1. Lock the password of user.
2. This appends the encrypted password of the user with a character ‘!’, and thus
making it unable to match with any of input password combinations.
3. This does not disable the account but prevents the user from logging in using a
password.
4. Though other authentication methods like ssh keys can be used to login to the
account.
-u, –unlock: Unlock the password of an account.
Chage tool
The chage command is used to view and change the user password properties.
The chage command let you specify an expiration limit for a user’s password.
A user can be required to change his or her password every month, every week, or at a given date.
Once the password expires, the user is prompted to enter a new one. You can issue a warning
beforehand, telling the user how much time is left before the password expires.
If there is an account that you want to close, you can permanently expire a password. You can even
shut down accounts that are inactive too long.
The -M option with the number of days sets the maximum time that a password can be valid.
chage -M 7 chris
To set a particular date for the account to expire, use the -E option with the date specified
mm/dd/yyyy.
To find out what the current expiration settings are for a given account, use the -l option.
chage -l chris