0% found this document useful (0 votes)
163 views78 pages

Linux Notes-9

The document discusses various basic Linux commands and features of the Bash shell. It provides explanations of commands like ls, mkdir, cd, pwd, cp, rm, cat, touch, more, which and their usage. It also covers Bash shell features such as variables, aliases, history, auto-completion and customizing the command prompt. The document is a guide for new Linux users to get familiar with basic file and directory operations from the command line.

Uploaded by

sopan sonar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
163 views78 pages

Linux Notes-9

The document discusses various basic Linux commands and features of the Bash shell. It provides explanations of commands like ls, mkdir, cd, pwd, cp, rm, cat, touch, more, which and their usage. It also covers Bash shell features such as variables, aliases, history, auto-completion and customizing the command prompt. The document is a guide for new Linux users to get familiar with basic file and directory operations from the command line.

Uploaded by

sopan sonar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 78

ELI

HIing 11th sell


shell command line interface Enables to work on Linux
system
A program that allows txt based interaction b w
woe and operating system
Interaction is carried out
by typing commands
home girish Home directory

th y trametecticated
place directory

at echo
ftp.int
uptime

echo n hello
hello 3 hello will be printed without any trailing
line
Commandtypes

Internal commands't External commands


Built in
There are BinaryPrograms script
which are usually located in
distinct files in system
Pre install

Type commandname 7
Gives the type ofcommand Internalbuiltin Enternal

echo n hello
Gkommand
named fption argument
Eh shelf
Thereshells
Bourne shell ish I may have diff
core
Shltype C Shel esh or teshl capabilities
Korn shell Ksh But main purpose is to
2 Shell 2sht facilitate communication
Bourne againshell Bash b w user and 0

echo SHE'll
will give the current shell default shell

ansh
Password

Loginshell Abin bash bin sh


__

usingthis command we can change default shell to required


shell we have to provide password during this action

features of Bash

1 Command auto completion by clicking Ead autocompletes directory


on file name
2 Usage of alias tired long command
By this u can to shortform

alias at date

3 history
will give the details of commands that you ran previously

Variables

fecho Kvaniablename
kill output the value of variablename provided
g en
lists the variables and their corresponding values
export variablenames avalue to assign
This sets the variable for current shell and forany
other programmes procera started by shell
variablename valueto assign
This apply to variable within the shell not applied
to other procend programmes value won't be carried forward

To make the provided variables and values to be persistent


over subsequent login or reboots
Add the variables and values to Profile Pam
Profile a environm
l pam environmentnt
n

PathVariable
Iver issues an external command into the shell The
shell uses a path variable to search for there external commane

echo PATH
shows the directories defined in path variable

If path variable doesn't have location directory


of command
a programme defined then Gunning command will result in failure

which Programe command


Will show the path where directories of command are defined

export PATH PATH

Append the path


gg etony

of directory if you want add the path


and want the command to be executed
Eh Impt
the taiminal you can see prompt
When
you turn on open
showing name of user current directory ate

This can be customised to what you want to see

Bash Prompt are set and controlled by separate environment


variables

echo 151
7
upon running psi it shows present working directory

Psi Ivariabename I By this value of Psi


variablename
prompt will be changed to variable name

In variable name we can use


characters given in the photo
to atomize further
Basic linux commands
Pwd Ipresentwalkingdirectory

homegirish
LS I list conents

mkdir directory names


Creates new directory with given name inside homedive
Cd adirectory name
micdir hdirname Idir name
will create new directory ni nz inside home directory

mkdirhdir.name Ldir namet


will go to ni and then create na imide ni should be
n present

mamey dirname
Mkdir p hair
This will create ni and then na inside n

Cd the home
will move directory
Cd
Cd homegirish
Y
ed homegirish name 7 Absolute path

ed name 7 relative path


Cd will keep u in Same directory you are in

IN This command remembers the current waking directory

before changing to the directory specified inthe tommand argument


Pushd fete
This will be the home divestory
Popd
This will pops the given directory and bring back to home
directory
Ige Game yd y fils

my isoirilitath holutinationtepath

This will move directory at source path to a destination path


If you are using relative path make sure you are in
correct directory

my sourcepathwithwrongnamedirectly Destination
path correctnamediver
Used to rename the given directory name a file name

Cp asourcepath I destination path


will copy file in sourcepath to destination path

rm k pathoffileto remove
will remove file directory in given path

While Cp and rm commands us r option


using
Read and Invite to filer

cat filepath
content in the given file at given filepath will be displayed

cat t Efilepath inwhich replace datarequired If


Type txt u want to give user input
can give as many lines u want by
clicking enter

TIED
To emit out of the prompt and save data

Touch L directly path filename with extension

To create a file in given directory enquired directly


more filename
By this you can view txt files in a scrollable manner
once file open below helps loads entirefile at once
IM Espace one screenful data at atime
Center south display lineby line
7 Strolls display back wards one screenful data
by
17 Search txt

QI To emit out

lets filename txt


allow to view content of the file

Ing
Liste the file in the directory
LS 1 long list
as
offiles
Provides moredetails directories such

Acer model
Ownership
Laitaccededtime
Is a Itlidedenfiled
lists all the filet including hiddenfiles tilstop
a lot
Ihiddenfiles directories precede startwith filename

Is It I long list files in order created

Is Itr long hit files in the reverse order

Commands
tying
whatis command
This will display one line description of what a command
does

apropos keywords

Prints searches the file name with keyword


Inept
thinside library
students Ig Applications procen

Wmd librarian
the keeps track of books Send notification
before deerdate i e looks after
I i resources their availability allocation
1300kt studtide
penitytation
limiting would so to makethem
available for all
hemby tip ape in

Linux keenal takes care below Major tasks


of
to track how much men used to storewhatand
Memory management where

Process management which Proceu can use cpu when where forHowlong

Device Drivers I Meditor to hardware and Procera


System call and Semity receives reqfromservices from procenes

Linux kernal is monolithic i e has Cpu scheduling manager several


operations byitself
Kunal is modular
entende its capabilities by dynamically loaded Kunal
modules
uname
Linux giver Kunal being used

uname r
gives keenal version details
4 15 0 72 generic
4 Keenalversion O Mindversion Genetic Bistrospecific info

15 Majdversion 72 Patch mean


