107
RHCSA in Redhat 7 – by Navdeep Singh Jimmy Chapter 1:- Time and Date Configuration. You might be thinking about why &what is the use of date and time in while using REDHAT in CLI (Command Line Interface) mode but actually all commands which we use in Linux are run according to date and time and also logs that are created, So you should know how to see and configure date and time in Redhat 7. Lets Start With Time: There are Two Types of clocks: a) Real Time Clock(RTC) :- It has different names hardware clock, CMOS, RTC. As you know CMOS is a cell i.e integrated on Circuit board of system (Motherboard) that keeps tracking the time when is turned off but not when system is in running state. b) System Clock: It also knows as Kernal clock, Software clock. This clock initialized from the RTC at boot time. We can say that it is software counter based on the timer based interrupt. It only exists on run time of system. You don’t need to understand about how both works in backend. Your work is to do Configuration :- timedatectl: It is a utility by which you can configure time and date in Redhat7 and this utility is the part of systemd. Before that date and hwclock was used. Still we can use both. But this new command timedatectl shows everything such as : Local time, Universal Time, Zone, Last change and Next DST change time, NTP(Network Change Protocol). timedatectl (It will show you whole aspects of time and date) #Way to change the Current time and Default format is HH:MM:SS timedatectl set-time 23:26:00 (In other old versions date –set and hwclock –systohc were used) #To Enable or Disable RTC timedatectl set-local-rtc yes or y or true or 1 (for enabling the rtc) timedatectl set-local-rtc no or n or false or 0

Redhat 6 & 7

Embed Size (px)

Citation preview

Page 1: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Chapter 1:- Time and Date Configuration. You might be thinking about why &what is the use of date and time in while using REDHAT in CLI (Command Line Interface) mode but actually all commands which we use in Linux are run according to date and time and also logs that are created, So you should know how to see and configure date and time in Redhat 7.

Lets Start With Time:

There are Two Types of clocks:

a) Real Time Clock(RTC) :- It has different names hardware clock, CMOS, RTC. As you know CMOS is a cell i.e integrated on Circuit board of system (Motherboard) that keeps tracking the time when is turned off but not when system is in running state.

b) System Clock: It also knows as Kernal clock, Software clock. This clock initialized from the RTC at boot time. We can say that it is software counter based on the timer based interrupt. It only exists on run time of system.

You don’t need to understand about how both works in backend. Your work is to do Configuration :-

Ø timedatectl: It is a utility by which you can configure time and date in Redhat7 and this utility is the part of systemd. Before that date and hwclock was used. Still we can use both. But this new command timedatectl shows everything such as : Local time, Universal Time, Zone, Last change and Next DST change time, NTP(Network Change Protocol).

timedatectl

(It will show you whole aspects of time and date)

#Way to change the Current time and Default format is HH:MM:SS

timedatectl set-time 23:26:00

(In other old versions date –set and hwclock –systohc were used)

#To Enable or Disable RTC

timedatectl set-local-rtc yes or y or true or 1

(for enabling the rtc)

timedatectl set-local-rtc no or n or false or 0

Page 2: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Date Configuration:-

By default format of Date is YYYY-MM-DD

timedatectl set-time ‘2015-30-06 20:59:00’

List of zones and Changing the time Zone:-

timedatectl list-timezones

timedatectl set-timezone Asia/Kolkata

To Enable or Disable NTP(Network Time Protocol).

It is used to synchronizing the system clock with a remote server. For enabling the NTP ,You have to enable one service chronyd or ntpd.

(You no need to enable it for now anyway this command is used , Will practice It after Lesson Managing and Controlling Services).

Timedatectl set-ntp yes (by default it is ON)

Timedatectl set-ntp no (disable)

Changing date by Date utility:-

date (To show current date and time)

date- - utc (utc current date and time)

date - -set HH:MM:SS (replace HH:MM:SS with two digit numeric value 11:10:00)

date - - set YYYY:MM:DD (replace YYYY:MM:DD with numeric value such as 2015:30:06)

Using hwclock:- Note : hardware clock always synconize with software clock in every 11 minutes.

hwclock (to check hardware clock time)

hwclock - - set - - date “dd mm yyyy HH:MM” - -utc (06 June 2015 11:16)

(Keep hwclock in UTC)

Sync Hardware time and date with :-

Page 3: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

hwclock - -systohc Sync Sytem Time from hardware time hwclock - -hctosys

With Local Time:-

hwclock - -systohc - -localtime

Best way to watch time with seconds and also date

Watch –n 1 time

Page 4: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Chapter 2: Ls,rm,mv, and other basic commands:- To see the list or to see how many files and directories :

Ls

Or you can use its will show without color that differentiate files and directory:

dir

With permissions :-

Ls –l

Using logics

Ls *0 (will show you entire files ending with zero)

Ls *jimmy* (will show only those directories and files which consist only this jimmy)

Ls –lv (this flag shows you total number of files and their links )

Ls –la (-la or –a shows you hidden files)

Ls –lh (-lh makes files human read able ,it means size of file will in kb`s and mb`s or gb`s)

Ls –F (it will add ‘/ ’ after directory that makes easy to differentiate directory and files)

Ls –r (reverse order)

Ls –R (will append sub directories inside directory)

Ls –ltr (latest modification files with date and times)

Ls –lS (S will show big size file first)

Ls –lvi (links and inode number)

ls / 2> error( 2> will store error of file only)

Changing directory

Cd / (will go in top level directory)

Cd ~ (using tilt will jump in home directory of current user ) cd directoryname (enter directory ,press tab it will complete the name or show dependencies in which directory you wanna go)

Mkdir directoryname (making one directory)

Mkdir directoryname directoryname (multiple directories at a time)

Mkdir –p dir1/dir2/dir3 (-p will helps you to create parent or structure of directory )

Page 5: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Cd .. (back one diretory)

Pwd (it will show present working directory)

Cp source destination (destination should be path of directory)

Cp –a sourcename destinationname (copying entire directory tree)

Cp –u (which prevents overwriting identically newer files)

Cp * directoryname (all files and directories from your present working directory)

Cp -R soruce destination ( -R used for sending rescursilvely to sub directory)

Cp –r source destination (will not give you error of omitting directory)

Cp –f source destination (force file copy)

Cp –i source directory (-I for user prompt )

Cp –l source destination (hardlinks of file instead of copy)

Cp –L soruce destinationfile (copy and create symbolic link (shortcut of main file))

Cp –n source destination (no file overwrite )

Cp –v source destination (-v used to see files copying or not)

Cp - -attributes-only sorucefile destinationfile (copying its all attributes )

Mv filename newnameoffile (changing file name)

Mv sourcename destinationname (file you wanna move one directory from other)

Mv –f sorucefile destinationname (-f used to force fully change)

Rm filename (deleting a file)

Rm –d directoryname (by this you can delete directory)

Rm –rf directoryname (this rf will remove all files from directory structure forcefully)

Rmdir directoryname (removing directory ,only empty directory)

! (just this sign will points history by this !commandname you can run your command i.e executed before ),

!! only last command

Ctrl+r (will give command search in History)

Rm –rfv path or direcrtory (v will show you whats it deleted)

Page 6: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Editing or creating a file :-

Touch filename (create empty file)

Touch file1 file2 (create multiple files )

Touch jimmy{1..10} It will creat 10 files with jimmy name . jimmy1 jimm2 upto 10 .

Cat > filename

Write you contents ………………………………………..

Press ctrl+c (saving a file )

#Appending file content

Cat >> existing file name

Write your content

Press ctrl+c (save it )

#way to see txt file contents

Cat filename

cat 123.txt 456.txt > 123456.txt ( creates new catenated file ,means both files output will be in new file)

Ps ( services or programs that are running by user )

Uname –a (kernel version and other information about version of redhat version in which you`re working on)

tty ( reveals the current terminal)

whoami (currently logged in user)

which (reveals where in the search path a program is located)

clear (clears the screen or terminal)

set ( prints and optionally sets shell variables ,means shell default infromation)

reset ( resets the screen buffer)

history (reveals your command history)

stat filename ( reveals statistics or attrinutes of files)

Page 7: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

alias copy=cp (by this you can create your own tags move=mv or h=history )

du –h /directory (it will tell size of files)

expand filename > newfilename (expand will remove the tabs in file content) Linux Redirection & Pipes Features: 1. Ability to control input and output Input redirection '<':

1. cat < 123.txt Note: Use input redirection when program does NOT default to file as input Output redirection '>':

1. cat 123.txt > onetwothree.txt Note: Default nature is to:

1. Clobber the target file 2. Populate with information from input stream

Append redirection '>>':

1. cat 123.txt >> numbers.txt - creates 'numbers.txt' if it doesn't exist, or appends if it does 2. cat 456.txt >> numbers.txt

Pipes '|': Features: Connects the output stream of one command to the input stream of a subsequent command

1. cat 123.txt | sort (first output would be second`s input) Other commands su username (if there will no username then it will take it as a root) head filename (displays opening lines of text files) tail filename (displays the closing lines of text files) wc filename ( counts words and optionally lines of text files) –c char, -l lines, -s string file filename ( determines file type) who (command simply return user name, date, time and host information) Free (command shows free, total and swap memory information in bytes.) lsof (mean List of all open files) chvt 1 or 2 (going into gUI or CLI mode ) bc (calculator) to exit ESC eject –t (to insert writer eject) cut –f 2 –d : filename (-f field number –d seprater : filename file such as: abc:def so that will cut entire 2 field and –d “:” it can be anything )

Page 8: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Chapter 3: Vi editor & Searching:- Vi editor is interface by which you can edit your files and create new one also. Its configuration files used to stored in Home directory of login user in hidden mode. Such as :- .vimrc (in this file ,whatever we write ,it will execute when we will open vi editor)

Way to get out of mode press escape

There are three main things that you must know about VI editor.

Insert Mode

Command Mode

Exit Mode

a) Insert Mode:- It means you wanna write content or add but for that you have to enter in insert mode in new file or old file that you`re modifying For this there are three keys.

a (by pressing a you will be in insert mode one character ahead from the place your cursor is )

A (by A , you will write end of the line )

o(it will generate new line below the current line)

O(it will add new line or generate above current line )

i(where your cursor is )

b) Command Mode:- take your coursor on some line and press cc but keep in mind don’t get into inset mode. Cc Cut line and shift +d also Yy copy line P paste Dd delete line Dw deleting word u undo ctrl + r (redo) g (jump to last line) gg (jump to first line) deleting 5 lines from belowcurosor press 5 dd same for copy 5 yy same for cut 5 cc

c) Execute Mode:- enter in execute mode by pressing “ : “

Adding number in file:-

Page 9: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Se nu

Q! (quit without saving)

Wq (quit with saving)

#searching a word

/wordtosearch (for next word n and for previous N)

#replacing a word

/%s/wordtorepace/word/g (g globally it change all the words)

:!which uptime (! This symbol also know as bang and it helps to run a command when in shell without quitting vi which is command that tells path of uptime command )

d) Replace Mode:-