Ubuntu 20.04 use Linux Kanal 5
Example

Iemoryatnagement Ind
Memory divided

use space
Enigtiminilitate kunal
g space 1
access to and has
1 has Apps Programs
Proceed insidethisspace
has unrestricted arced
to hardware
Kanal code
Eulation
Device driven

Uses Space How Prog running in user space work


will function data
Apps running by manipulating
data line on disk
Then anceded
by system calls

Systemcalls get pin


Inesg
Displays msgs from area of kernal called ring buffer
When linux boots up numerous msg generated bythe kernel that
appeal on display
It have logs
udevadm info query path name deviselas

udevadm utility is a management tool for udex


G udevadm command queries udev database for device information

This command queries the harddisk attached to system

userspace
it c
LIII
I s nugent
LUSITH Uden

When USBattacheddata
It
will be visible under
my pay
udevadm monitor
This command listens to thekeenal uevents
upon detecting events it prints ite details
like i device path
2 device name on screen
Command determines the details
of a newly attached 8
removed device

Lspci
display info abt all PCI devices that are configured
in system
peripheral componentInterconnect
Pel

ethernetcard maid controller videocards and


Effi wireless adapters that directly attach to pci slots
In motherboard of computer
Is
big lists info abt blockdevices
Sia 7 physical disk
may min RM Ste
a dis
8it
Partitionscreated
spacecarvedout
STGsq eatsthereusabledisk
88 ofphysicaldisk
8 2 10M
Sdgs 83 60.14

Major Number Devicetype


1 RAM
3 HD CDROM
6 ParallelPrinters
8 SCSI Disk

Provides detailed info such as Cpu architectures


no ofCorel thread model

mens
used listsavailable memory in the system
Is mem summary
will list and printsummary of memory

free m
gives total us used memory in system

in Kb
Ishw
Is tool to entra it detailed info on the entire hardware
configuration of the machine

Reports enact memory configuration ethernet controller


firmware version
mainboard config
cpu version and speed
SUDO
Not all wees can run each and Every command on linux
system
Some need to be run at the root the superuser
This can be seen by using Sudo

LINUX BOOT SEQUENCE

Bios Post Boot loader kernal IN'TProcess


GRUBS Initialization Systema

power on
selftest Boot 1
POST Grandunified This calls systemd
BootlodenVersion 2 daemon
Systema is responsible
for bringing Linux host
to usable state
systemd is universal standard Responsiblefor mounting
But now file systems Starting
Another initialization process andmanaging systemsemi
init was used
Syfy
Syst used in RHELG and centOst

using Systema over Sysfile init

It reduces startup time by parallelising start


up service

Is I Isbin init
www.o.lsbinlinit 7 liblsystemd systemd
This command will output the init system being used

Interface after booting up linux system Goi all

runlevel operational mode that provides non Graphical


µ
y interface

run level
operational mode that provides Graphical
µ g g interface requires displaymanager service

During boot init procen Chica Inter comistolniingly


makes sure all programme
need to make
system operational
in given mode are started

Viewing 8 changing systemd target Gui Cu Cii Gui

Systemctl get default


graphicaltarget
Is Itr letelsystemd system default target

Systemctl set default multi user target


will swith ownlevel 5403 GUI 7 CLM
ELE TEES II LEX
Every object in Linux tan be called asfiles in Linux
Types

There are common files that has data txt images


Regular file
Txt jpeg
file that stores other files within
oh
CITY fig represent
delices under filesyste
II
Special files which allows to communicate
of Ilodeviy
Blockfilet Represent bloat device under
Idey
Ram Halfdiske escamplet
Linke Hardlink
E soft link Ilike
Socket Special file enable communication
btw 2 Procelles
Named Piper specialfile that allows connecting
one process as input to another
thin provide way to anociate 28 morefile names to same set

Hardlink Associate 28 morefiles


share same block of data on physicaldisk
deleting one will delete data
soften Act like pointers to another file
Deleting symlink doesn't affect data
file givefile adirectorypath
This command gives the output which type offile
Like directly symbolic link socket Bourneagainshellscript
Id givefile a
Is directorypath etc

dr wXv Xv 8
command ist letter will tell typeoffile
The output ofabove
The first letter acts as identified

type identified
Divestay y d
so iket s
Regular
Iharacterdevice a
link 1
Pipe p
Blockdevice b

filesystem Inches
1 bin contains basic programmes and binaries such a cp.my
miidin ele

Iboot

1hey fontaine Special blockand character device files


files of ex HD mouse keyboard etc
etc a stores most of the configuration file in Linux

This consists home directories for all users


home
empty
fib 4 This and Libby isthe place to lookfor shared libraries

É
to be imported into your programs
media u can view data of anyattached externaldevices
susbl
Imnt used Mount file system temporarily in the system
using ment command
put 3rdparty software here if youwant to install

tmp stores the temporary data like data from mounted


disk
Usr In oldersystem this is usedfor user homedirectories
In modern systems this is where userland application anddad
resides en Mozillafirefox v1 txteditor etc

Divestoryto which system writes data such as loge


Ivar
and cashed data refer herewhen uface issueswithapppro
df he
diskfilesystem command prints out details about all the mounte
file systems

KEIL PAGE AMENAGENT


Paysage tag packageManager
Ubuntu debian DPkg APT
Redhat CentOs Rein
RHEL

Diff b w RHEL Centos and Ubuntu


There are too's
of Linux distributions in use today
common
ways to categorize a Linuxdistribution
1 Package manager uses
RHEL
RPM H centos Rpm based distribution
Fedora

of dpkg
E
DEB Thesemake use
thin
Debian

RHEL VS CENTOS
1 Paid
2 Enterprise offering
3 Technical support I2 community version
Immunity
support

Package
It is a compressed archive that contains all thefiles
that are required by particular software to own

all files softwarebinaries


metadata
configurationfiles
Linux prog may not run Same
wayfrom onesystemto
another

To fix this packages inilude


1 Manifestof dependencies
2 lists of programme andversions
That must be satisfied for Packaged Software to run
correctly on given computer

Pelage
nag is a
software in Linux system that
provides consistent and automated process of installing
upgrading configuring and removing packages from Os

functions
1 Ensuring integrityandAuthenticity
ofpackages
2 Simplified Package manament
3 Grouping Package
4 Manage Dependencies

Linux Supports many Package managed Some were


1 DPKG Debian based distribution base packagemanaged
2 APT C Present Iin Ubuntu
3 APT GET
4 RPM Redhat Cento
5 YUM
G DNF

RPM
Fed in
RHEL
CENTOS
Fedora
of operations in RPM
Idc If
Installation Below command is used to install a Package

rpm ixhapailiage.name g telnet rpm


used to printdetailedgutputmm
i install v verbose I
uninstalling To un a package use below
named
rpm e a package

upgrade To upgrade to newelversion use below and


rpm Ilah apackagename
RPM database stores info of all Rpm pailcage installed in
path war lib rpm directory

Query To query database of packages stored in


Iwao Lib 2pm are bellow command
rpm q apackage name

Verifying To verify a installed package

rpm Wf 2 path tofile


This Verifying package means compares information about
files installed from package with Same info from original
packages

This makes us sure that package is installed from


trusted and secured source

Despite all the above model


RPM doesn't resolve package dependencies on itsown

So he use higher 41 package manager


YI
YUM pastage managee Yellowdog updater Modified

free and opensource Package manager works on RPM


based Linux

system

Works with SoftwareRepositories collection ofpackages


and provides package anddependency management on
RPM based distros

Repo info stored in etc yum reposed


Repository files have repo extension

YI acts as high lil package manager But still


depends on RPI to manage packages on the Linuxsystem

Automatic Dependency Resolution

Yure manges package verywell its able to install any


dependencies

dependent package to get base package installed on Linux


system

Ew Yum insalls a package

um local eglaptop

ends.mg
Klarehouse Yiimon
4 There can be accessed
by http HTTPS FTP

Info of Softwarerepo is saved at etc yumreposed

Yum use RPM package manager to install package


on linux system
SoftwareRep

HIII
Local FTP
package RPM Package
Manager Manages

Pete Hum repos d


lets yum nepos I redhatrepo
4
redhat software repository
gy
letelyum.repos.nl nginxrepo
He can point diff software repo other
than offical As official might mightnot
repo
have updated software or doesn't here at all

Stassiinstalling Padages
Yum install apackagename

1sttransaction check will be ran

Package not installed


Yum cheeks configured repositories

Also checks any dependency packages insta


Transaction Summary will be displayed Y N

Y This
flag will help in Skipping Transaction
Summary input
gum repolist
will show all the repos added to your system

Yum provides acommandname


This command shows the package to be installed
for a specific command to work

yum remove a package name


To remove installed package

yum update page name

To update a single package with latest version

1 gum update
To update all the installed packages use this command

DPKG and APT

Package
Extension jeb
Simerly to
Installation Below command is used to install update a
update package
dpleg i packagename

uninstalling To unistall a package use below


dpkg r package nanny

list To list packages installed in system along


with version and short description use below
dpkg I package name
States y to check statue
Apkg s package y

Veryfying 7 To display details about packages like


version no maintainer etc

dpkg p a pathof packages

Similar to RPM Dreg doesn't resolve dependencies


issues
So we are higher led package manager APT APTGET
to get packages installed

APT Advanced Packagemanagement

Apt Apt get 43 Don't depend on each other they are


2 diff entities
Apt more user friendly than Apt get
Apt acts as frontend package manager that relies on
apkg
SoftwareRep

a Apt Package Deke package


Manager
y
Manages

tetclapt sources list

Itis
Apt update command used to Refresh repository

It downloads package from all information Sources

Runthis command immediately after installing Os or


after adding new sources

apt upgrade
at is used to install available upgrades of
all packages currently installed on the system from
sources configured

apt edit sources


used to update repositories
This open letelapt sources list in txt editor
him nanano

Hotplate fit file in wi editor

Once all repos are set


up
apt install apackagename
command install package

apt remove packagename


To remove package

apt search package name


To search Lookfor package

apt list
APT V3 APT GET

1 provides output in user 1 Not wer friendly in


friendly while installing providing output
package

2 While Search for any package 32 Not possible need to we


another tool
you can
apt search package apt ache search package

liking lath SHEI


du sk filename directory

I will show the size of corresponding file directory


du sh filenamedirectory
10017 filename
Will showthe size of file in human readable format
Is 1h filename dirname
ow ru r I 99m may 13 00 00 filename

by using h with long list will print size of file

Archiving files
Tay Elity Tape Archive
used to group multiple files directories into a single
file
files created with tar are call tarballs

tag of filename tax Lfiletoarchive filetoarchive


creates archive with given filename tar and archives
the files provided
tar tf anhtoYiew
tar ball
will show the contents of

tax Xf tar tile to Extract


will Extract files from tar ball

tar Lcf a tarfile filestoarchive files file37


will compress the given tax file to reduce size

Commands to compress file

bzip2 filenameto comprent upon using these b22


command It
92p filename to compress
44aids to
entention
file along with
7 092

x2 file name to compren filenameanditsEutension y x2

To uncomprets use below commands

bunzip2Lfile
enten.bz2 Sgunziphfile.enten.gz

Unxz file enter.xz

Below commands help in reading compressed files


without uncomprening them

2cat file ext 227

bzcat file ext gzy

Xzcat Lfile ext xzy


lock they
Ich In
locate filenames
will return all the paths matching pattern with
keyword in it
This command depends on mlocate bd to query
file name
This command may not be useful if you just
installed linux or created file a directory
Since DB might not be updated

updatedb
will manually update db and should own as
root user

find t directorypath nine filenames


whereyouwant
to search
home girish
command used to find path of the given file in
given directory
There are plenty of options available to are the
find command

Mfs't
popular command to search within files in Linux
Commonly used to printlines of a file matching a pattern

command is case sensitive


grep sword filename
Hill output the line that matches given word

grep i xword files

will make case insensitive and output the line


that matches pattern
2 word L directory path
grey
will search for pattern word recursively within a
directory

grep V word 99 filename


This command will print the lines that doesn'tmatch
the given pattern

grep W word afilename


will search for only the whole word and
gives lines that matches the whole word
Whd Exam command
line ExampleofAustralia other grep d
exam in india gy output both
will
0M
Byusing one
line 2
grep VW wordy filenames
Will print the lines that doesn't match exact word