Double press insert button from keyboard and get into replace mode.just type and it will replace automatically with the word or line you`re type

e)Visual Mode:- in visual mode you can select it . for this press v to get into visual mode.

Select mode and by yy or cc you can cut particular line .

#Non –modifable file

Vi –m filename

Vi –R filename (file will be non-modifiable by using :w!)

Vi –n filename (don’t use it for swap file for backup)

Vi –r filename (recover data)

# creating encrypting file :-

Vim –x filename

And changing password

:set key=newpassword or clearing password set key= (enter )

### cursor movements

H to left

L to right

Page 10: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

J to down

K to up

##if you want add any command in VM run time ,

e.g:

Vi /etc/vimrc

Set se nu

Page 11: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Chapter 4: Finding & Searching Files :- 1: Find :- this command used for both files and directories .

Find / -name nameoffileordirectory (/ path where you wanna search , -name is peramter )

Find / -iname nameoffind (-iname used for ignoring case sensitive )

Find / -mtime +8 -mtime -13 (defining days)

Find / -name filename –ls (-ls will show give you o/p same as ls)

Find / -size +1M (minimum 1mb or greater than that)

Find / -type d –newer filename (d used for directory and newer used for condition means directory should be newer that filename you mentioned there)

Find / -exec file {} \; (file will tell you which kind file it is and –exec used for add other command with find )

Find / -perm 766 (it will give those files which having 766 read write execution permissions)

Find / -group groupname -name filename

#to run two commands at one time

find . -exec grep foo {} + will show you output like this ./dir/file.py:from foo import bar

find . -exec grep foo {} \; will show you output like this from foo import bar

find . -exec grep -l foo {} + will show you output like this ./dir/file.py

find . -exec grep -l foo {} \; will show you output like this ./dir/file.py

2. locate :- its another way to search files that matches pattern or filename that you will mention with it . but before that you have update your database with updatedb

Locate filename

Page 12: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Chapter 5: Managing User and Groups Default user of Linux is “root” and according to requirement we can create more users . We can create total that are reserved by system at now starts with 1000 and groups users 60,000. Whenever we create a user its data or in other words System created its HOME directory in root “/HOME”. “ /” it is top level directory in Redhat or any other version of linux. These are Physical accounts on system that we created. There are so many reasons creating of users By creating particular user we can assign some permissions to it and some application access. Every user associated with UID i.e unique numerical identification number or user ID. List of all groups stored in “/etc/group” configuration file.

There are three kind of users :-

Supreme user (Root) UID 0 GUID 0 /root (its home directory)

Normal user /Custom User (created by us which has limited permissions i.e given by root) UID 1000 GUID 1000 but in Redhat 6 it started with 500 or above /home/username (home directory)

System User (we can`t login with this, its by the system or package and for the system) less than 1-999 in redhat 7 and in redhat 6 it was less than 1-499.

Vi /etc/defaults/useradd (main file ,it carry what user gets defiantly )

There are three main files whics helps to create user :-

Ls –a /etc/skel

.bash_logout (helps to logout)

.bash_profile (creating home directory of user)

.bashrc (helps to login)

Creating a file or directory and checking its default permissions:

mkdir dir1 (Empty directory on that path where you`re working and that can check by “pwd” command)

ls –l (this command will show you permissions, I will tell you later how and why these permissions changed)

Check default permission set by user:-

Umask (default umask is 022 i.e configured from “/etc/bashrc” its shows who can modification in a file or directory unless in UPG i.e user private group this is not necessary since every group has own private group ).

There are two command by those two we can create user & group and give password to particular user:-

Page 13: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Usermodname of user (modification particular user its settings)

Useraddname of user (adding user )

Userdel name of user (deleting partocular user)

Userdel –r nameofuser (wil delete home directory also)

Groups: Whenever we create a user ,system creates automatically Group with same name we have created a user and This user is Primary Member of that Group or primary group and it is also know as UPG i.e user private group . Its structure uses Inheritance method but we can assign to other user and make it Primary.it carry same permission that user (Primary user) have. It associated with GID i.e group ID. A Primary user who creates a particular file that can be own by group ,Technically group is also owner of that file which is created by Primary user of that user.

Note: “root” can change permission (read ,write , execute or can make a file accessible to particular member of a group this is done by ACL i.e Access Control Lists, we will do that later ).

Gourps enteries :-

/etc/groups

Groupname:maskpasswrd:gid:members

and its password . /etc/gshadow

Groupadd (adding group by this not members)

Groupmod (Modifying group)

Groupdel (deleting group)

Gpasswd (adding password to group)

#way to check members and groups:-

Groups username

#changing primary group :-

Usermod –g newgroupname username

#adding secondary group:-

Usermod –G secondarygroupname username

Groups username

Id username

#adding more than two groups in a user.

Page 14: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Usermod –a –G newgroupname username

#changing group name

Groupmod –n newgroupname oldgroupname

Password or Shadow Password to user:- In Multiple user environment ,its every important to use a password on your user account by that other user cant access your account. It can be done by “shadow-utils” package (first enable this). We can do this by configuration file where shadow-utils stores or passwd command. Password would be encrypted.

/etc/passwd and (only root user can read both files) it store other options about user and of user

Open this file you will see something like this :

Username:x(its password):UID:GID:comment:homedirectory:shellname

Shadow file stores the password:

/etc/shadow

Username:password: :minmumdays:maxdays:inform to admin about password gonna expire:

Other login polocies are stored in :- /etc/login.defs (passwd polices and passwd file polcies)

Other utilities that can enhance the user privacy and security:-

Chage

By using chage utility we can add login period for user means he/she can access it for few minutes ,days, months or some login attempts . it all comes under Password Security.

Gpasswd(This utility for root for group password i.e stored in “/etc/groups”).

Verification of passwords ,group and associated shadow files.

Pwck, grpck

Way to convert shadow file to passwd and passwd file to shadow. (coversion)

Pwconv (passwd to shadow)

Pwunconv (shadow to passwd)

Coversion of shadow utility for groups:-

Grpconv and grpunconv

Examples and Scenario`s:-

Page 15: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Useradd [option] username (Replace username with any name and option with flags that are given below )

Useradd –s /sbin/nologin uk

Usermod –c ukumar uk or useradd –c “navdeep singh” jimmy

Useradd –g username (represents primary group which is created when we created user)

-c comment

-d home_directory

-e date (date when account expires and format is YYYY-MM-DD)

-f days (Number of date password that is given to user expires)

-g group_name(Group name or group number for the default user)

-G group_list (group names or group numbers seprated by commas ,of which the user is a member,Group must exists )

-m (if there is no home directory)

-M (Don`t create home directory)

-N (Don’t create user private group )

-p password (encrypted with crypt)

-r (create a system account with UID less than 1000 and without a home directory)

-s (user login shell)

-u uid (User id and must be unique and greater than 999)

Note:- usermod command same as this ,in usermod you have add –a for adding group

Before other examples you have to know about how user stores in /etc/passwd file.

Username:x:uid:guid:Primaryuser:homedirectory:shell

Useradd –u 1001 username (id should be more than 1000 because other reserved for system)

Username –u 1001 username –g 50001 groupname –d changehomedirectory

Userdel username or groupname with primary username

Same for groups but it will create group member within primary user in which you`re login

Groupadd nameofmember

Page 16: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Groupdel nameofmember

Su or root commands are known as System Administrator commands. There are so many tasks that can only perform by root only for that sometimes we have to login into user from our other working shell from other physical account.

Su (su is the command for entering into root directly and after that you have to enter password of root if there is any.)

There a is another way , As I told you before there are few GUID i.e carry or reversed by root ,So for becoming member of root there is group name called wheel (it is special tag )

Usermod –G wheel username (username should exists physically on system and –G for group list i.e of root)

Or give it UID-0 GID-0.

Or Open visudors or /etc/sudo/sudors.

Configure its permissions.

#if you want any users permissions :-

Chage –l username

#if you wanna know by which user you logged in:-

Whoami

#check the id of logged user

Id

#check your users groups:-

Groups

#last reboot check:-

last

#gui add delete user or group

System-config-users

#####REdhat 7 New:-

Loginctl

##user sessions:

Loginctl int-session

Page 17: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Loginctl show-users username

##other options :-

Man loginctl

Page 18: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Chapter 6 : Hard Links and soft Links First of all you should know about “INode working”. You may think what is inode , inode is a block or you can say sector of harddisk where your data stores.

Actually there are three things :- Super block ,Inode Block, Data Block.

Super blocks consists,type of file system and size and other things of harddisk and operating system.

InodeBlock or Inode table:- It carry information about file ,when you see file`s properties then it shows , owner of file and other permissions. Actually inode refers to Data block which means where our actual file is and store. When you recover your deleted or damaged it ,Inode stores and it and restores it .

When you do :- ls –l

It also shows links of files at just right side or Permissions.

Soft Links :- shortcut of file .

Hardlinks :- actual file with different name on other side of harddisk or some other path but it consists same inode of its copy.

Creating Softlinks:-

Ls –n targetfile srcfile

#to check inode of a file:-

Ls –li (first column is inode of file)

(srcfile will may consist a new inode but that inode points to main file ,I means its path)

Hardlinks:-

Ln targetfile srcfile

(here one inode and three copies of file with different names , but it not take directory as a hardlink)

Page 19: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Chapter 7:User Permissions every file or directory has their permissions for users. Those are defined into their context menu or properties.

Ls –l / (you can check it” / “ path of directory)

It would be something like that :-

dwrx-r-r actually it is user= wrx group = wrx anyone=wrx first d represents to directory. or in numeric value 4= read, 2=write , 1=execute

When you create a file or directory ,it got permission automatically ,it because of umask. Umask is system file that is configured by system.

Check your umask by :-

Umask (default umask is 0022) root and normal user gets 0002

You can change umask by

Umask 0777 or anything that makes sense to you. Means if you set :-

Umask 0777 it means user group and others will get all permissions but in rich administration you will allow this .

Umask 0740 that would be better.

You might be thinking why 7 . it means user= read i.e 4 and write i.e 2 and execute i.e 1. So it become 7 .make sense right!

For particular file or directory :-

Chmod 740 filename or directory name

There is another way to add and delete permissions

Chmod g+r filename or directory name (it means group will get add read permission in its old permission set)

Its simple: user:groups:others or you wanna give permission to all use “a”

#suppose I have executable file and that is dangerous for other users and groups then I `ll add.

Chmod u+wrx,g-xw,o-wx filename or directory name

Chmod u-x,g+xw,o+xw filename or directoryname

Page 20: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

OwnerShip

Chown ownername newowner

Attributes

Lsattr and chattr to change attributes of file and folder.

You can check it by “man lsattr” it Is used to see attributes i.e is set by chattr

Lsattr –v (it will show version number)

Chattr +a filename (a append only,it means file can only append not delete or modify) to remove add –a

Chattr –i filename (by this you cant append not even copy a file) and +I to remove it

Lsattr

By attributes you can add and change some permission of file.

Page 21: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

ACL access control list

Getfacl and setfacl :- both helps us to give control over file by this we can give permission to those users who are not even member of our group.

# to see permission

Getfacl filename

#to set permission check it by man setfacl

Suppose you have two group teachers and Students

And you created one directory with name Foo/ and inside that bar and secret.txt . So here you wanna give permission to teachers that can access foo but not bar and students can access both. But before that I wanna took all access of groups and others:-

Chmod 700 foo

Now adding permission.

Setfacl –Rdm g:students:rwx foo/ (r recursively that will give same permission to directory that is inside foo/ and d default permissions m modify)

Setfacl -rm g:students:rwx foo/ (here we are giving permissions to files that are inside foo directory for students)

Setfacl –dm g:teachers:rwx foo/ (teachers can access foo)

Setfacl –m g:teachers:rwx foo/secret.txt (also to file but not to any directory)

This is it . you can check it by

getfacl foo/

Page 22: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

SUID ,SGID ,StickyBit NOTE: SUID takes 4 SGUID takes 3 and Stickybit 1 os if you add 1777 it means stickybit

SUID:- set user id ,which means some script that you have created should used by root or some other users. That’s why we created other users ,for particular work.

Check the attributes of a file by ls –l if it is like that :-

-rwxr-xr-x it means groups own the execution permission

For more under standing

-user-group-all and read=4 write=2 execute=1

Set user id will change the root permission or for particular file it would look like this:-

-rwsr-xr-x

S(stands for suid it means only root can use it )

Numeric value is 4000 chmod 4000 filename or chmod u+s filename to change the permission.

# Suppose we have three users (only use on directories)

A b c of root.

So it means a can write or delete the contents of b and c .

For more check by this ls –l

-user-group-all user1 user1 (first user indicates user and second group)

Chmod g+s groupnameb

Ls –l (there will be s in groups)

## create an enviorment where only member or group can change the file or from directory which created or owner of a file .

It means person would be delete something from directory. So add stickybit.

Chmod +t directoryname (applies on directory)

By adding t only who is owner of directory can modify it.

If we add 7777 on file or directory permission would be:-

Rws rws rwt

Page 23: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Chapter 8: File Structure of LINUX. ~ users home directory

/ Most top of directory

Root home directory of root user

Home contains the user home directory along with directory for services that contains services files of

Particular user.

Bin it holds the command for the end user only

Boot kernel ,bootloader and other files and modules are stored

Dev it stores all hardware related files.

Etc it stores all configuration files

Lib it contains library files that provide link bw actual service with user ,you can see that with

Systemctl –l status servicename

Lost+found it stores log files of a physical drive . when you run ls –a you can see that or when

You do partition and after mounting ,you can see that then.

Media all removeable devise are accessed from here,you can say it maps all devices

Misc&opt miscellenous & optional that are very hardly used by system for some purpose,otherwise will store anything.log or any tmp files

Mnt whenever you wanna mount something you can mount it here ,this is free to use.

Proc it stores all id`s of processes`s .Kernal reads everything from here.

Net sharing data over groups and networks , but by default is blank.

Sbin it store selinux i.e advance security of linux and it stores commands that are only for root

Selinux it stores policies of selinux

Sys it contains running system information

Tmp temporary files

Usr it stores all utilities that you install in your system ,you can say it stores so much than other directories

Var it stores all logs,queue and other events and services links and it also consists all man pages.

Bin it stores troubleshooting commands and maintance

Page 24: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Chapter 9 :Partitioning in Linux Creating Simple Partition :-

Step 1: Check free space and check how many harddisk`s are attached with system.

P p p p

P p p e

P p e e

P p e e

This is how you can create extended partition and primary partition. After creating extended you will get option of logical partition.

First check how many harddisk are attached with

Cat /proc/partitions

Fdisk –cul /dev/sda (sda is master harddisk sdb master slave another 3rd hdd would be secondary master (sdc) ,4th hdd secondary slave(sdd) )

Check the current layout of Storage.

Fdisk –l (list of harddisk and partitions)

Fdisk –cul /dev/yourharddisk

Fdisk (press enter for using this utility to create new partiton)

Then press m for menu .

Now create it by pressing n . after that enter again for default starting value of block. Then size +100M (mb or G for GB k for KB )

Now write that partition in partition table by pressing w after that enter.

Now you have created partition but not drive but you need to restart your system to send this information to kernel or else.

Partprobe (enter ,it will send information of new partition to kernel without restarting system)

Now check.

Cat /proc/partitions

Partition will be here in this file but Now you have to create drive of partition you have created.

By this command:-

Format it:-

Mkfs.ext4 /dev/yourpartition

Page 25: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Now your partition fully formatted

Now you can mount it or label to it .. Label represents the name of drive.

For check its inode and label and othet blocks information .

Tune2fs –l /dev/yourpartitionname

Label to drive:-

E2label /dev/yourparttionname namehere

Again use tune2fs , Now you will see label of drive

Mounting:-

Mkdir drive

Mount /dev/yourpartitionname drive (place of drive you can add any path of directory where you wanna mount you drive)

Its temporary mounting. For making it permanent you have add your partition and where it mounted information in fstab.

Vi /etc/fstab

Append this :-

/dev/yourpartitionname Yourmounteddirectoryname ext4 defaults 0 0

Save this file and reboot your system , Here you can use and see you drive permanently ,to see where it mounted or not !

Mount (write it and press enter )

Page 26: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Encrypted Drive In linux using Cryptab and luks.

Cryptab is a utiloity and luks represents Logical Volume .

First create a partition with fdisk (don’t format it).

Cryptab luksFormat /dev/yourpartition (it will ask you password that you wanna give to your partition)

Cryptab luksOpon /dev/yourpartion name arguename(name is temporary via you can access it further)

Now format it for use and Mount but first check where it opened . /dev/mapper/name

Mkfs.ext4 /dev/mapper/name

Mount –t ext4 /dev/mapper/name /mnt (you can change it /mnt ,give any directory path here . –t temporary mounting )

Umount /mnt (for not to use)

Now close it :-

Cryptsetup luksClose /dev/mapper/name

You can use it at booting time for this :-

Vi /etc/cryptab

/mnt /dev/mapper/secret (write this is cryptab file and save it )

And

Vi /etc/fstab

/dev/partitionname /mnt ext4 defaults 1 2

#adding key

cryptsetup luksAddKey /dev/vg/lvnname /etc/keyfile

chmod 400 /etc/keyfile

vi /etc/crypttab

crypt /dev/vg/crypt /etc/keyfile

Page 27: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Swap Partition:- Parted –l (it will give you list of all harddisks and partitions)

#Check virtual and physical memory (RAM )

Free –m

#check which swap memory is on and use.

Swapon –s

Create a partition with 82 Id ,means swap partition with fdisk

Now add it in fstab .

Now

Mkswap /dev/partition

Now start it

Swap –a /dev/partitionname

Check it shows in :-

Free –m

For Off the swap partition

Swapoff /dev/partition

Check again

Free –m

Page 28: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

# Extended drive and LVM.

First create extended partition then you will able to create logical partition after that logical physical volume and after that logical volume group and LVM logical volume and you can mount it with ext4 file system.

But we can create only 3 partitions logical partitions with the use of fdisk . First create one extended partition then after that create Logical , After that change type of partition that’s hex code is 8e Linux LVM.

Pvdisplay

Lgdisplay

lvdisplay

After creating of Logical Partition Now create LVM physical partition with :-

Pvcreate /dev/logicalpartitionname

After that create lvm_volume_group (for this you have create more than 1 lvm physical partition)after create 2 or more than that :-

Pvs (it will show you ,you attach any partition to volume group or not)

Vgcreate vg1 /dev/logicalpartitionname /devlogicalpartitionname2 (vg1 name of group and two partitions that would be part of LVM group)

Vgs (it will show you volume group)

After that creating LVM Logical Volume.

It means One LVM logical Volume over LVM group.

Lvcreate –l 100%FREE vg1 –n lv1 (use 100% space of v0g1- volume group that we have created and create lvm logical volume whose name would be lv1).

Lvs (to check lvm logical volume)

Now format it as ext4.

Mkfs.ext4 /dev/vg1/lv1

Now you can mount it . with mount command that you already did.

But here is something diffrenet you can do .

Open fstab :-

/dev/vg1/lv1 whereuwannamunt ext4 defaults 0 0

Now after that type

Page 29: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Mount –a (which you tell that fstab having all entries)

You can check it by entering “mount”

Check the path you mounted lv1

Df –h /path_where_you_mounted_lv1

#now extend the lvm volume group.

Pvs (it will show that lvm attached to any volume group or not )

Vgextend vg1 /dev/lvmphysicalvolume

Vgs

Now extend Logical Volume :-

Lvextend /dev/vg1/lv1 100%VG or lvextend –size +60G /dev/lv

But after checking

Df –h /pathyoumounted

It will show you same size of your lv1 but for that :-

Resize2fs /dev/vg1/lv1 (it will refresh the size of your logical volume)

Df –h /dev/vg1/lv1

#removing lv vg and pv

Lvremove /dev/vg1/lv1

Vgremove /dev/vg1

Pvremove /dev/partition name

Page 30: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Quota Permissions:-

Quota permissions are disk permissions.it means how much size a user can use from or of the harddisk . In simple words we can add some reserved space of partition.

e.g skydrive ,onedrive they give us some space Right! Such as 30 gb or example of dropbox 5 gb or 2 gb. Same as hosting over internet. 100GB space. That’s what quota is.

There are two types of Quota:-

Disk Quota or block wise

File Quota or index or index quota.

1 Disk or block wise Quota:- its all about space of partition . in quota we can divide 10 gb space in multiple users.

There are three things in quota:-

Soft limit (it will alert to root user it will alert when space full or user need more space)

Hard limit (if 3gb full and 2 gb left it will alert and create log file to user and give the alert when 5 gb over .. space limit exceed)

Grace Period (if user gets 1gb more space for 7 days for emptying older data or reduce it to limit size ,if he/she will not then disk that1 gb will denied)

2. file or index or inode index:- basically inode store the size and other meta data about files. If we say a user can use 10 inode over drive ,it means he/she can create 10 files on disk. It is same soft limit and hard limit and grace period also.

#Checking the node of a file:-

Ls –i filename

#####Implementing quota permissions

First check quota package on system with the help of

Rpm –ql quota

Now open fstab , because you have to mention quota in fstab for on which drive you wanna add quota permissions

/dev/partitionname /mounteddirname ext4 defaults,usrquota,grpquota 0 0

Save it:-

Page 31: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

After that you have to mount it again with permissions:-

Mount –o remount, usrquota,grpquota,rw /whereyoumonting

Creating usr and grp quota files in drive which you mounted.

Quotacheck –cugm /mountedpartitionpath (these files will stores quota permissions)

Check it :-

Ls –la

Now turn on quota

Quotaon –augv /pathof drive in which quota files are

# now set quota permissions on user.

Edquota -u uername

It will open a configuration file.

In this file you can set minimum block side or disk size for user and maximum also by editing it . 0 0 will consider to inodes minimum and maximum inodes.

Or you can use command

Setquota –u username 16000 17000 0 0 (first 16000 reprents minimum size of partition or you can say soft limit and 17000 represents max hard limit and 0 0 min and max inodes) /pathofdriveonwhich you stores the quota files.

Check entries are done or not with the help of :-

Edquota username

Now try to checl it by copying files or create dummy file

Touch abc

Fallocate –l +1G filename (it will make your file 1gb of size)

Its way to create dummy file . Now you will get error if your quota permission exceeds or you can create more files same as that till your quota permissions not exceeds.

TO see user quota and its limit and permissions

Repquota /username

Requota –a (all user)

For files quota

Setquota –u username 0 0 7 10 (minimum files 7 and max 10 can create a user) /pathofdrive

Page 32: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Or apply with “edquota username”

You can see the limit exceed by message.

This is it about quota

Check it by .

Repquota –a

Page 33: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Chapter 10:- Compressing And Archiving First old utility that used before Archving :-

Tar –cvf filename.tar * (c compress ,v verbose that is current ,f forcefully ,* will compress all files )

#checking whats in tar.

Tar –tf filename.tar

#extract Archving

Tar –xvf filename.tar

#Way to compress it more with Gzip or Gunzip

Tar –c2vf filename.tgz (make sure that file is archivied in tar already then gzip -c2 used for gzip)

Or

Gzip filename.tar.gz

#unzip from gzip.

Gunzip filename.gz

#another technique of compression.

Tar –cjvf filename (cj used of bzip2)

Or

Bzip2 filename

NOTE:- keep in my mind for more compressing first archive it with TAR and then compress . it will reduce size of archive more further and for extract

###best technizque for compressing 7z.

Page 34: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Chapter 11: Package Installation RPM –red hat package manager

There are five things you can do or we do in rpm

1-Installing (new package)

2-Uninstalling (cleanning)

3-upgrading (updating versions)

4.querying (finding and configuration file searching)

5.veryfying (properly installed or gpg key check)

you can download rpm from internet or there are main packages are in iso of Redhat 6 or 7 or any version. There is package directory in Redhat iso .

Cd /media/isofile/Package/

Or in redhat 7

Cd /run/media/user/Redhat7iso/Package/

In Package you will see rpm`s in colors. Suppose we have one rpm whose name is

Zsh.4.3.10-4.1.el6.i686 rpm

4.3.1 is version of rpm & 4.1.el6 release number i686 architecture number.

1-Installation:-

Cd /media/isofile/Package/

Or in redhat 7

Cd /run/media/user/Redhat7iso/Package/

Rpm –ivh packagenname (i installation v verbose h hashcheck )

# if we already have installed package. It will give you alert. But if you wanna replace old files with new one then:-

Rpm –ivh - -replacepkgs packagename

# if you wanna replace configurations files also that already exist in system

Page 35: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Rpm –ivh - -replacefiles packagename

#searching about installed package

Rpm –qi packagename

#finding its documentation files

Rpm –qd packagename

#sometimes we got package dependencies error or warning . In this you can search for dependencies

Rpm –ivh vlock(press tab it will complete the name)

Rpm –qR packagename

#package i.e not installed.

Rpm –qpi packagename

#location of documents of package.

Rpm –qpd packagename

#package dependencies.

Rpm –qpR packagename

#location where package and its files gonna installed.

Rpm –qpl packagename

#skipping dependencies.

Rpm –ivh - -nodeps packagename

#uninstalling or removing package.

Rpm –e packagename

#upgrade package.

Rpm –Uvh packagenamei.einstalled

#Searching about package installed or not.

Rpm –qa |grep packagename

Rpm –ql packagename

Page 36: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

YUM -yellow dog modifier

Yum server advance package installation method . It automatically solves dependencies that we install manually in RPM. but first we have to configure yum server.it is advance version of YUP server i.e used in old versions when there was no YUM server. there are two ways by which it solves dependencies automatically.

Locally

Network

There is one directory or repo data which we have to configure for YUM. First install yum. It would be in Redhat iso with yum name.

Vi /etc/yum.conf (global configuration file of yum server)

Cahcedir = path (it is directory where our package header gonna save)

Keepcahce=0 (you wanna save cache or not if yes then place 0 with 1)

Other options are for check packages`s architecture and gpg key and all that.

Last line which is :-

#in /etc/yum.repo.d (it is save repo file or database where dependencies available )

è Cd /etc/yum.repo.d/filename.repo

And yum Plugins are stored in

è Cd /etc/yum/ (you can check plugin ,there might be some plugins you can check it by editor)

## Configuring YUM 1. Create database for dependencies.

First install package of createrepo from Redhat iso.

Rpm –ivh /Packages/createrepo….

(it will ask for two dependencies deltarpm and python .. install both )

Page 37: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Createrepo - -database pathofpackages (you need to copy your package folder there which you got in Redhat iso)

Creating repo file.

Cd /etc/yum.repo.d/

Vi rhel7.repo (you can replace rhel7 with any name)

[writename]

Name=anyname

Baseurl=file:///yourpackagepathname where you created database

Gpgcheck=0

#now check yum server working properly or not.

Yum check

#finding repolist

Yum repolist

#finding any package with yum.

Yum search packagename

#installing package

Yum install packagename (it will install dependencies automatically ,we have set the repo data…it will ask for installation or not)

Without any prompt and it will install automatically .

Yum –y install packagename

#updating package.

Yum update packagename

#Check list of installed packages.

Page 38: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Yum list installed

# packages that comes in group

Yum grouplist

# removing package

Yum remove packagename

#creating over repo over FTP (do this after doing FTP) Add this in your repofile and make sure ftp working properly.

[ftpshare]

Name=ftpshare

Baseurl=ftp://192.168.1.2 or dns /pub (url should pub because via pub yum works properly and ftp folder is accessable )

Enable=1

(save it )

Yum repolist

Page 39: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Chapter 12:Jobs and Process Processes Management

Processes is program i.e executing or running . process can be waiting ,running,pause,sleep sate. There is one more thing in linux i.e PID that means process id and also process can have child processes i.e PPID. Whenever redhat system starts it starts init process i.e first process. It starts other processes. That’s id is 0 0 .

Threads (further modules of process)

Pid (process id)

Priority (if you have two process which process you wanna initial first so if lower the number to process it means process will get processed first than higher number process)

Memory (every process has its memory that is given by system)

File descriptor ( 0, 1 ,2)

Security (by which user or something)

(note)

When a process forks a child or create or calls a child it shares same memory. Child can exec new command that means calling new command. If you got any error with name copy of write it means every child has read only memory and it will create that child to new process and it got new memory space and PID.

Process can be child and parent at a time.first process i.e execute when system starts or at boot time is init with pid 1.

Pstree (this command tell you how processes execute)

In this we gonna learn Tracking the process, changing priority of the process and killing the process. Suppose:- you`re in row with 10 people that are infront of you and you have some emergeny and you wanna go first than 10 then you ll get that

Page 40: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

permission by changing your priority and find any known person that can take you there first . right!

Seeing process by :-

Ps (it will show only terminal processes with some pts/0 option pts means pseudo terminal and tty is tally terminal)

Ps –aux (it will show detail of processes )

Or

Top (best utility)

Or Graphical Utility

Gnome-system-monitor

You can also see this :-

Vi filename (enter)

Now press control + z and after that type “ jobs “ it will show you your running process or that are paused but still taking memory and or in background mode

Process States:-

-R or runnable

-S or sleeping

-T or terminated

-D or uninterruptable sleep (something like printing )

-Z or zombie process (if process id still kept and process is dead and body is still there it become zombie and it clears when you reboot your system )

Page 41: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Viewing process :-

Ps

Ps –u (user of process)

Ps –a(all)

Ps –auxf ( f will add their directories from which directory process is running from)

Ps –l (long listing uid and owner)

Ps –ef (system and background process-)

Pgrep processnames (searching process)

### Signals

Signals are interrupts that can be send by user or system itself. What types of signals. Killing , pausing etc.

First there is two things you should know about:-

PID (process id) and JID (job id)

If you see here:-

Ps (you will see first row is process id ) but

If we do this :- vi& (& will send vi in background automatically)

And that [1] or any number will be job id and all signals kill or pause or interrupts the process with its job id .

You can also see this with :- jobs

In simple words that have user interface are known as job id.

For foreground the process suppose that vi you sended to background now foreground it by :- fg %1 ( fg forground the process which process that has 1 its job id and % used to get it in foreground)

Now killing the process:-

First check how many signals we have :-

Page 42: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Kill –l (we have)

Signals are configured by system automatically to process that are programmed by system.

Kill -9 %1 (-9 is terminate signal you can search it in kill –l signal list)

Or way to terminate by “ctrl + t “

Process Priority:-

Nice –n number programname

e.g nice –n -20 programname (priority would be -20 highest and less 19 lowest, default priority 0)

#### for process or program I.e already running and to change the priority of the process.:-

Renice -15 –p pid (-15 priority)

Renice -15 –g pid (-g used for process group means its childs also )

Renice -15 –u username (it will change the priority of particular user`s process`s )

Multiple commands and sending their output to one file .

$(date;who | wc -l) >>logfile

$(cd /usr;du)&

# Important:-

Open terminal and write “firefox”.it will open firefox but it will become your firefox utility parent of your terminal ,means if you will close your terminal it will close firefox. So for that :-

Nohup firefox (it will make process parent itself )

Page 43: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

# you can change priority or kill and track a process from inside “top” utility

Open terminal and write :-

Top

By pressing :- M it will short al process by memory

P CPu process

W it will save or create a output file of process

O sorting process by requirement

c processes path

k killing process

z running process first

r renice or changing priority of process

1 total cpu`s

d process refresh rate

A split screen

h help

I hide load average bar from top utility.

#Redhat 7 Latest commands:- Lstopo-no-graphics

Lscpu

#to check which version you`re using :-

Uname –a or cat /etc/redhat-release

Other Command for REDHAT 6 and 7 sar iostat ss

Page 44: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

vmstat mpstat numastat tuna free –m (memory management concept)

Task Schedule At :- at is utility by which you can run your commands at particular time.

Its configuration file is . /etc/at

At timewhenyouwannaexecuteit

At> commands here

Ctrl +c to save it

# way to see its queue

Atq

#removing job

Atrm jobid

#Deny and allow users

Vi /etc/cron.d/at.deny (by default exist) you can add at.allow but other users will gonna deny automatically

Crons

Jobs schedule means ,jobs or task that you wanna run on particular date or time. Such as backup of system after every 2days or 10 hours or 1 month .

It is done with the help of “ Cron “ utility.

There are two types of crontabs :-

System specific crontab

User specific crontab

Page 45: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

# all crontabs or their list is in this directory:-

Ls /var/spool/cron (if it give empty o/p then it means you having no crons )

#check cron`s process is running or not.

Ps –aux |grep cron

#for system wise crons,you need to edit cron file

Vi /etc/crontab

(it will tell you everything)

Now you want to add your cron then go to last line by pressing G after that o Write here:- # Your cron

(this line is comment line in your cron ,here you can mention the purpose of your cron,its medatory to remind why and for what you have or other admin has added cron here

Minute hour day week month user commandstorun

(write your minutes 59 it means every hour`s 59 minute your command will execute )

So, save it after mentioning your numeric values and also other things

e.g

* * * * * root /usr/bin/uptime >> /root/uptime.systemuptime.txt (this command will run every minute and it will create systemuptime file in root/ directory)

# user specific commands

Crontab --help (it will give you options how you can create )

# checking user cron for specific user.

Crontab –u root –l

# all crons

Crontab –l

#Creating crontab in root user

Crontab –u root –e (e for making or modifying )

Minute hours days weeks years commandhere (syntax you already seen in system specific crontabs but here don’t add any user because you`re logged in user and it will work only in user you have created)

30 0 1 1,6,12 ls ( - 00:30 hrs on 1st jan june dec.)

0 0 1,10,12 - ls (midnight on 1st 10th and 12th of month )

Page 46: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

That’s concept its uses

# now check your created cron .

Ls –l /var/spool/cron/

There are two more files that can give you permission over allowing crontab allow or deny for particular user

/etc/Cron.allow

/etc/Cron.deny

Note: if you don’t have these files you can create it with same name cron.allow and cron.deny

# creating cron.allow

Cd /etc

Vi cron.allow

Root

User1

(save it or write those users you wanna allow those who can allow to create crons )

Vi cron.deny

Write those here you wanna deny but if you already mentioned user in cron.allow then it automatically deny others.

2.user wise crons:-

Crontab –e

* * * * * command here

Chapter

Page 47: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Chapter 13:Boot Process

Boot Process Whenever you start a system there are some process that executes or starts the time of system starts and Such Steps are or process is :-

BIOS (basic input ouput System)

BOOTLOADER

Kernal

INIT

USERLOGIN

Bios:- basic input output system .it is firs process or thing that executes first and bios is a chip and also it stores on PROM i.e programmable read only memory . So, when you start your system bios read prom and whatever setting stores In prom it starts exactly because sometimes we do setting or some changing in our bios or adding new harddisk is also a change and that new information stores in NVRAM ie non volatile RAM and I.e read by PROM .

And one more thing whenever you start a system by pressing power on button ,you see there is signal in Mouse and keyboard and screen yup! That signal is known as POST ,it’s a power packet i.e send by PROM for device that are connected with system and devices those whoes information stores in NVRAM.

And this PROM created device tree and after that it reads or sends system to bootloader.

BOOTLOADER:-In window operating system there is bootloader i.e NTLDR . In redhat the main bootloader works is GRUB i.e grand unified bootloader . Its updated verison is GRUB2 i.e used in REdhat7. Bootloader stores on secondary memory i.e sector 0 of harddisk its also knows as MBR ,You can say its first sector of harddisk.You can see bootloader when linux startsup just press any key from keyboard it will get you into bootloader menu. Form that bootloader you can change the GRUB file that stores in :- “/boot/grub/grub.conf” when you open

Page 48: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

the file, you will see default=0 that means start.And all boot logs are stored in. “/var/log” .it has also two stages

1 mbr that just send signal to stage 2.

2 stage does further process. That finds kernel and operating system.

But before that you have to know one moe thing i.e gurb password , Because when you get in grub at boot time so that means you can edit that grub.conf file and its not good thing , somebody can harm to your system so for that you have to change it by login system :-

Grub-md5-crypt (it will give you password or key ,just copy that key )

Vi /etc /grub.conf

#write here under hidden menu

Passwd - -md pastekeyhere

#save it

That’s it .

After processing of stage and all process of bootloader it will sends you to kernel or search kernel.

##Grub2:- in redhat 7 grub2 works. Its versions number is 1.99. if you wanna see grub2 the /boot/grub2/ and you wanna see timeout of grub 2 i.e in /etc/default/grub by grub command you can make some settings. Try out

Grub (type grub and press tab two times ,it will show you all other tags of grub2)

KERNAL:- kernel reads the bootfile and read hardware from init file . Yeah kernel is the medium of Hardware and system .

You can say when you execute a command and how that command runs ,I mean how background process works. For simple purpose you can say :

Usercommand ßà kernel ßà hardware

Main Kernal Processes:-

Page 49: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Process Management

Memory “

Device “

System Call

And here kernel will read the hardwares from INIT file that stores in Sbin directory and now it will send you for init.

INIT:- when Sbin starts it starts Init ,you can check it “pstree” which process starts first from the starting of system. You can check it by “/etc/init “ or “sbin/init” when sbin/init starts ,it starts the process that carry into /etc/ and when init starts it has 6 levels that starts by the time of Bootloader , you can say it starts with bootloader through kernal.

See init levels .. you may thinking about what is Levels. You already know about few things such as ..CLI mode and GUI mode of linux . So through init you can set default any mode and how run-level change.

Vi /etc/init and /etc/initab (this tells you which runlevel starts by default)

In REDHAT 7 there are no more run levels. But in rehdhat 6 there are 0- 6

0 Shutdown

1 single user

2 System Reseverd or some GUI functinality

3 Mutliuser without GUI

4.Undefined

5. Multiuser with GUI

6.Reboot

You can use these by typing :-

Init 0 (it will shutdown system)

Init 1 (cli mode)

Page 50: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

In redhat 7 these works in targets and also change by systemctl i.e service tag to start ,disable ,enable and stop the service

Systemctl

But you can still use “init 0” in redhat 7 because of some purpose commands still execute.

# want to check which runlevel you`re:-

Runlevel

Who -r

And also that service or hardware information store by init in :-

/etc/ini.d

That gives hardware information to kernel. And what hardware or service should starts consist into :-

/etc/init (press tab two time )

Or

Old version is : /etc/rc.d/ init.d/

Here you will see various services that should start or stop during start of system and service will start all with starts with S character and Stopped services starts with K character in rc.d . you can check what the actuallt doing by entering in any directory in

Cd /rc0.d/

Ls – l (it will show all linking and will tell what exactly a service gonna start or is on stopped state )

USERLOGIN :- user login is handled by system scripts . There are so many . .bashrc and other /skels/ ,some that controls services. Passwd and security checker. Main point is it checks UserLogin name and passwd is true or not .

Page 51: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Few commands that are important :-

Ntsysv (it will send you in gui mode where you can start or stop a service But few that starts with system during system startup)

#Note:- Init is no more as I told you before it replaces with “Systemd” in redhat7

Log information and service other things.

There are so units such as : .socket ,.daemon ,.services ,.device,.mount etc.

As a administrator you should where those units are.

Find / -name “*.service”

Ls /usr/lib/systemd/system (here system units created while installation)

Here you will see so many services and units.

You can check what the service or unit exactly do by just editing it:-

Vim /usr/lib/system/system/firewalld.service (just for example firewalld)

But if you know how to modify it then you should otherwise ignore.

There is one more directory .

Ls /etc/systemd/system (here units managed by administrator)

/run/system/system (when units execute)

Here you will some files that are services also . but these are changed in redhat6 there are some such as multi-user.target or graphical-user.target are init levels. But now everything changed. They replaces it with systemd.

Page 52: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

For system Redhat dev. Created “Systemctl” that controls systemd. You will see word enabling service it means that service will boot automatically when your system boots.

That’s it next chapter will see how systemctl uses .

But before that ,as I told you init not in use anymore so do runlevel and runlevels are replaced with “SysV”

Where init 1 is single user here it is rescue mode.

And these all are starts with runlevel0.target or runlevel1.target sequence is same as before

#to see by default runlevel.

Systemctl get-default

#to change runlevel

Systemctl isolate name.target

#set default

Systemctl set-default multi-user.target

#single user mode.

Systemctl rescue

###Redhat 7 with systemD New:-

System-analyze

Systemd-analyze blame

Systemd-analyze critical chain

Systemd-analyze critical chain servicename

Systemd-analyze list-dependencies

Page 53: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Services ,Daemons & Ports Services & Daemons:- Service is something running state and daemon that handles service and its process. To check daemons :-

Ntsysv

In redhat 7 there are so much difference with redhat6 . because first services are stores in “/etc/” , Some services are store here but all are accessed from “Systemd” and that also genreats logs also.

# way to run or execute service in redhat 6

Service nameofservice start

# way to on daemon of service in Rehdat 6

Chkconfig servicename on or off

Other importants:-

Service nameofservice status

Service –status all

But in redhat 7 they changed so many commands ,you can whole procedure that saves memory and other stuff that runs in background of redhat. Don’t need to worry about that .

Systemctl (systemctl is command that control daemons and services)

Systemctl enable servicename (enable means creating link with service that may under /etd/ or system or sbin )

Systemctl start servicesname

Systemctl restart servicename

# if you wann your service is running or not

Page 54: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Systemct –l status servicename

Ps –ip PID

# to check its port

Netstat –tulpn |grep servicename

There are so many other options you can check by man systemctl

# reloading the service .it will change the memory area

Systemctl reload service

# to check all process inactive and active process Systemct

Systemctl is-active servicename

Systemctl list-units - -type=service

Systemctl - - all

#searching path of service

Systemctl status servicename.path

#service logs and its changing store into

/var/spool/servicename

## masking the service . Services that we don’t want to start.

Systemctl maks servicename

And to umask it ,by this person can start the service

Systemctl umask servicename

Page 55: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Ports :- ports are interfaces that helps to connect other service with our own system or you can say it is door of your home or room . So it makes simple for everything when someone wanna come in the port or door should open. All ports that are opened or not are in :-

Vi /etc/services

Or you can see via :-

Netstat -alp

Or semanage port -l

Ports such as : 80 http service,20 ftp, 21 telnet,22 ssh,25 smtp that are commonly used.

You can close any port . through configuration file that store in /etc”

e.g:

vi /etc/ssh/ssh-config

denyusers *@ipaddress

There are some services that store in /etc/rc.d/ as you already know ,and those which are ends withD character are read by Librepo which is also know as TCpwarpper. That can helps to close the port

Or

Vi /etc/hosts.deny

Ssh:ippadress or *

Or

* ssh:ALL EXCEPT ipaddress

In redhat there are so many ways to close service or port for a network or particular ipaddress for that you need to know about .

FirewallD and IPtables that are security utilizes . READ in Next chapter .

Page 56: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Chapter 14: Networking Network Configuration with ipv4

Network is essential part of Computer system , in simple words without internet computer system is nothing. It helps us to sends and receive information.Search About its History. First of all , How internet works. It works with protocol and web Applications.

You can say .. Web Applications Such as browser sends the request vi Protocoal i.e 80 http protocol and it sends the request to other medium,it may be transport or network layer. You might be confused what is layer.

IPV4 is protocol I.e internet protocol version 4 that consist OSI model that is Open system Interconnection.

Simple question is : when you enter a website and it request with Web browser in such a way: https://www.gooogle.com. Then how it gives you fully website in some mileseconds and how it works, whats the back end . that’s what networking is . But for Redhat or Linux Configuartion you should know Basic things.

Basic Concepts:-

LAN - local Area Network , that works in small area or scope

WAN- wide area network – LAN works thorugh WAN. LAN gives local IP but WAN that is public has having Public IP and is connect you with Main internet service you can say with ISP(internet Service Provider). Search about WAN

MAN – Manopulation are network – Uses in collages and for inside organization.

Main Concepts:-

There are two types of internet

Internet – Global Network

Intranet - Private Network.

How Network Works :-

Hardware (Network works with system when system attached with NIC – network interface connector)

Hardwares such as Switch – most expensive gear. Switches are used for connect system with one Network and it can divided into subnets with the use or routers and hubs. Switches transfers data in duplex for half duplex or full duplex. Such a CCNA stuff .but you should know about what switches are.

Packets (internet works in packets in 0 & 1 form ,in bits).

Page 57: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

When you sends request for any website , it divided into packets. It done by Switch .Because internet sends and receive bits in electric bits form. Or Signals.

Protocols (Rules of Packets)

Rules that governs packets . How packet should divided and in what way . or you can say in simple words Protocols are doors to send and receive something in our system.

Addressing (IP address)

TCP transmission control for sending and receving ,

UDP user datagram protocol for applications such as utorrent and other applications that sends data in large size,

IP internet protocol with this you really connected with internet

Addresses are: hardware adreess :- jbas:66hs:82sd

Ipadress: 192.168.1.2 (this IP version is IPv4) there are two ipv4 and ipv6 (latest)

Hostname:- google.com (.com is DNS)

OSI MODEL The Way internet works:

Page 58: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Basically it is a procedural Model. When Requests Send iT work Form Top i.e

Application Layer And then process top to Bottom but when it Receive ,Because when you Sends any Request then there must be Receiver. And Receiver accepts it and receives with Physical layer and Process Bottom To Top.

• Application Layer: The Application layer deals with representation, encoding and dialog control issues. All these issues are combined together and form a single layer in the TCP/IP model whereas three distinctive layers are defined in the OSI model.

• Host-to-Host: Host-to-Host protocol in the TCP/IP model provides more or less the same services with its equivalent Transport protocol in the OSI model. Its responsibilities include application data segmentation, transmission reliability, flow and error control.

• Internet: Again Internet layer in TCP/IP model provides the same services as the OSIs Network layer. Their purpose is to route packets to their destination independent of the path taken.

Page 59: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

• Network Access: The network access layer deals with all the physical issues concerning data termination on network media. It includes all the concepts of the data link and physical layers of the OSI model for both LAN and WAN media. In internet the IP is using form so long is Ipv4. IPV4: Ipv4 has 5 classes that’s how we can attach system with one network. All classes has different ranges of host . Host are systems that are gonna attach with our Network.It is 32bit address. In this way:

8bit.8bit.8bit.8bit. if n.n.n.h (first 3 n define network address of system and h is host that defines how many systems can attached or can be)

In Ip4 there are three things:

Ipadress -- address of system and all are upto 255. Means if we have this 255.255.255.0 so one portion`s limit is 255 , actually in bit way or in the form of 0 or 1 is

1 1 1 1 1 1 1 1

128 64 32 16 8 4 2 1 =255

Subnetmask --- that tells the IP address of a subnet ,because subnet is possible , it means , Subnets of a Network. If we have two subnets.

And ipaddress are 192.168.1.100 subnet 255.255.255.0 gateway 192.168.1.1

192.168.2.100 subnet 255.255.0.0 192.168.1.1 (it means whenever a request sends it will find its destination with the help of Subnetmask)

Gateway—its main address or you can say gate that connect a system with WAN or public network. If we have two subnets then it will carry just one Gateway because one router or switch consist one gateway and that gateway will send you on WAN address means public IP.

NOTE: 255 and 0 are used for broadcast ,so you cant use it for any host

Page 60: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Classes:

A 1.0.0.0 – 127.255.255.255 N.H.H.H (h represents to hosts and N to network address )

B 128.0.0.0 -191.255.255.255 N.N.H.H

C 192.0.0.0-223.255.255.255 N.N.N.H

These are main classes that are used and other classes are:-

D 224.0.0.0 – 239.255.255.255

E 240.0.0.0-247.255.255.255

Class d and e are used for RND , some development purpose so that are reserved classes.

Private Ip range:-

Class Private IP Address Range Subnet Mask A 10.0.0.0 to 10.255.255.255 255.0.0.0 B 172.16.0.0 to 172.31.255.255 255.240.0.0 C 192.168.0.0 to 192.168.255.255 255.255.0.0

One more thing I have mentioned you above that is Broadcast , it means sending on multiple system means public.

There are two more Unicast only one sender and one receiver. Multicast – in this sending in receiving in multiple groups

IPV6 We will do later.

Note: there are two ways we can setup our internet connection :

Page 61: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Static IP :entering Ip address manually using network configuration tools and entering IP ,subnet , gateway according to you.

Dynamic IP: When you enable the DHCP , that is dynamic Host control Protocol ,in this system will catch any IP whatever it gets first.

We ll do both.

###### Linux Network Configuration IN Redhat 6 #############

Configuration Files:-

/etc/resolve.conf --------- this file carry server names and dns , When you create DNS then it will in work . till then in Network configuration there is no need for this.

/etc/hosts ----------- sometimes we want to ping our ip address and if you have 10 ip`s with differnet systems and its difficult to remember which ip of whicg system ,for that you can add ip and with system name in Hosts file such as:

192.168.1.1 adminsystem admin

After saving this hosts file ,now you can ping that system with:-

Ping adminsystem ------------ (ping command will tell you system is alive or not , means its network.

###to see ip address & NIC cards of system

Ifconfig

Ip addrs

##to check LAN cable is plugged or not :

mii-tool interfacename e.g:- mii-tool eth01

ethtool interfacename

### configure the Network ,there is TUI tool ,text User Interface Tool

Type “Setup” on terminal and hit enter then

Go to Network

Page 62: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

And you can do everything after that . its easy

## manual Way to Configure.

Vi /etc/sysconfig/network-scripts/ifcfg-eth1 --------file can with this name eth1 or any other . just check.

## way to down and up the particular NIC.

Ifdown interfacename

Ifup interfacename

### After doing changing in network must restart network service

Service network restart

Redhat 7 Network Configuration.

In Redhat 7 there is no Network option in “Setup” TUI utility. Options are changed

##you can add network profile with there new TUI uitltity i.e

TUI: nmtui for that sometimes you have enable Network manager

Systemctl enable networkmanager

Systemctl restart network

## With CLI mode

Nmcli dev status (to see how many NIC you have)

Nmcli connection show (to see how many devices get connections ,means really connected with network)

##adding new connection

Nmcli connection add con-name Profile\ 1 ifname eth1 type Ethernet ip4 192.168.1.25/24 gw4 192.168.1.1 (24 is subnet address that’s actually in binary form it measn 11111111.11111111.11111111.1110111)

After adding the connectiom:-

Page 63: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Nmcli con up Profile\ 1

Nmcli con show

Now it will work.

## For Doing manualyy its same directory

/etc/sysconfig/network-scripts/ifccfg-Profile_1

## edit profile via GUI:-

Nm-connection-editor

## editing with CLI

Nmcli con edit

Nmcli>Ethernet

Nmcli>gotot ipv4

Nmcli ipv4> goto addresses

Nmcli > set newipaddresshere

Nmcli>save

Nmcli> exit

# after editing type this

Nmcli con reload

# down and up the profile

Nmcli con down Profilename

Nmlci con up Profile Name same for device ,just change the con with device

#to delete Profile

Nmcli con delete profilename

Page 64: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

That’s it.

Nslookup sitehere (name of server)

Dig –x ipadresshere (reverse checking)

Dig –a

Traceroute sitehere (finding routers bw website and server)

Netstat -nap portswithservice(main command to see opening ports and other services )

Netstat –a allports

Netstat -l alllistingports

Page 65: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Chapter 15: Security Firewalld

Firewalld is firewall that provides us the authority to control over ports and services . those services which can be used by different network or any local network user.

Basically firewalld gives us permission to configure dynamic firewall in linux.it gives us zone concept facility that makes so much easy. Zones such as :work, public, private ..even you can create your own network zones.

First check service is running or not

Systemctl status firewalld

If yes then good otherwise enable it and start it

Systemctl enable firewalld

Systemctl start firewalld

Cool!

there two ways you can configure firewalld:-

1 gui interface of firewalld-config

2. by cli firewall-cmd

But what you really wanna know is by using CLI .

#active zones of firewalld

Firewall-cmd - -get-active-zones

Or

Firewall-cmd - -get-service

#way to see all setting or configuration of particular zone.

Firewall-cmd - -zone=public - -list-all

# adding your service and port in firewall

Firewall-cmd - -permanent - -zone=public - -add-service =http

Page 66: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

For port:-

Firewall-cmd - -permanent - -zone=public - -add-port = 20/ftp

#removing service & port

Firewall-cmd - -zone=public - -remove-service=ftp

Firewall-cmd - -zone=public - -remove-port=20/ftp

#to see all services & ports that are in public zone.

Firewall-cmd - -zone=public - -list-ports

Firewall-cmd - -zone=public - -list-services

#allow and block incoming and outgoing packets for website.

Firewall-cmd - -panic-on

Ping google –c 1

Firewall-cmd - -query-panic

Firewall-cmd - -panic-off

#way to forward any port to another port i.e masquerade

Firewall-cmd - -zone=external - -query-masquerade

(don’t puzzle here we just change the zone public to external and you can set external to your default zone by )

Firewall-cmd - -set-default-zone=external

#list of all zones

Firewall-cmd - -get-zone

(we checked masquerade is active or not now add it)

Firewall-cmd - -zone=external - -add-masquerade

Page 67: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Firewall-cmd - -zone=external - -add-forward-port=port=22:proto=tcp:toport=2222:toaddr=192.168.1.3

Firewall-cmd - -zone=external - -list-all

#way to block and allow icmp

Firewall-cmd - -get-icmptypes

Firewall-cmd - -zone=public - -query-icmp-block=echo-reply

Firewall-cmd - -zone=public - -add-icmp-block=echo-reply

Whatever you did up there if you wanna to load into file of firewalld i.e

/Usr/lib/firewalld/zones/ for that you have to add

Firewall-cmd - -reload

####firewalld config file stores into :-

/etc/firewalld/firewalld.conf

RICH RULES of Firewalld

Rich rules are polices which provides us blocking a network or ip address.

Firewall-cmd - -permanent - -zone=public - -add-rich-rule=’rule family=ipv4 source address=192.168.1.3 service name=dns accept’

To reject just replace accept with reject

To see:- firewall-cmd - -zone=public - -list-all

Removing rich rule:-

Just replace above - -add-rich-rule with - -remove-rich-rule

Page 68: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

You can search other Rich Rules by man firewalld , use some for RHSCA paper .

IPTABLES

Iptables is a firewall that was used in Redhat 6 also in Redhat 7 . You can either Firewalld or iptables

There are three things you can do via Iptables:-

Input

Forward

Output

##to check list of policies that are already added in iptables:-

Iptables –l

## to clear Iptables:-

Iptables -F

Lest start:-

###Creating Log of particular IP A stands for Append I input i.e interface –s source i.e ipaddress –j is used for Jump .

Iptables –A INPUT –i eth0 –s 192.168.1.1/24 –j LOG

## Droping Ipaddress

Iptables –A INPUT –I eth0 –s 192.168.1.1/24 –j DROP

Page 69: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

## Accepting

Iptables –A INPUT –i eth0 –s 192.168.1.1/24 –j ACCEPT

##port Closing

Iptables –A INPUT –p tcp –s 192.168.1.2/24 –j REJECT

## to save these permanent:-

Service iptables save

Or you can do this via configuration file:-

Vi /etc/sysconfig/iptables

###there are some graphical utilities by those you can see packets sending or receiving by and to the system:-

Nmap

Wireshark

Page 70: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Chapter 16: Logs LOGS:- logs stores information about process or service running or not . and their other information. As you already know what logs are , you might create your own also .

/var/logs

/etc/rsyslog.conf --------- changing logs directory and other configuration of logs

/etc/logroate.conf

In redhat 6 there was system configuration options it has been changed IN redhat 7 , but that was

Vi /etc/sysconfig

But there is no sysconfig for that you have to go for

Find (systemd-journal ) that’s what is sysconfig its in

Vi /usr/lib/system/system/systemd-journal.

You can find logs and check it ,so logs also created at “/home/user/ “ in hidden mode.

Some logs are same as where the config files are such as:

Vi /var/named/data/named.run (these are service logs)

Or you can install Uitility i.e called “SYSKLOGD” which will provide you /etc/syslog

features:-

Handles Loging

Domain Sockets (dev/log)

Internet Socket (UDP 514)

Page 71: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Ability to log Local And Remote Targets

Other running logs such as with corn or sending spool mail

Logger –p cron.info “msg”

That’s it.

Checking Logs IN Redhat 7:-

Journalctl (system logs)

# last boot log

Journalctl –b

# All kernel Logs Store in :-

/dev/console

#AuthrPriv File Restricted Acces:-

/var/log/secure

##other you can check with the help of :-

Man journalctl

Page 72: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Chapter 17: Security Enhanced (SElinux) Selinux

What is Selinux?

Selinux is enhanced or you can say advance security feature. There are iptable and firewalld but both are different . Selinux is Administrator Feautre. Which carry :-

Modes

Polices

Labels

Modes:- there are two modes enforcing, permissive , disable

Getenforce (to check in which mode your system is )

To check other modes

Vim /etc/sysconfig/selinux

In enforcing mode service or something legal would disable or blocked in system.

In permissive mode it will create logs in ”/var/log/audit/audit.log” but will block nothing .

In simple words there are two kinds security features in selinux . low level (permissive), High level (enforcing)

Now changing modes b/w permissive and enforcing for that:

Setenforce 0 (permissive )

Setenforce 1(enforcing)

Check in which mode you`re by :-

Getenforce (already told you)

You can check it by:

sestatus

Page 73: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Policies:- there are three different policies available. You can check in

Vim /etc/sysconfig/selinux.

a) Targeted Policy:- Its best policy. In this processes are protected. b) Minimum Policy:- In this policy only selected processes are protected. c) MLS :- Multi level security . it is advance For RHCSA or RHCE you don’t need

to know about it.

Policies are in context or you can say in properties of file and directory.you can see it by :-

Ls –Z

Contexts are in three different parts:-

First part is user . second part is Role . Third part is type.

For RHCSA you need to work on type :-

System_u:object_r:var_t (var can be placed with anything or any directory or service name)

Label:- Type: Every process has different or can be same context type. In simple words every context or process has type :-

Ps –Zaux (you will see type of every process)

To check the context label .

Semanage fcontext –l |grep typename ( name of process you wanna search or something that you see in ps –Zaux or ls –Z ,name which ends with _t)

Its tough way, easy way is :-

Ls –Z

To see selinux policy man pages , you need to install its package .

Page 74: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Old package was pam_selinux something like that but now it changes to search it :-

Yum whatprovides */sepolicy

Or install it by yourself which is “policycoreutils-devel”

Yum install –y policycoreutils-devel*

After installing it :-

Sepolicy –help

Or

Man sepolicy-manpage

Now put man pages of sepolicy to main man pages path which is .

/usr/share/man/

Now :-

Sepolicy manpage –a –p /usr/share/man/man8

Update the man database:-

Mandb (latest command before that :- apropos . you can check it by man apropos)

Man –k _selinux (it will show entire manpages of selinux)

To check Context of particular service or process :-

Man httpd_selinux (httpd is service )

Easy way to find context of particular service. And to play with context :-

Man semanage-fcontext

To change the context:-

Semanage fcontext –a –t httpd_t “/web{/.*}?” ({} it means all files in web directory )

What we have done only on policy not on file system for that we have to that on :-

Page 75: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Restorecon –R –v /web

We can do it with :-

Chcon –t httpd_t /web

Restorecon –R /web

# Boolean

Boolean is on off switch .

Getsebool –a (will show you all booleans and their current state)

Or semanage getsebool –a (state & other detail )

You can find it in man page :-

Man –k _selinux |grep ftp (give you ftp booleans)

Suppose Ftp_anons_write is off , you can check in :-

Getsebool –a |grep ftp

You can search what if we on the ftp Boolean ,I mean on it or off it , you can check it here:-

Sesearch –b ftp_annon_Write –ACT |grep –y type_trans (it gives you transition types)

(sesearch is for advance users )

Setsebool -P ftp_anon_write on (it will on it by this the ftp anonymous user will able to write ) this is it about selinux

## to check status

Sestatus

Page 76: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

## to check all ports of system:-

Semanage port –l

##to search to Boolean

Sesearch –b allow_ftpd_anon_write |grep –v type_transit (-v to ignore)

##all logs off selinux stores in :-

Tail /var/log/audit/audit.conf

Page 77: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Chapter 18: SSH,FTP & Servers (DNS,MAIL,NFS,SAMBA) SSH & FTP

With both you can admin or access your data center or other system that is far from your place for this you need SSH i.e secure shell and download and upload files their with FTP i.e file transfer protocol

SSH:- its terminal. First install it. Port 22 used in SSH. Before connecting the ssh you should see you firewalld or iptable ,if its ok then great otherwise add port 22 firewalld-cmd - -permanent - -add-port=22/ssh or allow it.

Ssh ipaddress

Name of user:

Pass:

After login you will in other system ,keep in mind whatever permissions that user has by which you logged in can do things and all thing will applied on that system not yours.

Now you have to see how many clients you`re connected with and you wanna see for that

Vi .ssh/known_hosts in users home directory

#Sending file to that system without ssh.

Scp filename ipaddress:/pathwhereyouwannaputthatfile

(scp is secure copy over internet or you can local network)

There are more utilities also such as:-

Rsync (to send files)

## other way to connect remotely and graphically .

Vncserver or tigervnc (this is utility that you need to install in system if you wanna connect remotely and graphically in some system)

Vncserver 0 (to see desktop only)

Vncserver 1 (to control it)

Page 78: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

# you can also deny access of anyuser or network

Vi /etc/ssh/ssh_config

Denyusers *@ipaddress

#second way is

Vi /etc/hosts.deny

Ssh:ippadress

Or

* ssh: ALL EXPECT ipaddress

FTP FTP uses 20 port: First install “vsftp” package

Configuration file of ftp:

Vim /etc/vsftp/vsftp.conf

There are few lines that having # sign infront of ,it means comment and some lines we have to uncomment such as :-

Local_enable=yes (something this)

Write_enable=yes (find this also ,its upto you to uncomment this line)

You should change permissions of selinux by setsebool check vsftp.conf file everything mentioned there.

For other methods such as :

Allowing particular user and ftpusers list fort that ope:-

Vi /etc/vsftp/user_list (read it carefully and that user_deny=yes you have to find from vsftp.conf file and off it )

And enter your users that you wanna allow in ftpusers.or set it default and try to change users from list then try to connect its easy way to understand how ftp user list works .

#uploading and downloading files from ftp

Mget fileyouwannadownload

Mput fileyouwannrecevice (for changing your local directory use “lcd”)

Page 79: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

NFS server Nfs means network file system .because sometimes administrator share some file for multiple pc`s and its difficult to sending via ftp or scp ,so here we create a file system that works over network and you can mount it in your system and it will updated automatically whenever admin will made changes in it ,you can see those changes .its kind a file system that you use in system such as ext4 or LVM .Its same thing but over Network that anyone mount and use.

For this first install NFS utility.

Yum install nsf-utils

# you can set yours ports with

Vi /etc/sysconfig/nfs

Uncomment ports but deleting “#”

(but no need for that )

# creating nfs

Vi /etc/exports

/var/ftp/pub 192.168.1.2/255.255.255.0 (rw,sync) ;path ipaddress rw read write and sync used for updation of nfs.

Now enable service “ systemctl enable nfs-server” and start systemctl start nfs-server

Or

Exports –r

Now go check from receviers system. But before that make sure you enable and start your nfs-server.

Showmount –e 192.168.1.2

It will show what sender or admin of nfs shares.

Now mounting and using everything.

Mount 192.168.1.2:/var/ftp/pub path_where_you_wanna_mount

Now after mounting create any file or folder in this folder and see :-

Ls –l

Page 80: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

You will the file you created or folder is created by “ nfsnobody “ ,Yeah. You saw correctly. By default in nfs user is “ nfsnobody “ . you can see this in /etc/passwd you will see there. But if you wanna change the owner or file because you wanna modify that file you have created and you want permission to change it so for that say to whoever nfs`s admin.

Or sender or admin of nfs can change that permission by :-

Chmod 1774 _dir (1 will work here stickybit ,,,, give this permission to directory which is shared over network)

/var/ftp/pub * (rw,no_root_squash)

But whatever you do it will create or share everything with UID not name.

For permanent mounting as you know :-

Fstab:-

192.168.1.2:/sharefolder /mountname nfs4 defaults,hard,fg 0 0 (you can check hard fg in “man exports)and whatever mapped iin nfs or you can say its session logs store in

Vi /var/lib/nfs/etab

This is it

Page 81: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Samba Server By this server we can share betweem windows & redhat or any other operating system . Samba server carry every other server information . such as in windows netbios that run with the help of NMB protocol and in Linux it is smb i.e server message block. Now days in windows CIFS i.e common internet file sharing. On the same network

Samba consists all of these.

First install Samba Package.

Rpm –qa|grep samba (way to check package install or not )

There are two parts you should install:-

Samba-server and samba-client

## if you see what window operation system shares with you.

Smbclient //192.168.1.2:/sharename

Now after that you can create files or folder according to permission that gives by window person.

## files where stores of samba

Rpm –ql samba*

## samba config file and sharing should be here on last of this file.

Vim /etc/samba.conf

There are two ways to share :- Publicly

User

Publicly:-

Vim /etc/samba/smb.conf [share1]

Comment=Linuxshare

Path= /var/ftp/pub //sharing directory

Public =yes

Browseable=yes

Page 82: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Writeable=no //it means no one can write

(for this you have to set your selinux permissive mode)

In windows it will see directly without any password or username.

users:

[share2] Comment=linuxshare2

Path /var/ftp/pub

Valid users=user1 user2

Read list=user2

Write list=user1

After saving this file now check file is loading ok or not by:-

Testparm (used for samba only)

Now add users in samba , but user must be exist physically in Linux machine

Smbpasswd –a username (-a used for append)

#to see samba users who can access our files.

Pdbedit –L

#to edit or delete user.

Man pdbedit

Or to delete :-

Pdbedit –x –u username

##Mounting in other linux machine

Mount ipaddress:/share1or whatisshared

For auto mount at system startup then give its entry in fstab.

Ipaddress:/path /mountdirectory nfs4 deafults,hard,fg 0 0

Page 83: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

DNS Server

First of all DNS is domain name server . as you already know about Domains such as : com,org,in. But Networking point of There are a lot of questions. As you already know every website has a unique IP ,may be same. Its depend upon static ip or dynamic ip . here main point is how a IP combined with domain , In simple words how A ip got name . and you used to access that name but in backend everything done with IP. Every website google,fb has ip`s .Lets start making a DNS server.You will understand it.

First you have to install a package “BIND”. Bind is package by that we can create a DNS server. Barkley is the person who created DNS system. You should search for its history why the created. Simple ,I can put it like that,its difficult to remember so many ip address of different websites.there are 13DNS that are main DNS they have further sub-DNS ,country wise ,state wise or other stuffs like universities wise etc.

Website sends dns search packet to àrootdnsàsub treesà here it will get ip that bindwith that website and it will sends data or whatever that packet back to browser in form of webpage.

1 Step after installing “BIND”

Vi /etc/resolve.conf

Nameserver yourippadress

(write this and you ipddress end of this file and save it)

2.Step:-

Vi /etc/named/named.conf

#there you will see line with

Listen on port 53 {127.0.0.1; youripadress;} //write you ipadress there

Allow-query { any;} //replace localhost with any or any network

#now go end of this file and write after the line #include or copy above both zone with name and one with in.addr something whole 10 lines and paste down here after include line and change them and keep in mind zone “com ” whatever you will write here is your domain

Zone “com” IN

{

Type master; //it means it has no secondary DNS

Page 84: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

File “jimmy.for”; //this is forward file which will work with name such as localhost.com or whatever you will give name in “jimmy.for ” file .

Allow-update {none;}; //this is for secondary DNS

};

Zone “1.168.192.in-addr.arpa” IN { #here reverse IP without network range only hosts

Type master;

File “jimmy.rev” // its reverse file that will work with Ipaddress itself ,means ping 192.168.1.2 not ping google.com ..ok

Allow-update{none;};

};

#save it

3 step:-

Cd /var/named/

Cp –r /var/named/named.localhost jimmy.for

Cp –r /var/named/named.localhost jimmy.rev

Vi jimmy.for

# Delete last three lines and change version above , and change whenever you edit this file

@ IN NS jimmy.com

Jimmy.com. IN A 192.168.1.2 //my machine ip

www IN CNAME jimmy.com. //carsual name, means every website works with two ways with www or without www

jimmy.com 0 IN A 192.168.1.3 //dynamic ip ,that means ip can change after few minutes but its for example purpose ,add other ip that works with you other NIC

#save it

Now edit:-

Vi /var/named/jimmy.rev

Page 85: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

#delete last three lines same

@ IN NS jimmy.com.

2 IN PTR jimmy.com. //2 is network address as you mentioned in zone 1.168.192 and it completes it 2.1.168.192 automatically

#change version above , please do add same version name as you mentioned in .for file

#save it

4step

Systemctl enable named

Systemctl start named

#if you service not start then you should mention your network DNS and you know how to mention it or add by editing

Vi /etc/sysconfig/network-scripts/ifcfg-Profile 1

# add dns after prefix0

DNS1=yourdns that you mentioned in jimmy.for file

#save it

Systemctl restart network

5 Step

Ping jimmy.com // if you two three times it may change ip address because you added a IP there.

Ping ipaddress

Ping www.jimmy.com

## if not work then change you localhost name with :-

Vi /etc/hostname

Jimmy.localhost

#save it

## reboot your system and now try it ,it defintly gonna work or see error in

systemctl –l status named

Page 86: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

####check DNS with or Test DNS

Dig jimmy.com

Nslookup 192.168.1.2

Host jimmy.com

####there are more things you can search such as what is MTU and MDU when you ping a website or IP address

Secondary DNS

Add new server also its A entry with its ip .

Now go to Secondary system where you wanna setpup secondary DNS.

open named.rfc file and create a zone with same name “com” that is in primary DNS. Here you have to add two new things .

Type slave;

Master {192.168.1.1;}; primaryipaddress

#Saveit

That’s it

Page 87: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

MAIL SERVER

Mail server you might already aware of it. Yahoo.com,gmail.com live.com all are mail servers.

For that first install “POSTFIX” port is 25. And mail servers are not different but here mail servers works on local network but you can make it Public but for that you need live server.

Ignore ,for paper purpose its enough. First packaged that has been used that was “sendmail ”.

Ohk lets start with Mail server ,But before that you should configure your DNS , same as we did above.

First how mail sends and recevices:-

Mua mail user agent à MTA mail transfer agentà MX DNSà NowReceiverSideàMTAàMDA Mail delivery Agentàdatabase inboxàMAAàMUA

And all mails that are sent and received are store in:-

/var/spool/postfix

Or /var/spool/mail (logs )

If you know about mail server ,I mean if you ever configure outlook in windows.you may know about two ports and service that does all stuff of MAIL Server`s

POP only used for synchronize mails from inbox ,it also synchronizes same mails again.Used to download not to send

IMAP3 it is intelligent ,it not copy same copy. And it used to send mail.

#find mail server port .

Netstat –ntup |grep 25

In redhat 7 they are new ,you can find there ports from :-

Vi /etc/services

#configuration of POSTFIX or mail server.

Vi /etc/postfix.main.cf

#first uncomment

Inet interface =all or oneip //upto you

#uncomment and add hostname

Hostname=jimmy.localhost

#uncomment and add domain name

Mydomain=com

#uncomment origin

Page 88: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Myorigin =$Myhostname

## you can add your alias but for that you have to add you aliases /etc/alias here but for paper ignore that.

# add destination ,again its upto you

#relay hosts needs live ipadrees ,used to send mail outside of your network

#header check , by this option and whatever you will add here ,it will check with mail and reject it

##save it..

There is one more file which used for imap protocol for that file :-

Vi /etc/dovecat/dovecat.conf (search about it)

By default all mails stores in /var/spool/mail

### Now.. go :-

Vi /var/named/jimmy.for

#add this after NS jimmy.com

@ IN NS mail.jimmy.com // nothing just showing you can create more than one server

#add this in the end of file

Jimmy.com IN MX 192.168.1.2

#save it

##restart you namd service and now you can use it.

Suppose I have two users user1 and user2

User1@localhost: mail [email protected]

Subject:hi

Ajsbdakjdbkjasd

(press ctrl+d to send )

Page 89: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Now go to user2

User2@localhost:

(/var/spool/mail/ newmail)

User2:localhost:mail

[email protected] ………………………..

& 1

It will show you mail and for more help add “?” .. and find out how to use it and reply and delete .

## if you want to send any attachment also just add” MUTT” utility .

Sending :- mutt mail [email protected] (you will understand it)

Receiver:-mutt

That’s It with mail server

Page 90: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Apache Server

Apache server Is local server .Basically Apcahe is an organization that created Web server.In Linux Apache is the server but utility that we are gonna use is HTTPD. So first Install httpd rpm.

In simple Words Apache or httpd is same as WAMP and XAMMP Server in windows because both are PHP base servers.So it means you can create your webpages and can actually execute them on your local system.

So lets make a Simple webpage,after installation of HTTP rpm

Now:

STEP1:

Cd /var/www/html/

Vi index.html (you should know every website need index page which meant to home page of a website)

<html>

<body>

<h1> this is sample page of Webiste</h1>

</body>

</html>

Step2:

vi /etc/hosts

192.168.1.1 websitename.com websitename (your website gonna run with your own ipaddress also with name but you have to mention it here as I did )

STEP3:

Go to browser and write your website name or ipaddress. Make sure firewall and selinux set it properly. Now it will work.

#### How about making more than one website .So that’s called Virtual host. Because every website on hosting works in WWW folder and by default httpd consists /var/www/html …. But we can give permission to another website with creating one more directory there for new website.

Page 91: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Step 1:

Mkdir /var/www/jimmy.com

Cd /var/www.jimmy.com

CREATE a INDEX PAGE WITH HTML CODE AS I DID IN HTML DIRECTORY.

STEP2:

## IN redhat 6 there is virtualhost tag inside that everything mentioned properly and easy to understand but in redhat 7 you have to add by your own at end of the httpd.conf file

Vi /etc/httpd/conf/httpd.conf

NameVIrtualHost ippadreess:80

<VirtualHost>

ServerAdmin [email protected]

DocumentRoot /var/www/jimmy.com

ServerName website.com

ErrorLog logs/websitename_error_log

CustomLog logs/websitename_access custom

</VIrtualHost>

Step 3: Add this entry in host file same as we did last time but with this website name that our can also ping with this name.

But if you use ipaddress then it will take first website because first one is more priority than other`s.

Page 92: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

SSL Certificate SSL is Secure Sockets layer. Main point is ,it encrypts website data. It means first you have to accept the certificate and then it will decrypt it and will show you website.

For that first you have install “GENKEY” rpm.

After installing :-

Genkey websitename

Then it will give you Terminal UI ,that’s interface where you will see everything and work with that layout not any command or anything .

With first option ,it will ask for method ,Please do remain what is recommended then next don’t encrypt data because you do so ,then every time person opens it ,it will ask for password so just next ,Now wait for while until it will do its works, after that read carefully what`s written above the progress bar . and do same what it is asking for….now add your information and it will give you successful option.

Step2: vi /etc/httpd/conf.d/ssl.conf

#here find servername and change it ,you can change your Document root if you want to .

#second go down and find cert and key file and change there name ,if you want to see your key and cert file ,you can do “LS “ on given path of cert and key in ssl.conf file.

“etc/pki/tls/certs”

“etc/pki/tls/private”

After that save your file and now run your website with https://websitename

That’s it

Page 93: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Chapter 19: Shell Scripting Scripting

Scripting is running multiple commands through a file. For example:

Vi scrip.sh

Ls

Time

Date

(save it :x)

Now execute it. With:-

Sh scrip.sh or bash scrip.sh

Now you will see it why it is know as Scripting because in Programming Stuff there are so many other things such as loops,variables and syntaxs. But no doubt Shell scripting consisting everything as Programming but you can say it consists commands also.

Lets start with this file :-

Vi ~/.bash_profile ( simply this file stores HOME of particular shell or path of your current directory ,because this file executes every time when you system starts up, so you can add any command here that you wanna excute at the time of system starting up)

If you do write on your bash :-

Echo $HOME (it will show you your home directory , because HOME is already a envoirment variable ) there are two types of variables by system and for system ,you can use those also:-

Set -o (to on the some features of your shell ,but it will show you only off to see all those are on shopt -s , to on e.g:- set –o nocobbler (these are some intresting facts that you should know about it) )

SET (these are some shell variables that are only for shell ,but to make any of your variable as enviorment variable to use any anywhere )

Page 94: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Env ( to see all enviorment variable)

## making your on variable as environment variable but if you do simple as:

Jimmy=5 ;echo $jimmy and after that you should see It in “set” you will see your variable but you cant see in Env list for that:-

Export Jimmy=5

Now you can check this in “env” .

And you can use that variable for any of your script

Other files that are same work like bash_profile ,that are called ,LOGIN file for local user on system,e.g:- root

~/.bashhistory

~/.bashrc

Lets start with scripting ,

First line whenever you start writing any script is :-

#!/bin/bash (#!Shbang sequenece ,its name and bash is shell where you are going to execute it)

# there is shell with name BASH , there are plenty of shells in Linux Enterprise,you can download it and install it .but bash shell is latest shell i.e used currently.

# to find shells:

Yum search shells

Or

Ls /etc/bin

When you write a script:-

Page 95: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Vi jimmy.sh

#!/bin/Bash/

Echo “HI”

J=5;

Echo $J

##this is just a example, as here to print a string use “” this and to value and declaring variable simple put value in variable and by $ sign use it .

But its not it , first you have to make your file Executable for that ,you already know how to give executable permission.

Chmod 777 jimmy.sh

## how to get value from user .

Vi argue.sh

#!/bin/bash/

Echo –n “Enter you Name ”

# -n user for to continue in same line

Read NAME

# user variables in capital letters than can easily findable from long script .

Echo $NAME

##save it and execute it .

To get multiple values at a time .e.g:-

Echo –n “whats your First name and lAst name ”

Read FIRST LAST

Echo $FIRST $LAST

Page 96: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

# TO Ask value in read statement itself.

Read –p “Enter your age ” AGE

# -p used for print, -s invisible string, -t time

Echo $AGE

# TO perform arithmetic operations

Echo $(( 4 + 2 ))

# How do you find tags such as ls , pwd are executing from where ,I mean there main directory , for this :-

Type –a ls (ls is tag In this example)

Or

Which ls

Conditional Logic Operators :

You already did Redirections ,these are same as that ,but for that you have to learn this whenever your command executes ,it gives you ,

0 and if there is any error it will give you some oter number, to specify status number

$?

To use this simply use

Echo $?

Or

With last of your script.

Exit $?

…………………………….

Lets start condition logics :-

Page 97: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

You may have did this in C or C++ or any other programming language .

||

&&

!

e.g 1.

Echo “hi” || ls

# this is execute both , what it means is “OR” statement , doesn’t matter first command works or not, second will gonna work anyway.

e.g 2.

Ls –q && grep “root”

This is AND logical operators, If first will work only and only then second will work

e.g 3:-

! – f /etc/yum.d (-f file )

Conditional Logics:-

(You can find this in book Bash Scripting in Chapter 4 by Vivek Gite.)

if $((5 < 2)) or if (5 –le 2) le also means less than equal to

then

echo “condition true”

else

echo “not true”

fi //( this is how if condition ends )

Page 98: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

## to check file is or not

If [-f /etc/yum.conf]

Then

Echo “It is a file”

Else

Echo “its not a file”

Fi

2. test condition

Test 5 < 2 && echo “true”

E.g:

If test –f /etc/vsftpd/vsftpd.conf

Then

Echo “file”

Echo “not a file”

Fi

# to check two strings are equal or not

iF test “hi” == “hi” // [condition use] these brackets

Then

Echo “same”

Else

Echo “not same”

Page 99: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Fi

##NESTED IF

If [condition]

Then

If [condition]

Then

……

Else

……….

Fi

Else

………….

Fi

#### Multiple if`s

If [condition]

Then

Elif [condition2]

Then

Elif [condition3]

Then

Else

Page 100: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Fi

E.g:

Read –p “enter value” VALUE

If [$VALUE –eq 0]

Then

###Echo “yup” (your choice wanna write or not)

Elif [$VALUE –ge 0]

Then

Echo “YUP”

Else

Echo “find out ”

Fi

##### as I told you before about exit status :-

date # run date command

echo $?

### to find out file or directory

-f (test –f path)

-d (test -d path or you can use “ ! –d /etc/yum.conf “)

-e file exists or not

-h file True if file exists and is a symbolic link. -k file True if file exists and its ‘‘sticky’’ bit is set.

Page 101: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

-p file True if file exists and is a named pipe (FIFO). -r file True if file exists and is readable

Bash shell set several special parameters. For example $? (see return values section) holds the return value of the

executed command.

All command line parameters or arguments can be accessed via $1, $2, $3,..., $9.

• $* holds all command line parameters or arguments.

• $# holds the number of positional parameters.

• $- holds flags supplied to the shell.

• $? holds the return value set by the previously executed command.

• $$ holds the process number of the shell (current shell).

• $! hold the process number of the last background command.

• $@ holds all command line parameters or arguments.

## e.g of what is $1 and $2

Vi re.sh

#!/bin/bash/

Echo $1 $2

Run your script with this

Sh re.sh 5 6 (here are two arguments are passing first is 5 and second is 6)

## Switch case

Page 102: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Case $var in

Mon) …..body ;; //(;; for break or you can write break itself)

Tues) …body ;;

*) //*) default

Echo “not an option”

esac

##LOOP STATEMENTS

For VAR in values

Do

Body

Done

e.g:

for J in 1 2 3

do

echo $J

done

OR AS C and C++

for (( EXP1; EXP2; EXP3 )) do command1 command2 command3

Page 103: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

done

e.g:-

for I in $* ($* holds the arugements)

do

echo “its car” $I

echo “NO ,Its my baby” $I

done

## Nested loop

For variable in value

Do

For variable in value

Do

Body

Done

Done

##While loop

While [condition]

Do

Page 104: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Body

Done

Note: while is same as if but it can work as well as for.

e.g:

#!/bin/bash

N=1

While [$N -le 5]

Do

Echo “Yup”

N =$((++N))

Done

## infinite loop

While :

Do

Echo “this is infinite loop,to quit Press ctrl + c”

Done

##Until Loop

Until is same as while , difference is where you wrote ,while , just replace it with UNTIL.

## Select LOOP statement

Concept select is to making case or switch statement a loop

Select varname in list

Do

Page 105: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Case $varname in

Pattern1)

Body;;

Pattern2)

Body;

*)

Body;;

Esac

done

Note: there is one more way to making case statement loop, with continue statement , what continue does is ,it will not break the scriot ,it will executes that again after working first time, so just replace continue instead of break.

##INPUT OUTPUT redirection. Redirection we already did , there are three kinds of redirections

INPUT 0

Cat << filename

OUTPUT 1

ls >cat filename

ERROR 2

Sh filename.sh 2> filename

Page 106: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

## Creating Functions:-

Functionname()

{

Body….

}

#you can call function anywhere in script. By just :-

Functionname()

##SUBSHELL

Sub shell means shell inside shell, Basically that’s what you do when you define #!/bin/bash

Or you can do that without it , Just open the terminal .

And write “bash” ,you will be in SUBSHELL and for exit it , just write EXIT.

SOME Important and other commands:-

Exec -- it will replace the current shell

The exec() family of functions replaces the current process image with a new process image.

Page 107: Redhat 6 & 7

RHCSA in Redhat 7 – by Navdeep Singh Jimmy

Pending Topics:- IPv6

MariaDB

Linking and Bridging

Remote Block Storage

Linux Containers and Dockers

Configure the Shell Enviorment