grep Al world filenames

will print the lines matching pattern and one line below
it
A will these
Simalay By giving the no
oflines often

no of line

iii iii ii
will print the lines matching and one line above
it
airman
no
of lines above it
A1 131 Awad filename
grip
will print the line matching word and one line
above and below the word

IO Redirection
standard
Stalin Accepts txt as input
Input cat sample txt
standard output output printed will be delivered
by stdout thirst
Standard error as errors will be sent bythis stream

IKE EDIT
To redirect standard output to a file instead printing on screen

echo 7 shell txt


5Hell
Witemove all data in shelltxt and adds given
output data
echo This is bestcourse x shell txt
will append given tent in shell txt at the endof file

cat offileto whicherroriswritten


knname

missingII
This command will write over to given file
If file
doesn't exist it will create new one It already enisle
the file will be overwritten

cat send msgto add 2291 terror filenames


This will append error msg and doesn't print Errol mig
on Screen
cat our msgs 2 the placewhere you dump
lighting anything you don't need
will dump the Gods msg to bitbucket location
And Error wont get printed on screen

Command I I command2
I
pipe
In this case commandI output acts as input
for command 2

II EDITOIS
II Edith
Vi Name path offile to Edit create
This command will open the file for Editing
for creating

Modes in v1 Edith

Commandmode

upon openingfile using y it always becommand mode


PIET FEET He can issue commands to copy paste delete a line

Insert mode
É heused to editfile Addtext Remove text
To enterthismodefrom commandmode we can use keys
0 A I i d o

a Last Line
Lani Id file using I command
Mona You open any to
move around at will be in command mode and
Navigate infile you say we below keys

II IIIa
copy a line 4 Move to particular line and Enter below
E II
a Moveabove line a place in file and Enter below
paste
F
use uppercase 4713 to save

deleteletter M Move to intended location and type x


DX
delete a live a move the cursor to intended line and enter below

D To
I Did to delete 3 lines u can replace number
with n roof number lives
of
undo Type D to undo change made previsorly

Redo us type
Do to redo change

To find a
string in a file opened on vi editor

use D Id followed
by pattern to Search

I patternto search
This will search downwards from current position line
upon searching cash will move to 1st ocurrence from
the current position
Any upon pressing will give nxt occurrence below the
current line
pattern above current
line
WIT To find the
patient 7 This will be enact opposite reverse
will search upwards from current position line
N key will search word upwards
N key will search it wold downward

Angstmode
you can lay in IT to a
lastline mode
Type in
By this you can make many change bytyping below

seethe file btw

Ed q
save andQuit
wq
Quit q
with confirmation

An improthersionfieditor with mom features


Networking in Line

Doe
TED Ey
Iffy
192172 1.10

He 2 Computers which are poet of same network with


ip addrence assigned

To check connectivity b w 2 servers

Ping hipaidrenaddven of machine which u want


to connect
Run this command from machine are testing
you
for the connectivity

you want to give name to IPaddrey And can


When we
name instead address
of
miasma a
the system having the file
IP address name
I
an above file you can map ipaddwell with name

Checks connectivity with name as it is already mapped


hostname
Gives the hostname of system

you can map as many names you want to single


IPaddress
in etc hosts
lather Ever we below commands like
you
Ping
curl
5511

It looks into letethost file to find out IPaddren

Name resolution
Translating hostname to IPaddress through using
letelfile known as Name resolution

command
Ping may not always good if Ping is disabled
in host you can't use them

Inslookup and dig can be used when pig is disabled

DIS
The Environment all the etc host files in the
grew
systems got filled with too many Entries then
managing all became difficult

One Seever ipchanged then it req to be thanged in


all of the hosts files

To Overcome this all these entries were moved into a


Single server that will manage centrally and it is
called our DNS Seever

All host will be pointed that server for name resolution

How to point our hosts to DNS Serves

1 DNS Serverwill have IPaddress


2 7 Every host has Dns resolution config file at below location
etc resolv conf
Add an Entry speifying IP address into it maps thename

en DNSServer IPaddress

Still you have both DMs and also host file


In host file you can configure your required
Server which were
upto your requirement use
System can resolve ipadvers

locally thorough late hosts

remote bring DMsSeever


When u have Entry in both local and emote
with same hostname but different IPaddress
they it ist looks in local host file

The older of checkinglocal host and then the


remote can be changed by making changes in
cat etelnsswitch conf
hosts files dns

If Entry not available in both then add another


Entry in etc resolveconf
ie nameselves 8.8.8.8
Tubacnamseevee hosted
by google
It knows all the websites

We can also configure the same on DNS saves itself

to forward unknown host names to the public


name saves
any
on internet

Now you can Ping any thing on internet

Domin Name
The IPaddrenes translates to names that we can
remember on the public internet are called domain names
Just like we name our hosts

The heron for format separated like org com net


are to
group similar things together
The below were top level domains intended for common
purpose
Comm commercial purposes
s net Networking General purpose
edu educational organization
o
Ong for non profit org
io
Root o where Every thing starts

Toplevel domain COM

google domain name assigned to google


Subdomain

mail drive aww maps apps


Above subdomains can still be divided into as many
we want

Boy Lapped In Ing Idle Eying Eachguy dyaingame

apps google.com

t Org MPs90096.10m 210.58221


DNS
t caches IP
Organisatizone
pg names So thatit doesn't
gothrough wholeprocess
COM
DNS
again

4095ns

216.58221 78

Similarly organisation can have their own structure too

org
DNS

mycompany.com

I
n's mail pay to drive
whw Iq
Now can resolve
we and map ip with name for our
company in internet

Lip address web mycompany.com

So when you want to ping from company network you

can't f ping web wont happen


une
X
ping web mycompany.com
path
to happen
We need to make changes in hosts
cat y Pete resolve conf
nameserve hip add specityrdomainndm
append
Search to
mycompany.com

Aping web
PING web.mycompany.com

Royl Typed
How records are stored in Dns server

It will Store IP to Hostname

EEA type
TAT hostname IP
hostnam IPV
DtaA record
quad
hostname I hostname 2
ENAMEL
other
mapping one hostname to

Mashup
You can nslookup to query a hostname from a

DNS Seever

nstrokup hostname
Seever
added

nshookup doesn't consider the entries in local


i e etc hosts file

Rig
This command return more details in a similar
form stored in Server
SwitchingAnd Routing

Lets make communication between 2 Computers


or rims on cloud

111 To connect A and B A should neath B viceversa


indie to make this possible we use switch

A switch B
creates natural
containing
2System
I

42
Inordee to connect system to switch they need interface

A etho switch Ethio B


There are Interfaces that can be
Physicalvirtual to connect hostswith
I
P
command wed to see the interfaces for the host
Step2

A tho a D D D D D Ethio B
192.172 1.0
I Assuming switch is network I
192172.1 10 192 172.111
Now we align with ipaddrenes using blew comma
systems
on both system So that both communicate with each other
elev etho
ip adds aid Ipaddress withCepr
192.172 1.1024 Interfacename

LIII
a DO'D DO D
tho B
it
emo
A etho a DO'D 00 a
192.174.1O 192.172go
12.12.2 192m22
192172.110 a a in io

Motel connects to a network we


assign 2 IP's
Iggy Router
192.172.2

Switch can Enable communication within a Network i.e it can


receive packet from host and deliver to other system on network
In order to make communication possible b w 2 hosts machinesfume

in different network we are routed


Routes help connect two networks together

SITI a ooooo
1921741O igno
a
etno.rs
192172
000
i
D

4,1 g

192.172 I I you Router 192.1722

Now we want B to connect with C


As Route just another network device on network

Here we configure gateway route


Network is a Room
is a door to other network internet
Gateway
90
F command will show routing table

In linux to configure gateway on


any Systema to reach
other systems we use below command

Similarly we need to configure other gateway to reach

from Systems to systems

Ip route add 192.172 2.0 24 via 192 168 1.1


LimpofSwitth2ciDry tip of routes with switch17
specify where to reaint through which gateway

ie Sys B reaching Sys e

If Sysc want to send to syst their route

should be added in Sys c

Steph
4Now there systems need accell to internet
Now connect route to internet
Add new route in your routing table

ip route add hipaddofinternet ebay via Lipadded


gateway
EEE ÉE
Tho
A or DOD DD tho D
g DOD 00

j it
192.174.1
O 192.1721.0
12.172.110
12.12.2 iat.no
iaz.na.in io

192.172.1 1
Dow Route 192.172.2 I

There are So
many diff sites on diff network on internet
instead of adding routing table routes for each we can
use
default
for any network we don't know route to we the
given route at default gateway
ip route add default via 192.172.21

ip route add 0.0.0 0 24 via 192 172.2 I

A 0.0.0.0 Entry in gatewayfield indicates


you don't need
gateway

It there multiple routes in network then you need


to configure routing table all the routes
Separate Entries for Each network required
Go.EE AEFE7o
Tho
A a DO'D Do B D
etho DO'D 00
I I
192.174.1
O Ith e Ethio

192
172.110
in z
12.12.2
a

I
ain io

Route

192.172.1 1
Dow Route 192.172.2 I

P lindy
to list and modify interfaces on host

ip addTo
see ipaddvener anigned to those interface

adds add
slip tipaddrescipr den interface name

To set ipaddresses on interfaces

The changes made will only till system restart


to persist these changes you must set them in

file etc network interface

Slip route route

deet ipelDR via


ip route add 1 gateway ip
used adding Entries to routing table
Ehsooting Ietf issues

When not able to


any site
are access
you
Reasons might be

1 Issue with local interface


check local interface by below command
slip link Ensure primary ip is up
2 host not resolving address
Cheill we
ip
can resolve hostname to Ip address usingend

ns lookup hostname Ensure valid ip


3 Tune with the route to the Server
hostname It not happen inve lies here
Ping
Trace route hipadd will show where connection is
lost from Server End
4 Issue with Seever itself
netstat an I gulp 80 I grep i listen
used to print info of network connections routing tables
and several other network statistics
check for port listening or not
Check for interface too

think pg interface down un below and to up

ip link set der hinterfaces up


5 Software Suey not functioning correctly
hosting
Eerily end II
Permissions

Linux Security

tiffin pitta stigity rafting Selinux Maisymore

A t
pq'ake
me and password
of usaccess based authentication
to determine who can system

LIM IPlugable Authentication Model


Another to Authenticate in Linux Normally wed
way
Authenticate users to programs and services in Linux

ELK byte
used to allow alien to services listening on the Linux Server
Normally we depend on firewall

It can be set
up in linux
by using tools such as
IPTables and finewall

SSI Idening
sste used to remote ai cen a serve over an unsecured
network
This will make sure
SSH Hardening only Authorized wees
gain access

makes un of security policies for isolating appsrunning


on same system from eachother wage
Agent
une in linux will have wee account Which has
Every
username and Password to
log into system
And also has unique identified VID

cat letelpasswd
will have user alcount details

will be based common attribute


Similarly
lineup on

cat lets group have groupaccountdetails


identifier
GID unique
username

THE
have many
The
GID
directory
Default shell
If not partofanygroup it
inomelusa
Ibin Sh
assign win as
mm

id username

vid xxx I 7 girl xxx f I groups xxxx Xxx

Superga agent
0 d am and control over mm

1
VIDEO
111
foot

created during Os installation usually


Wed by software and services that will not run at
super um
used ssh Mail UID 2100 On b w 500 1000
Latent
Same at system account created during service installati

Eg ngnix service acomet

id
gignan up groups part of

WEwill show who currently logged into system

Last
Displays record of all logged in weed

Eying
Su username
To Swith to other any in system
any
SV
I To switch to root urea

Instead you can me Sudo to me tommand a moot


user

55011
used to provideAdministrative accel
When treated wees we SUDO
prompted for theirpanned
They are

Default config for Sud is defined under

Eat letelsudoers onlywees in this can we


Sudo
Sudo configfile

cat letelsudoers
a

admin ALL CALL ALL

Sudo ALL CALL ALL

to used All CAIL ALL

finish Lays rnot


lusulbinshotgown

user group Hosts user command

ALL Lyolfity
Most of ACF are stored wider
Agone can we view
Only root canthodity
Modifying is ponible only by
builtin curds
letdpasswd Has basic info abt vers in system
UID GID Home directory
girish X 1001 1001 homegirish bin bash
username password UID 4117 GEcos Homeisin SH Ell
le te shadow stores panwords of woe
content are hashed
girish x x xxx xxxx x xxxx 10219 0 99999 7

USERNAME Password Lastchange minage maxage warn Inactive


Eupdate
lets group storeinfo of all group
gin and membell
developer x 1001 Bane

Groupname panword GID Groupmembers

Imaging yet
Create local user

useradd ausername To create user

passwi a username To create password for une

whoami To see use logged

Panwd To rent password

you can cure below tags along with undd


s
e customcommat specifyloginshells
d custom home dined
6 create me with multiple
e expiry date
specific GID secondary group
g
U Specific up

userdel username
To delete a wee

groupadd g 1011 developer

To create a grip with custom


gig
groupdel group name

LINUX FILE PERMISSIONS

Is I L filenames

by this longlisting
He know command we
get
details
of file
rwxowxrwx I A 89 mare 17 07 30 filename

Lets splitup
at
TWX TWX TWX

gives file type


1stcharacter

Regularfile
d Directory
e character device
I link
S SOCKETfile
p PIPE
b BLOCK DEVICE

TWX TWX TWX 47 Remaining denote Permission

Owned Group Others


U Gg

Bit Purpose octalvalue


8 Read U
W write 22
x execute 1
Permission
0444 To'd read and write

r 4 2 1 7 Read write and Emile

M X ut s read and execute


We 2 1 3 writeand Eneente

D X TWX Vox
Consider the owner accessing the above file He can't
access
Although he is present in group
Became an linux system identifies the any trying
to access tile direitchy and checks permissions sequentially

If any trying to access as owner Owner permission


are applied rest
ignored

IIyifying file Permission


Chmod t Permission filename
Syntax Ugo 1 Drax
Chmod Etrux flex
provide owners all access
Chmod ugo tr x files
provide read and Remove onecute to all
owners groupsand users
chmod O rwx Ifile
Remove all accell to other well

Chmod utrwx gtr o rwx


files
provide owners all accell group mad onlyaccey
and remove others all alien

Using Numeric
8 Chmod 777 file
All acred to owner group wet
Chmod 555 filly
read and Eruente access to owner group um
only
chmod 660 Lfiley
Chmod 750 a file

Modifying Ile Permission

known Lowney group filet


Chown townee f filey

chgrp Lgaoup file


SSH
He use this to login into and Execute commands on
remote computer

Ssh Lhostname ipaddrew for the command


to own Remoter
ssh

Ssh 1
user

fur
a Hostnamelipaddress

a Hostname ipaddrew
yserver should have
SSH Service running
in Port 22 accessible
from client

Should have valid user name and password

SSH port2222
user trengouteer

ClientLaptop

Reed In Sst
SSH key wed to login into machine without password

Create key
pair
Private key should only with client
Public
key Installed on remote server

o client SSH Port22 Remote


saved
Pubkey
For this to happen
i create a key pair

ssh keygen t rsa

Entre panphrase optional

tublay stored at 7 home user ssh id sa pub

Put key stored at home use 1 ssh id rsa

Ital Phd Ly En Rege Seay


ssh copy id user remoteSeevername ip
remote saver without password
Now you canaccel
ssh keys installed were present in below file

cat home wee ssh authorized keys

SEP
Cp allows copy files in directory within filesystem in linux

Scp allows copy file from local to remote webserver

Scp f pathof filedirectorytocopy Hostname path toplace


copied fileY
you have permission to write files in
should
destination otherwise command wont work
I Tables

As long SSH service is running on remote server you


should be able to connect to the system from client

1 To connect to remote server one should have


valid Authentication
user and password band
SSH and key bared

2 Network connection must be open for port 22 from


client to Seever

In normal Prod Env we have many clients routes


webservers it is important that we implement network
switches

security to allow or restrict access to various services


Such as
allowing SSH access from a specific IP a Network
This can be done by using firewall such as
CISCOASA
Juniper NGFW
Barracuda NOFlat
Fortinet
etc
using Network appliances we can control any traffic flowing
through the network

OR apply there rules at individual faves level


Iptables
firewall D in Linux system
firewalls in windows servers
implement EI I tably

Lets consider a client and 2 Savers are present


in a Network
As there are no firewall rules Every selves
can accel other
He don't want this to happen we want client
to accel only specific server and other Seever
can accel the different one

In server we use Iptables for access restriction


Centos and Redhat has Iptables preinstalled
for Ubuntu use Sudo apt install iptables

Sudo iptables I
To list default rules configured

Types of rules

chain Input Network traffic comming into system

chainforward Networkroute where data forwarded to otherdevice


innetwork

claimoutput Network traffic going out of system

It no rules added default policy is set to accept


all traffic allowed in out of kpten
it can multiple outer
called chain because
Its chain reeler
of
the package
If condition meets accepts
doesnt meet drop

A
Webserver
SSH port22
172 18020.20
172.18020.271

anorder to access webseries from A Hebseever must


configure input rule

uses websung tiptables A INPUT p top s Éciientiis dport 22 j Acer


option Description
AN Add rule
p protocol
S source
d Destination
dport Destination Port
J Action to take
sliptables d
Defaultly it accepts all inputs

iptables A Input P top dport 22 5 Drop

This rule drops ssh connections from all other servers


sthinespecified
until
any
Sequence of adding rules must be taken care

rule I topdown approach ruler will be considered


may 4 rule I statisfies it doesn't go to rules
iptables I output p top d IP address dport 443 j
Acce
rule at
t
the chain instead bottom
inserts the
topof
iptables D OUTPUT Positionnumber
1 213 415
To delete rule at gives position of iptable

netstat an I grep pots


will output the source and det ips connection
Established

EI JIB
Crow JOB When we need a particular script command

at some
given time regularly He can schedule the
job with date time and frequency without any
human intervention
This functionality is enabled by crond service earning
background

SILK Iob
To Schedule Job run below command from requried user

crontab e

m h dom mon dow command

There 5 fields are wed to specify the Enact schedule to


run task
next one is command to run

Don't une Sudo with Crontab command as Job


will be scheduled for root wee
Ex we need schedule Job on

10 00 AM 11th October

00 10 11 10
minute Four Tonth weekday
Tay
at wantto schedulejob onlywhen its
Monday Then set weekday as 1
Set weekday as A
value whatever
at indicates any
day it may be job will run

Set mouth rake I


To run job on all month on given day andtime

Similarly set value all the I


command

This command will run Every minute

12 command

This
is called step value

12 means Every 2min Same can be used

crontab I
To list cron jobs running
tail Ivar logsyslog
used To check whether Job ran successfully

SYSTEM D AID SERVICE MANAGEMENT

hats learn servicemanagement with systems


by creating
service unit from scratch

You have a shellscript located in your machine


Requirement This has to be started in background at
a service and enabled to start
during boot
for running script in background

He need to run as Service


He need to create service unit file
an location Pete systemd system Ksavianame service
Servicename Service

tserviceTI Semidefinatio
Execstart bin bash 198ft bashscript
most basic service can be built with this into
This is used to own command or an application
Ibinlbash as we are running bashscript

SystemCtl start Ksenianame service


will start the service

Systema status servicename service


will check and display status of service runningor not

servicename7 service
SystemAl Stop
will stop the service
Req service should start with all above depending
on default target graphical CLD
I install runlevel
Wanted This can be your required
By graphicaltargety al Systematarget
will allow service to be enabled during boot this section
will help

service should use the


Req given available service
account

Selvig
user Serviceaccounts

Req App should restart automatically on failure


Service
Restart on failure
will ensure that system attempts to restart theservice

Req If fails again it should bring upappafter specific


interval

Egesta see 10
will set time in seconds to wait before

the system attempts to restart it

Reg dog the service Events

With Systema the service Events are automatically logged


so req automatically taken care without any change in
service file
Req script above starts an appon machine but app depends
on other app service
Sothisserviceshould be upand running beforetheappstarts
Eun it
Description Service file configury these are not mandatory
Documentation through various
epos
After
T.it 9IjwfiT service will be running only
after the given service man

Systemctl daemon reload

will detect changes made in Service file


After the reload you can start serviceagain

ServicenamesService

Ionit
Description
Documentation

After viename 27 Service


Isee
Seenice
absolute path bashscriptto run
Enecstart binbash L of
Nsel serviceaccount andto run
Restart on failure
Reetaatsec 10
I install
wantedbygraphicaltarget
System.d Tools

SYSTEM
CTL JOURNALCTL
on systemd managed Seever thistoolcan
Query system journal
Manage systemstate
continient tool to
Start stop Reload Restart figure out
Enable Disable issues like service failure
list and manageunite
list and updateTargets

Systemctl start docker

Systemctl stop docker


Systemctl restart docker
This Will bring down service andthey bringup

Systemctl reload docker


will reload without intercepting normal functionality

Systemctl enable docker


To enable service and make it Persistent across reboot

Systemctl disable docker


To disable service at boot

Systemctl statue docker


provides info abt state of service
1 Active Service running

2 Inactive service stopped

3 failed crashed Timeout Envoy

4 Activating Deactivating
Systemctl daemon euload
Run this after making changes to service unit file
This will reload system manager config and makes
system aware
of changes

Running Service who config was changed can only


ran after above command

Systemctl edit Lsuvianame service full


will open configfile in txt editor
upon making changes There will be applied
automatically
yid command

Systemctl get default


will show current run level
graphicaltarget

Systemctl set default multi user target

Systemctl list units all


prints all active inactive failed unite

Journal Ctl
Itis useful when troubleshooting issueswith systems

Échecks journal de
log entries from all partsof the
system
Journalat
prints all logs entries from oldest to newest

Journalett b
To see logs with current boot

Journal U unitmamey service


Now data provided by log cutey will show

why Service failing


storage.IE
Bass Image
Blockdevice A type offilefound at de directory
It represents a pieceofhardware that store data
Traditional Harddisk SSD Examples of blockstorage
in Linux
BlockStorage Data is mad or written to it in blocks
or chunks ofspace
Isblk
NAME Majmin RM Size Ro Type Mountpoint

8 0 0 119.29 0 disk
SIsdal q I loom o past lbootlefi
Sda2 8 2 8 73G
Sela3 8 3 O yo g Ppi Imedialmaldata

is 1 Ident grep ab
g list index directoryand
filetype b
Blockdevice has major and mind number

Majdnumber Devicetype
RAM
is used identify
HD CDROM
6 ParallelPrinter typeof blockdevice
8 scsi Disk

Mindnumber are used to distinguish individual


physical logical devices

Partition

Entire device is divided into small usable spaces


called partitions
Salal Salaz Sda3
He can use each partition for specific function
It'srecommended to partition a disk as it offers greater
flexibility
Sudo fdisk I IdevSda
It ran be used to list the partition table
information and also to create and delete partition

Partitiontypes

PrimaryPartition a Type of Partition used to boot 05


Disks were limited 14 Primarypartitions

Extended Partition 7 Type


of partition that cannot beusedon its
own can host logicalpartitions
With restriction of 4 10partitions we can opt
to create extendedpartition and carve out logical
partitions inside it

Extendedpartition is like a disk drive in its own


right
This has Partition table pointing to 104more logical Partitions

LogicalPortions
There are partitions created within the
Extended partitions

Partyhemeftable
It define how a disk is partitioned
Scheme s MBR Master BootRecord
1 max 4 PrimaryPartitions
2 Max size peedisc 2TB

It more than y partitions required


then create 1 Extended portion and come out logicalPartition
within it
Scheme GPT Guldpartitiontable
More recent partition scheme created to addred
limition in MBR

can have unlimited no of partitions


This is limited by restrictions imposed by Os itself
RHFL allows max 128partition per disk
disk size limition dont exist
This Icheme is Best unten MBR is compulsory requirement

Eating Iitions
gdisk device path
Eg Idea Sdb
Run above command with devicepath as argument

Isk improved version


offetish Honks with GPTpartition table
Now Menu driven interface will be followed

Éommand I to help

Type n to create new portion

Pation number I

Size I
i Nexcode

fee all give command ME to write partition table


Idex SDB created
LINUX FILESYSTEM

I Partitioning the diskalone won't make


your disk
usable
in OS

Disks in paction are seen by Linux kernel as Raw Disk

To write to a disk partition Hemust

1 create filesystem
filesystem defines how data stored

2 Mount created file system to directory


Now we can read write data to it

comenlyLedfilesystems

1 Extended file system series from Entz to Enta

EX 2 EXT EXT U
max 2713 fileSize Max 2713fileSize 16TB filesize
YTBVolumesize up volume size I Enabyte
supports compression usesJournal uses Journal
Linux Permissions BackwardCompatible uses chksum for Jornal
longCrashRecovery Backward compatible
Exes as 2 72
Gmeans can be
mounted
mounted as ext3 bill

king with Exif


mkfs ext y Idex sdbl
devicepaths
create file system
mkdin Imnt ext y
Create directory to mount
mount Idex sdbl Imntlexty
now filesystem is mounted
by this command

mount I grep Idealsdbl


To check mounted
It hp I grep Idea say 8 not

To make mount available after system reboots add


an entry to the letelfstab
fief in Istafb
Filesystem filesystem Ide sdbl to mounted
Mount Directory to be mounted on mountpoint
point
Type En ext2 ext 3 exty
Options Such as RW Readwrite RO ReadOnly
Dumps O Ignore I take backup
Pass
I D Ignore 192 Feck filesystem check
Enforced

to back up
file using dumputility
Ganthet O disable backup
I take tack up J dumpnumter
7 Its priority set for filesystem check tool to
determine the order in which the fire system
should be checked during boot after a crash

O will ignore
1 max usually set for root files
External storage

Commonly und Enternal Storage

teeth
storage won'talways suffice our
onboard Tin
Normally
care of Enterprise grade serves Eux

Such as prod data HebSeever storing a lotof


data
So to get
away from this issue they make use of Enterprise
grade high capacity External storage with high availability

DAS Direct attached storage

NAS Network attached storage

SAN Storage Area Network


This uses fiber channel for providing highspeedstorage

Iftnanalstorage is attached directly to the hostsystem


that require space
Host will consider Das device at block device
No firewall If
713 No Network Das

Provides faster response than NAS


Affordable
As it is directly attached it is dedicated to singleserver

Not ideal in Enterprise Env's Where multiple servers


need storage
NetworkAttached storage
NIsuitable
to mid to large
Located
apart from host
datatraffic b w storage and host isthough Network

NFS
Hosta

Host t t
By
NAS file storage device and Das SAN are block storage

Storage is provided inform of directory


share i e physically present in NAS device
But exported via Nfs to hosts

This is ideal for centralized shared storage that


needs to be accessed simultaneously by different
hosts

Ethernet

MAIL.gg
huspeed

This is weed
for Backend Storage for webservers or
app servers
OS installing not recorded
Network
storage Area
Ed
Provides blonk storage used enterprise for
by
business critical
apps that need to deliver
high throughput and low latency

Storage is allocated to Hosts in form of LUN logicalunitnumb

Range of blocks provisioned from a pool of sharedstorage


and presented to the server as a logical disk

Host will detect there as raw disk He can create


partitions and file systems on top of it as we do
on block device
any
And mount on servers to use

SAN can be Ethernetbased was FCP fiberchannelproton


Fop High speed data transfer protocol

Fcp uses fiber channel Switch to Establish


communication with host
Hosts use HBA Host Bus Adapter Connected to the
Pal Slot to interface with fiber channelswitch

SAN performs hotter in hosting mission critical appsthan NAS

lay install Oracle DB MSQLDB


using for virtualization deployments like VMware Kym
a microsoft Hyper X
SAN

j
T
it
Host B

IN FS Network File System

at not like block devices


Stores data in file
Works on Seaver client Model

Consider software
repo Seever
directsoftware repo exists on reposerver
I
This repo is shared over the network using NFS to
clients on laptops
client
NFSSeever software up

Fiat
Mnt software epos

software repos
Tent
tmntsoftware repos
Tam fol directly sharing in NFS
Emporting

Once repo mounted can be used as any other


File system in OS

5 mom
This defiens client that should be able to
access directory on the Selvey

software repos client


ipf
2Hostname
client ip client ip

firewall between
Ideally there will be Network
the NFS Server and clients
So specific ports might be opened b w NFS and
client for solution to work

empatts a
exports all the mounts defined in the
letelenports file
emportfs O client IP softwarerepos

In our local we should haveto use below

Mount 10.61 112.101 software repos Imnt software repo


XNFS IP K Seever repo tsocal repo
mountpoint
Logical volume Manager LUM

This allows grouping of multiple physical volumes into a


Volume group
from this volume group logical volumes are
carved out

Logicalvolumes
Voll 1012 4013
5413 5913 5GB

volumeGroup

FI E TE
Idevisial Ideutsdal Idrisbdl
Physicalvolumes

Lum allows logicalvolumes to resize dynamically till the volume


available in volumegroup

On systems such as our laptops you can have filesystem


such as home VAR Trap created ontopof Lum managed Modules

aptget install tums


To use him above pakage needs to be installed

Steps Lofigying Ling


1 Identify free disk partition Nowcreate Physicalvolume object

Physical volumeobject is how Lum identifies a disk 8


a partition
Create Pv using unused disk

pncreate AlexIsdb
Fund discs
2 create a volumegroup using belowcommand

v6 create Girish99 deviselb


A volume group can have one morephysical volumes

Pvdisplay
volumes names
It lists all the physical sizes

V6 s created
Vgdisplay
displays all Prs partof v6 and diskspace used

5 Create logicalvolume using below command

Increate K 19 n volt girishgg

L linearvolume
most common volumetype
Enables us to use multiple physical volumes available
to create single logical volume
exdisplay
is to list volume
us
Another
way to list volume and lists
V6 it is partof

4 Createfilesystem inside 44 once Lu is created

mkfs.extyldevlgivish.gg you
5 Mount it
mount t extyldevlgirish.gg vo2Imntlyoll

Now Lure can be used


KIELY
91 check storage of 9

lyresize L 19 n Ideagirishgg vod


will increasethe volumeof LV
19 Additional lab added
Nowupon df hp tmnt you
Still have only 1GB
This is because only Lx resized not filesystem

resizezfs Idea girish gg voll


In order to resize not stopping on unmounting required
it can be done on fly
Now elf hp mount voll
output will Show 2GB
girish 9g Yo

logicalvolume Path Logicalvolumes with um an

31,1
ldevlgivish.gg voll
2 accessible at 2places

You might also like