Download as pdf or txt
Download as pdf or txt
You are on page 1of 91

Managing File From Command Line

June 23, 2019

On a Linux system, everything is a file; if something is not a file, it is a process. Most files are
regular fils; they contain normal data, for example text files, executable file or programs, input or
output from a program and so on. As Linux stores data and program in files. These are organized
in directories. A directory is just a file that contains other files or directories.

File System Structure:

In Windows operating system, we have C:\ drive, and there are many directories under C:

, such as Documents and Settings, Program Files, etc. In Linux, we can think of /(root directory)
as C drive in Windows. All files system directory or mount points in Linux are under / directory.
There are many directories full of child directories and files. Some directories such as bin, sbin,
and lib can be found in several other directories too. The following table describes many of the
most command Linux directories. Some file system and directories structure in one Linux
distribution maybe different from other Linux distributions.

File System Hierarchy:

All files on a Linux system are stored on file systems which are organized into a single inverted
tree or directories, known as a file system hierarchy. In the inverted tree, root lies at the top and
the branches of directories and sub-directories stretch below the root.

/ Root directory of the system


/bin Keeps binary files for user application (bash, ls, mount, tar, etc.)
/sbin Keep static binary files for system program. (fdisk, fsck, init, etc)
/etc Directory contains static, persistent system configuration data
/dev Device and hardware files are store here
/proc Virtual filesystem providing process and kernel information as files
/var Keeps system log files
/tmp All users have permission to place temporary files here.
/usr Keeps Linux system files installed software, shared libraries etc
/home Location of users personal home directories and configuration
/boot Files needed in order to start the boot process
/lib Libraries essential for the binaries, keep System Libraries
/opt Optional application software packages
/mnt Temporarily mounted filesystems
/media Mount points for removable media such as CD-ROMs
/root The root (super-user)home directory
/srv Service data

Locating Files by Name:

To locating a files or folders by name we can use absolute path or relative path.

Path:

A path is a unique location to a file or a folder in a file system of an OS. A path to a file is a
combination of / and alpha-numeric characters.

Absolute Path:

An absolute path is define as the specifying the location of a file or directory from the root
directory (/). Absolute path is a complete path from start of actual filesystem from / directory.

Such as a folder name doc on a root desktop: #cd /root/Desktop/doc

Relative Path:

Relative Path is identifies a unique file, specifying only the path necessary to reach the file from
the working directory. A path name with anything other than a forward slash (/) as a first
character is a relative path name. Such as a folder name doc on a root desktop: #cd doc

Navigating Paths:

Many task rely on being able to get to, or reference the correct location in the system. A lot of
command on the terminal will rely on you being in the right location. A you’re moving around.
The first command for Navigation around is pwd which stands for (Print Working Directory) this
command just tells what your current or present working directory is. in order to move around in
the system, we use a command called cd which stands for change directory.

Navigation path commands

cd – Change Directory (change Directory)

[cms@asim ~]$ cd Desktop

cd.. – Moves one level up in the directory

[cms@asim Desktop]$ cd ..

cd / – Moves using absolute path

[cms@asim ~]$ cd /run/media


cd~ – Change to user’s home directory

[cms@asim media]$ cd ~ [cms@asim ~]$ pwd


/home/cms

cd – – Changes to previous working directory

[cms@asim ~]$ cd – /run/media

cd../ ..- Changes to two levels up

[cms@asim media]$ cd ../.. [cms@asim /]$

pwd – Print Working Directory

[cms@asm ~]$ pwd /home/cms

ls – Show you list of directory(list)

[cms@asim ~]$ ls
Desktop Documents Downloads Music Pictures Public Templates Videos

ll – Same is ls-l list conteents of directory in long format

[cms@asim ~]$ ll total 0 drwxr-xr-x. 2 cms cms 18 Jun 19 12:10 Desktop drwxr-xr-x. 2 cms
cms 6 Jun 12 17:33 Documents drwxr-xr-x. 2 cms cms 6 Jun 12 17:33 Downloads drwxr-xr-x.
2 cms cms 6 Jun 12 17:33 Music drwxr-xr-x. 2 cms cms 6 Jun 12 17:33 Pictures drwxr-xr-x. 2
cms cms 6 Jun 12 17:33 Public drwxr-xr-x. 2 cms cms 6 Jun 12 17:33 Templates drwxr-xr-x. 2
cms cms 6 Jun 12 17:33 Videos

ls -r – Reverse the sort order (r=Reverse)

[cms@asim ~]$ ls -r
Videos Templates Public Pictures Music Downloads Documents Desktop

ls -t – List the most recent files first (t=time)

[cms@asim ~]$ ls -t
Desktop Documents Downloads Music Pictures Public Templates Videos

ls -S – List the biggest files first (s=Size)


[cms@asim ~]$ ls -s total 0 0 Desktop 0 Downloads 0 Pictures 0 Templates 0 Documents 0
Music 0 Public 0 Videos

ls -l – List content of directory in long format (long)

[cms@asim ~]$ ls -l total 0 drwxr-xr-x. 2 cms cms 18 Jun 19 12:10 Desktop drwxr-xr-x. 2 cms
cms 6 Jun 12 17:33 Documents drwxr-xr-x. 2 cms cms 6 Jun 12 17:33 Downloads drwxr-xr-x.
2 cms cms 6 Jun 12 17:33 Music drwxr-xr-x. 2 cms cms 6 Jun 12 17:33 Pictures drwxr-xr-x. 2
cms cms 6 Jun 12 17:33 Public drwxr-xr-x. 2 cms cms 6 Jun 12 17:33 Templates drwxr-xr-x. 2
cms cms 6 Jun 12 17:33 Videos

ls -a – List contents of directory including hidden files (All)

[cms@asim ~]$ ls -a . .bash_logout .cache Desktop .esd_auth .mozilla Public


.. .bash_profile .config Documents .ICEauthority Music Templates
.bash_history .bashrc .dbus Downloads .local Pictures Videos

ls -h – List contents of directory in human readble (Human)

[cms@asim ~]$ ls -h
Desktop Documents Downloads Music Pictures Public Templates Videos

Managing files command tools

#cp – Copy files from source to destination (copy)

[cms@asim Desktop]$ cp file1 file4

#cp-r – Copy folder from source to destination (Recursive)

[cms@asim Desktop]$ cp -r file1 file6

#rm – Removes files (Remove)

[cms@asim Desktop]$ rm file4

#rm -r – Remove folder (Recursive)

[cms@asim Desktop]$ rm -r file6

#rm -f – Remove files or folder forcefully(Forecfully)

[cms@asim Desktop]$ rm -f file2


#rm-rf – Force to remove folder (Recursive Forcefully)

[cms@asim Desktop]$ rm -rf dir1

#mkdir – make empty folder (Make Directory)

[cms@asim Desktop]$ mkdir dir1

#mkdir {1,2,3,4} – Make more than one empty folders

[cms@asim Desktop]$ mkdir {1,2,3,4} [cms@asim Desktop]$ mkdir dir2 dir3 dir4

#mkdir {1..10} – Make sequence of files from 1 to 10

[cms@asim Desktop]$ mkdir {1..10} [cms@asim Desktop]$ ll total 4 drwxrwxr-x. 2


cms cms 6 Jun 22 15:58 1 drwxrwxr-x. 2 cms cms 6 Jun 22 15:58 2 drwxrwxr-x. 2
cms cms 6 Jun 22 15:58 3 drwxrwxr-x. 2 cms cms 6 Jun 22 15:58 4 drwxrwxr-x. 2
cms cms 6 Jun 22 15:58 5 drwxrwxr-x. 2 cms cms 6 Jun 22 15:58 6 drwxrwxr-x. 2
cms cms 6 Jun 22 15:58 7 drwxrwxr-x. 2 cms cms 6 Jun 22 15:58 8 drwxrwxr-x. 2
cms cms 6 Jun 22 15:58 9 drwxrwxr-x. 2 cms cms 6 Jun 22 15:58 10

#rmdir <folder> – Remove empty folder (Remove Directory)

[cms@asim Desktop]$ rmdir dir1

#rmdir {1..10} – Remove sequence from 1 to 10

[cms@asim Desktop]$ rmdir {1..10}

#mv <s><d> – Move or rename files or folders (Move)

[cms@asim Desktop]$ mv file3 file9

#touch – Create empty files

[cms@asim Desktop]$ touch f1

#touch {1,2,3,4} – Creating more than one empty files

[cms@asim Desktop]$ touch {1,2,3}

#cmp – Compare two files


[cms@asim Desktop]$ vim f1 [cms@asim Desktop]$ vim f2 [cms@asim Desktop]$ cmp f1 f2
f1 f2 differ: byte 1, line 1

#comm – Displays what is command between files

[cms@asim Desktop]$ comm f1 f2 hi my name is asim Today i will teach you chp no 2

#dir – Briefly list directory contents

[cms@asim Desktop]$ dir dir1 f1 touch2

#tail – Display last few lines of a text file

[cms@asim Desktop]$ tail /etc/passwd gnome-initial-setup:x:988:982::/run/gnome-initial-


setup/:/sbin/nologin sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
avahi:x:70:70:Avahi mDNS/DNS-SD Stack:/var/run/avahi-daemon:/sbin/nologin
postfix:x:89:89::/var/spool/postfix:/sbin/nologin tcpdump:x:72:72::/:/sbin/nologin
cms:x:1000:1000:cms:/home/cms:/bin/bash ldap:x:55:55:OpenLDAP
server:/var/lib/ldap:/sbin/nologin ldapuser1:x:1001:1001::/home/ldapuser1:/bin/bash
ldapuser2:x:1002:1002::/home/ldapuser2:/bin/bash
apache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin

#tail -n – Display last given number of line of text file (Number)

[cms@asim Desktop]$ tail -n 3 /etc/passwd

ldapuser1:x:1001:1001::/home/ldapuser1:/bin/bash
ldapuser2:x:1002:1002::/home/ldapuser2:/bin/bash
apache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin

#head – Display first few lines of a text file

[cms@asim Desktop]$ head /etc/passwd root:x:0:0:root:/root:/bin/bash


bin:x:1:1:bin:/bin:/sbin/nologin daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin

#head -n – Display first given number of line of text file ( Number)

[cms@asim Desktop]$ head -5 /etc/passwd root:x:0:0:root:/root:/bin/bash


bin:x:1:1:bin:/bin:/sbin/nologin daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
#wc – Count lines, Words and characters

[cms@asim Desktop]$ wc /etc/passwd 48 95 2509 /etc/passwd

#wc -l – Count lines only

[cms@asim Desktop]$ wc -l /etc/passwd 48 /etc/passwd

#wc -w – Count words only

[cms@asim Desktop]$ wc -w /etc/passwd 95 /etc/passwd

#wc -c – Count characters only

[cms@asim Desktop]$ wc -c /etc/passwd 2509 /etc/passwd

#cat – Display contents of a text file

[cms@asim Desktop]$ cat f1 hi my name is asim

#cat -n filename – To see how many lines are written in the file (Number)

[cms@asim Desktop]$ cat -n f1 1 hi my name is asim

#less – Display the contents of a text file page wise

[cms@asim Desktop]$ less f1

#diff – Display the difference between file

[cms@asim Desktop]$ diff f1 f2 1c1 < hi my name is asim — > Today i will teach you chp no 2

#file – Display the information about file contents

[cms@asim Desktop]$ file f1 f1: ASCII text

Matching File Name Using Path Name Expansion:

Often, needs to perform a single operation on many filesystem objects. For example, if we
needed to create multiple directories all beginning with the name “Doc” and then followed by a
number, we could issue the command: mkdir Doc1 Doc2 Doc3 Doc4. it will be very quiet time
consuming if there were a lot to create. However, we could save a lot of time by issuing the
command: mkdir Doc(01..10). Basic appreciation of wildcards, pattern matching and expansion
technique can rescue us.

Wildcard or Globbing:

A wildcard or Globbing (because it was originally implemented as a program called /etc/glob) is


a symbol used to replace or present one or more characters. Wildcards are typically either an
asterisk (*), which represents one or more characters or question mark (?), which represents a
single character or Open and close brackets ([]) which match a single character in range.

Pattern Matching Characters:

f* – Only filename beginning with “f”

[cms@asim Desktop]$ ls f* f1 f2 file9

*f – Only filenames ending in “f”

[cms@asim Desktop]$ ls *f ff

*f* – Only filenames containing a “f”

[cms@asim Desktop]$ ls *f* f1 f2 ff file9

[!f*] – Only filenames where first character is not “f”

[cms@asim Desktop]$ ls [!f*] 1: 2: 3: 4:

???* – Only filenames at least 3 characters in length

[cms@asim Desktop]$ ls ???* file9 pass 1..10: dir1: f1 touch2 dir2: dir3: dir4:

*[[:digit:]]* – Only filenames that contain a number

[cms@asim Desktop]$ ls *[[:digit:]]* b1 f1 f2 file9 1: 1..10: 2: 3: 4: dir1: f1 touch2 dir2:


dir3: dir4:

Access the Command Line


June 22, 2019

Command Line:
A command Line, CLI, Command Line Interface, or Terminal, is a text based interface to the
system. Enter the commands by typing them on the keyboard and feedback will be given back by
Command Line or Terminal. The command line typically presents a prompt. As type, it will be
displayed after the prompt. Most of the time you will be issuing commmands. A command line is
a text-based interface which can be used to input instruction top a computer system.

Shell:
A shell is a user inteface to a computer system that relies on keyboard input. Shell is a command
language interpreter that executes commands read from the standard input keyboard of from a
file. Shell is not part of system kernel, but uses the system kernel to execute programs, create file
etc. The dedault Linux command line interface or terminal is the Bourne Again SHell or Bash
Shell. A bash is a command interpreter. The Bash Shell is similar in concep to the command line
interpreter found in Microsoft Windows CMS.
Type the command #echo $O or #echo $SHELL in the terminal to see which shell you are using

Command:
A command is an instruction given by a user telling a computer to do something, command the
name of the program to run. Commands are generally issued by typing them in at the command
line and then pressing the ENTER key, which passes them to the shell. One command consists of
three parts, Command name, Options, and Arguments.
Example: command-name optionA optionB argument1 argument2. Command[options]
[arguments].
Between command-name, Option and arguments, space is necessary. Option always start with
“_”
OR “–“.
Example: ls -l /etc where ls is a Command name -l is Option and /etc is Arguments

Kernel:
The Kernel is a software code that servers as a layer between the hardware and main programs
that runs on a computer. It is the first part to load when the OS boots up. Its loaded in memory
and stay there throughout the entire time the computer is in session. The Linux kernel allows for
communication between the hardware via drivers included in the kernel or added via kernel
modules and the software. It also responsible for the eddicient managemet of the system’s
resources such as memory management, process and task management, and dick management.

GNOME:
GNOME stands for GNU Network Object Model Enviroment. GNOME is a full point-and-click
enviroment — colors, little, pictures, the works. GNOME is a desktop enviroment and graphical
user interface that runs on top of a computer operating system. Is is composed entirely of free
and open source software. It is an international project that includes ceating software
development frameworks, selecting application software fot the desktop, and working on the
program that manage application launching, files handling, and window and task management.
GNOME can be used with various Unix like operating systems.
KDE:
KDE stands for K Dekstop Enviroment. KDE is a desktop working platform with a graphical
user interface (GUI) released in the form of an open-source package. It is a sdesktop enviroment
for Linux based operating system. KDE as a GUI forLinux OS. KDE has proved Linux user to
make it use as easy as they use windows. KDE provides Linux users a graphical interface to
choose their own customized dekstop enviroment.

Different between a normal user and a super user.

When a regular user starts a shell, the default prompt ends with a $ character.
E.g. [student@desktop ~]$

When a super user starts a shell, the default prompts end with a # character. This makes it more
obvious that is a superuser shell, which helps to avoid accidents and mistakes in the privileged
account. Super user is also called as root.
E.g. [root@desktop -]#

mportant Console Access Terms

Shell – The interpreter that executes commands types as string.


Prompt – The visual cue that indicates an interactive shell is waiting for the user to type a
command.
Command – The name of a program to run.
Options – The part of the command line that adjust the behavior of a command.
Argument – The part of the command lie that specifies the target that the command should
operate on.
Physical console – The hardware display and keyboard used to interact with a system.
Virtual console – One of multiple logical consoles that can each support an independent login
session.
Terminal – An interface that provides a display for output and a keyboard for input to a shell
session.

Bash command and keyboard shortcuts

Ctrl + Left Arrow – Jump to the beginning of the previous word on the command line.
; – Separate commands on the same line.
Ctrl + k – Clear from the cursor to the end of the command line.
!string – Re-execute a recent command by matching the command name.
Tab – Shortcut used to complete commands, file names, and options.
!number – Re-execute a specific command in the history list.
Ctrl + a – Jump to the beginning for the command line
history – Display the list of previous commands.
Esc+. – Copy the last argument of previous commands.

Basic Commands
[cms-lab1@localhost ~]

$ whoami
cms-lab1

[root@localhost ~]

# whoami
root

date – The date command is used to display the current date and time.

[cms-lab1@localhost ~]

$ date
Sat Jun 8 10:36:41 IST 2019

[cms-lab1@localhost ~]

$ date +%R
10:37

[cms-lab1@localhost ~]

$ date +%r
10:37:35 AM

[cms-lab1@localhost ~]

$ date +%x
06/08/2019

[cms-lab1@localhost ~]

$ date +%X
10:38:04 AM

[root@localhost ~]

# cal
June 2019
Su Mo Tu We Th Fr Sa
1
2345678
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30

Changing User from normal to superuser(root)

[cms-lab1@localhost ~]

$ su root
Password:

[root@localhost cms-lab1]

#
or

[cms-lab1@localhost ~]

$ su –
Password:
Last login: Sat Jun 8 10:49:59 IST 2019 on pts/0

[root@localhost ~]

Changing User from superuser to normal user.

[root@localhost ~]

# su cms-lab1

[cms-lab1@localhost root]

$ cd ~

[cms-lab1@localhost ~]

$
Note: We used “cd ~” command to change the directory from root to normal user.

passwd – The passwd command changes a user’s own password.

[cms-lab1@localhost ~]

$ passwd
Changing password for user student.
Changing password for student.
(current) UNIX password: old_password
New password: new_password
Retype new password – new_password
passwd: all authentication tokens update successfully.

file – Linux does not require the file name extensions to classify by type. The file command
scans the beginning of a file’s contents and display what type it is. The files to be classified are
passed as argument to the command.

[cms-lab1@localhost ~]

$ file /etc/passwd
/etc/passwd: ASCII text

[cms-lab1@localhost ~]

$ file /bin/passwd
/bin/passwd: setuid ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically
linked (uses shared libs), for GNU/Linux 2.6.32,
BuildID[sha1]=0a16a7915f7f9b01d96442755257e22067ce5b2c, stripped

[cms-lab1@localhost ~]

$ file /home
/home: directory

ls for Listing Files – If you want to see the list of files on your Linux system, uuse the ‘ls’
command.

[cms-lab1@localhost ~]

$ ls
Desktop Documents Downloads Music Pictures Public Templates Videos

[cms-lab1@localhost ~]

$ ls -l
total 0
drwxr-xr-x. 2 cms-lab1 cms-lab1 6 Jun 1 12:26 Desktop
drwxr-xr-x. 2 cms-lab1 cms-lab1 6 Jun 1 12:26 Documents
drwxr-xr-x. 2 cms-lab1 cms-lab1 6 Jun 1 12:26 Downloads
drwxr-xr-x. 2 cms-lab1 cms-lab1 6 Jun 1 12:26 Music
drwxr-xr-x. 2 cms-lab1 cms-lab1 6 Jun 1 12:26 Pictures
drwxr-xr-x. 2 cms-lab1 cms-lab1 6 Jun 1 12:26 Public
drwxr-xr-x. 2 cms-lab1 cms-lab1 6 Jun 1 12:26 Templates
drwxr-xr-x. 2 cms-lab1 cms-lab1 6 Jun 1 12:26 Videos

If you want to see hidden files on your Linux system, use ‘ls -a’ command.

[cms-lab1@localhost ~]

$ ls -a
. .bash_profile Desktop .ICEauthority Pictures
.. .bashrc Documents .local Public
.bash_history .cache Downloads .mozilla Templates
.bash_logout .config .esd_auth Music Videos

You can use ‘ls-R’ to shows all the files not only in directories but also in subdirectories

[cms-lab1@localhost ~]

$ ls -R
.:
Desktop Documents Downloads Music Pictures Public Templates Videos

./Desktop:

./Documents:

./Downloads:

./Music:

./Pictures:

./Public:

./Templates:

./Videos:

‘ls -al’ gives detailed information of the files. The command provices information in a columnar
format.

[cms-lab1@localhost ~]

$ ls -al
total 36
drwx——. 14 cms-lab1 cms-lab1 4096 Jun 8 10:50 .
drwxr-xr-x. 3 root root 21 Jun 1 18:50 ..
-rw——-. 1 cms-lab1 cms-lab1 5 Jun 1 12:31 .bash_history
-rw-r–r–. 1 cms-lab1 cms-lab1 18 Jul 8 2015 .bash_logout
-rw-r–r–. 1 cms-lab1 cms-lab1 193 Jul 8 2015 .bash_profile
-rw-r–r–. 1 cms-lab1 cms-lab1 231 Jul 8 2015 .bashrc
drwx——. 10 cms-lab1 cms-lab1 4096 Jun 1 12:27 .cache
drwxr-xr-x. 15 cms-lab1 cms-lab1 4096 Jun 1 12:27 .config
drwxr-xr-x. 2 cms-lab1 cms-lab1 6 Jun 1 12:26 Desktop
drwxr-xr-x. 2 cms-lab1 cms-lab1 6 Jun 1 12:26 Documents
drwxr-xr-x. 2 cms-lab1 cms-lab1 6 Jun 1 12:26 Downloads
-rw——-. 1 cms-lab1 cms-lab1 16 Jun 1 12:26 .esd_auth
-rw——-. 1 cms-lab1 cms-lab1 628 Jun 8 10:36 .ICEauthority
drwx——. 3 cms-lab1 cms-lab1 18 Jun 1 12:26 .local
drwxr-xr-x. 4 cms-lab1 cms-lab1 37 Jun 1 18:21 .mozilla
drwxr-xr-x. 2 cms-lab1 cms-lab1 6 Jun 1 12:26 Music
drwxr-xr-x. 2 cms-lab1 cms-lab1 6 Jun 1 12:26 Pictures
drwxr-xr-x. 2 cms-lab1 cms-lab1 6 Jun 1 12:26 Public
drwxr-xr-x. 2 cms-lab1 cms-lab1 6 Jun 1 12:26 Templates
drwxr-xr-x. 2 cms-lab1 cms-lab1 6 Jun 1 12:26 Videos

head tail – The head and tail command display the beginning and end of a file respectively. By
default, these commands display 10 lines, but they both have a -n option that allows a different
number of lines to be specified. The file to display is passed as an arguments to these commands.

[cms-lab1@localhost ~]

$ head /etc/passwd
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin

[cms-lab1@localhost ~]

$ tail /etc/passwd
mysql:x:27:27:MariaDB Server:/var/lib/mysql:/sbin/nologin
gnome-initial-setup:x:989:984::/run/gnome-initial-setup/:/sbin/nologin
avahi:x:70:70:Avahi mDNS/DNS-SD Stack:/var/run/avahi-daemon:/sbin/nologin
postfix:x:89:89::/var/spool/postfix:/sbin/nologin
dovecot:x:97:97:Dovecot IMAP server:/usr/libexec/dovecot:/sbin/nologin
dovenull:x:988:983:Dovecot’s unauthorized user:/usr/libexec/dovecot:/sbin/nologin
sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
ntp:x:38:38::/etc/ntp:/sbin/nologin
tcpdump:x:72:72::/:/sbin/nologin
cms-lab1:x:1000:1000:cms-lab1:/home/cms-lab1:/bin/bash

[cms-lab1@localhost ~]

$ head -n 4 /etc/passwd
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin

[cms-lab1@localhost ~]

$ tail -n 3 /etc/passwd
ntp:x:38:38::/etc/ntp:/sbin/nologin
tcpdump:x:72:72::/:/sbin/nologin
cms-lab1:x:1000:1000:cms-lab1:/home/cms-lab1:/bin/bash

wc – the wc command count lines, words and characters in a file. It can take a -l, -w, or -c option
to display only the lines words, or characters, respectively.

[cms-lab1@localhost ~]

$ wc /etc/passwd
48 98 2593 /etc/passwd

[cms-lab1@localhost ~]

$ wc -l /etc/passwd
48 /etc/passwd

[cms-lab1@localhost ~]

$ wc -c /etc/passwd
2593 /etc/passwd

[cms-lab1@localhost ~]

$ wc -c /etc/group
1039 /etc/group

[cms-lab1@localhost ~]
$ wc -c /etc/hosts
158 /etc/hosts

[cms-lab1@localhost ~]

$ wc -w /etc/passwd
98 /etc/passwd

Tab completion – Tab completion allows a user to quick complete commands or file names once
they have typed enough at the prompt to make it unique. if the characters type are not unique,
pressing the Tab key twice displays all commands that begin with the characters already typed.

[cms-lab1@localhost ~]

$ pas
passwd paste pasuspender

[cms-lab1@localhost ~]

$ pass

[cms-lab1@localhost ~]

$ passwd
Changing password for user student.
Changing password for student.
(current) UNIX password: old_password

Print command (pr) – This command helps in formating the file for printing on the terminal.

history – The history command display a list of previously executed commands prefixed with a
command number
The exclamation point character, !, is a meta character that is used to expand previous commands
without having retype them. !number expand to the command matching the number specified.
!string expands to the most recent command that begins with the string specified.

[cms-lab1@localhost ~]

$ history
1 su –
2 cd ..
3 ls
4 date
5 date +%R
6 date +%r
7 date +%x
8 date +%X
9 file /etc/passwd
10 file /bin/passwd
11 file /home
12 head /etc/passwd
13 tail /etc/passwd
14 head -n 4 /etc/passwd
15 tail -n 3 /etc/passwd
16 wc -c
17 wc /etc/passwd
18 wc -l /etc/passwd
19 wc -c /etc/passwd
20 wc -c /etc/group
21 wc -c /etc/host
22 wc -c /etc/hosts
23 wc -w /etc/passwd
24 history

[cms-lab1@localhost ~]

$ !ls
ls
Desktop Documents Downloads Music Pictures Public Templates Videos

[cms-lab1@localhost ~]

$ !22
wc -c /etc/hosts
158 /etc/hosts

clear – The ‘clear’ command will clear all the clutter on the terminal and gives you a clean
window to work on.

[cms-lab1@localhost ~]

$ clear

Managing Local Linux User and Group


June 28, 2019
The control of users and groups is a core element of Red Hat Enterprise Linux system
administration. The user of the system is either a human being or an account used by specific
application. Users within a group can have read permissions, write permissions, execute
permissions or any combination of read, write or execute permissions for files owned by that
group. A group is an organization unit typing users together for a common purpose, which can be
reading permissions, writing permission, or executing permission for files owned by that group.

Linux Users:

A user or account of a system is uniquely identified by a numerical number called User ID


(UID). There are two types of user = the root or Superuser and Normal user. A root or Superuser
can access all the files, while the normal user has limited access to files. A superuser can add,
delete and modify a user account. In RHEL7 the new users assign the first free UID number
available in the range starting from UID 1000 or above. UID 0 is always assigned to the
Superuser account, root. UID 1-200 is a range of “System Users” assigned statically to system
processes by Red Hat. UID 201-999 is a range of “System Users” used by system processes that

do not own files on the file system. UID 1000+ is the range available for assignment to Regular
Users. The full account information is stored in /etc/passwd file and a hash password and account
expiration information is stored in the file /etc/shadow.

Linux Group:

Linux group is a mechanism to organize a collection of users. Like the User ID, each group is
also associated with a unique ID called the GID (group ID). There are two types of groups – a
primary group and a supplementary group.

Primary Group:

By default, whenever we create user account a new group with the same user name will be
created. This group is called primary group of the user. You can associate the user with extra
groups using the usermod command. Every user has exactly one primary group. The primary
group is used by default when creating new files of directories, modifying files, or executing
commands. Primary Group information is specified in the /etc/passwd file.

Supplementary group

Supplementary group or Secondary Group are groups you are a member of beyond your primary
group. Each user is a member of a primary group and of zero or ‘more than zero’ supplementary
groups. The group information is stored in the last field of the group’s entry /etc/group and the
respective password are stored in the /etc/gshadow file.

su command:

The su command stands for Super User. It executes with no additional options. The user just
needs to add root account password. In the terminal, su also lets you access any other user
account using the required password. That’s why su also stands for substitute user or Switch
User. Simply type su followed by the user account name.

Sudo command:

sudo runs a single commands with root permission. It stands for “Super User Do” The sudo
command allows a user to be permitted to run a command as root, or as another user, based on
setting in the /etc/sudoers file. The best and safest way to edit this file is by using the visudo
command. Sudo is much better than logging in as root, or using the su “Switch User” command.

GUI Tool to Manage Users and Groups:

The user Manager application allows you to view, modify, add and delete local users and groups
in the graphical user interface. To start the user Manager application.

Application> Sundry> User and Groups. or, type system-config-users at the shell prompt.

simple add user account


[root@asim ~]# adduser abc1
Add user with caption name
[root@asim ~]# adduser -c normal-user abc2
Add user with password
[root@asim ~]# adduser -p 12345678 abc3
To see user default details
root@asim ~]# useradd -D
GROUP=100
HOME=/home
INACTIVE=-1
EXPIRE=
SHELL=/bin/bash
SKEL=/etc/skel
CREATE_MAIL_SPOOL=yes
add user with password and caption
[root@asim ~]# adduser -p 12345678 -c normal-user2 abc4
Creating username with user id
[root@asim ~]# useradd abc6 -u 1010
Modified user account caption
[root@asim ~]# usermod -c first-user abc1
Modified user account password
[root@asim ~]# usermod -p 12345678 abc2
Lock user account
[root@asim ~]# usermod -L abc3
Unlock user account
[root@asim ~]# usermod -U abc3
Modified user ID
[root@asim ~]# usermod -u 1011 abc4
Set password on user abc1
[root@asim ~]# passwd abc1
Lock password of user account
[root@asim ~]# passwd -l abc1
Unlock user account password
[root@asim ~]# passwd -u abc1
Delete user account password
[root@asim ~]# passwd -d abc1
To see the ID of the user
[root@asim ~]# id abc1
uid=1001(abc1) gid=1001(abc1) groups=1001(abc1)

[root@asim ~]# id abc2


uid=1002(abc2) gid=1002(abc2) groups=1002(abc2)
Show last logins of users
[root@asim ~]#last
Add group to the system
[root@asim ~]# groupadd xyz1
Delete a group to the system
[root@asim ~]# groupdel xyz1
To modify groups
[root@asim ~]# groupmod xyz1
To rename the group name
[root@asim ~]# groupmod -n xyz2 xyz1
Change Group ID
[root@asim ~]# groupmod -g 1021 xyz2
Add user to group member
[root@asim ~]# groupmems -a abc1 -g xyz1
List the member of the group
[root@asim ~]# groupmems -l -g xyz1
Delete user from member of group
[root@asim ~]# groupmems -d abc1 -g xyz1
User account details location
[root@asim ~]# tail /etc/passwd
postfix:x:89:89::/var/spool/postfix:/sbin/nologin
tcpdump:x:72:72::/:/sbin/nologin
cms:x:1000:1000:cms:/home/cms:/bin/bash
apache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin
abc1:x:1001:1001:first-user:/home/abc1:/bin/bash
abc2:x:1002:1002:normal-user:/home/abc2:/bin/bash
abc3:x:1003:1003::/home/abc3:/bin/bash
abc4:x:1011:1004:normal-user2:/home/abc4:/bin/bash
abc5:x:1005:1005::/home/abc5:/bin/bash
abc6:x:1010:1010::/home/abc6:/bin/bash
Password database location
[root@asim ~]# tail /etc/shadow
postfix:!!:18059::::::
tcpdump:!!:18059::::::
cms:$6$GOHH.OxaaMk93f7L$qnoTmCDuXbuuBhCqy3eRYlIjqPovG8zraTwt.5wC/070bV7g
SqoHk8VNPkmD020Rkd/lTt6Ee3ohinnUoQo2p1::0:99999:7:::
apache:!!:18073::::::
abc1::18075:0:99999:7:::
abc2:12345678:18075:0:99999:7:::
abc3:12345678:18075:0:99999:7:::
abc4:12345678:18075:0:99999:7:::
abc5:!!:18075:0:99999:7:::
abc6:!!:18075:0:99999:7:::
Group database location
[root@asim ~]# tail /etc/group
cms:x:1000:cms
apache:x:48:
abc1:x:1001:
abc2:x:1002:
abc3:x:1003:
abc4:x:1004:
abc5:x:1005:
abc6:x:1010:
xyz2:x:1021:
xyz1:x:1022:
Group password database location
[root@asim ~]# tail /etc/gshadow
cms:!!::cms
apache:!::
abc1:!::
abc2:!::
abc3:!::
abc4:!::
abc5:!::
abc6:!::
xyz2:!::
xyz1:!::
Install GUI user and group management
[root@asim ~]# yum install system-config-user
Graphical users and group management
[root@asim ~]#system-config-users

Monitoring and Managing Linux Process


June 29, 2019

Introduction:

When we run a program, those instructions are copied into memory and space is allocated for
variables and other stuff required to manage its execution. This running instance of a program is
called a process. A process is a program in execution. In simple term, any command that you
give to your Linux machine start a new process. And a program is identified by its Process ID
(PID) as well as its Parent Processes ID(PPID). A process may be in the foreground, in the
background or be suspended.

Foreground Processes:

By default, every process that you start runs in the foreground. It gets its input from the keyboard
and sends it output to the scree. They run on the screen and need input from the user. For
example, Office Programs. If you start a foreground program or process from the terminal, Then
you cannot work on the terminal, till the program is up and running. You can use the command
“fg” to continue a program which was stopped and bring it to the foreground.

Background Processes:

A background process runs without being connected to you keyboard. If the background process
requires any keyboard input, it waits. They run in the background and usually do not need user
input. For example, Antivirus. If you start background process then other task can be carried out
while the original process continue executing. To continue running the suspended command in
the background, use the “bg” command.

Daemons Process:

These are special types of background processes. Daemons are server processes that run
continuously. Most of the time, they are initialized at system startup and then wait in the
background until their service is required. A typical example is the networking daemon, xinetd,
which is started in almost every boot procedure. After the system is booted, the network daemon
just sits ad waits until a client program, needs to connect.

Example to run foreground process


[root@asim ~]# sleep 10
Example to run background process
[root@asim ~]# sleep 20 &
Press ctrl+z to suspend the fg process and type #bg to put in bg
[root@asim ~]# sleep 1000 [root@asim ~]# bg
To view process running in background
[root@asim ~]# jobs
To restart(fg) a suspended process
[root@asim ~]# fg 2
Press cntl+c to terminate fg job
[root@asim ~]# fg 2 Control + c
Running -R running or runnable(on run queue)
Sleeping-D uninterruptible sleep (usually IO)
Sleeping-S Interruptible sleep, waiting for an event to complete
Stopped-T stopped, either by a job control signal or because it is being traced
Zombie-X Dead should never be seen
Zombie -Z Zombie process, terminated but not reaped by its parent

Top Process Monitoring Command:

Top command is used to monitor processes on Linux, its display processor activity in real-time.
The processes are listed out in a list with multiple columns for details like process name, PID,
user, CPU usage, memory usage. Apart from the list of processes, the top command also shows
brief stats about average system load, CPU usage and RAM usage on the top.

Display process
[root@asim ~]# top
Check the top command version
[root@asim ~]# top -v
Display the process for specific user only
[root@asim ~]# top -u cms
[root@asim ~]# top
Shift+M -sort the process list by memory usage
Shift+P -sort the process list by CPU usage
Shift+N -sort the list by process ID
shift+T -sort by the running time
Shift+R -reverse the sortig order
Shift+A -Split output in multiple panels
[root@asim ~]# top
x -Highlight the sorted column with bold text
b -highlight sorted column background color
d -hanged the refresh interval
c -Display the full command path
u -View the processes of aspecific user only

PS command:

The PS (Process Status) command on Linux is one of the most basic command for viewing the
processes running on the system. The ps command is used to provide information about the
currently running processes along with detailed information like user ID, CPU usage, memory
usage, command name etc. It does not display data in real time like top commands.

Process and terminal associated with current user


[root@asim ~]# ps
View full list of processes
[root@asim ~]# ps -ef
View full list of process
[root@asim ~]# ps ax
Detailed information about processes
[root@asim ~]# ps aux
Display process by user
[root@asim ~]# ps -f -u root
Display processes by process ID
[root@asim ~]# ps -f -p 10966
Display tree view
[root@asim ~]# ps axjf

Kill Command:

The Kill command is used primarily to terminate processes. To kill, or terminate a process first
find out the PID of the process to be killed, then pass the PID number to the kill command.

To find the pid for specific prog


[root@asim ~]# pidof sleep 30
This command will also display pid of given program
[root@asim ~]# pgrep sleep
View full list of available signal
[root@asim ~]# kill -l
Gracefully terminated process
[root@asim ~]# kill 10532
Forceful terminate process
[root@asim ~]# kill -s 9 10532
Kill all the process of vim by killall or pkill
[root@asim ~]# pkill -9 sleep
To kill the vim process
[root@asim ~]# pkill vim

Control Access File with Linux


June 29, 2019

Linux is a multi-user system and therefore directories and files inside a Linux computer need to
be protected from unauthorized use. Linux file access permissions are used to control who is able
to read, write and execute a certain file. Access permissions are implemented at a file level with
the appropriate permission set based on the file owner ,the group owner of the and other access.
In Linux, directories and device are also files and therefore the file permissions apply on a
directory and device level as well, although some permissions are applied differently depending
upon whether the file is a regular file, directory or device. The access permission design allows a
good amount of flexibility in what permissions can be applied.

There are three categories of permissions which apply: read, write and execute. These
permissions affect access to files and directories. The permissions can be assigned in octal
notation or in the more easily recognized character or symbolic format.

r (Read) permission to read a file. permission to read a directory (also requires “x”)
permission to delete or modify a file. permission to delete of modify file in a
w (write)
directory
x
permission to execute a file/script. permission to read a directory(also requires ‘r’)
(Execute)

To view file and directory permissions and ownership use -l option of the ls command will
expand the file listing to include both the permissions of a file and the ownership.

IMAGE

Changing permission by symbolic method


The symbolic method of changing file permissions uses letters to represent the different groups
of permissions: u for user, g for group, and a for all. Use three symbols:+to add permissions to a
set, – to remove permissions from a set, and = to replace the entire set for a group of permission.

Providing write access to a user


[root@asim Desktop]# chmod u+w f1
Adding write permission to a grp
[root@asim Desktop]# chmod g+w f2
Adding executable permissions to others
[root@asim Desktop]# chmod o+x f1
Adding executable and write permission to all
[root@asim Desktop]# chmod a+wx f1
Replicating user permission to a group
[root@asim Desktop]# chmod u=g f1
Removing execute permission to a user
[root@asim Desktop]# chmod u=x f1
Removing execute permission to a user
[root@asim Desktop]# chmod u-x f1
Adding execute permission to others,
[root@asim Desktop]# chmod o+x f1
Providing read and write access to a user
[root@asim Desktop]# chmod o+x f1
Provide read access to user and executable to group
[root@asim Desktop]# chmod u+r,g+x f1
Remove read and write permission from user
[root@asim Desktop]# chmod u-rx f1
Provide read, write and execute to user, read and write to group and rad only to other.
[root@asim Desktop]# chmod u+rwx,g+rw,o+r f1
Adding read, write and execute to everyone
[root@asim Desktop]# chmod ugo+rwx f2

Changing permission by Numerical Method

Using number is another method which allows you to edit the permissions for all three owner,
group and other at the same time. A numeric move is from one to four octal digits, derived by
adding upon the bits with value,4,2 and1. Omitted digits a assumed to be leading zeros. The
single octal digit presents the there symbolic letters using a number weight in scheme.

Description Abbreviation Octal Binary


No Permission — 0 000
Read access r– 4 100
Write permission -w- 2 010
Execute Permission –w 1 001
Read and Write rw- 6 110
Read and Execute r-x 5 101
Write and Execute -wx 3 001
rwx rwx 7 111
Owner can read and write
[root@asim Desktop]# chmod 600 f3
Owner can read write and execute
[root@asim Desktop]# chmod 700 f3
All can read and write
[root@asim Desktop]# chmod 666 f3
All can read, write, and execute
[root@asim Desktop]# chmod 777 f3
Owner can read n write the group and other can read only
[root@asim Desktop]# chmod 644 f3

chown command:

The chown command stands for “changing owner”, and allows changing the owner of a given
file or folder, which can be a user and a group. chown command is used to change ownership as
well as group name associated to different one, whereas chgrp can change only group associated
to it.

Change the owner of file


[root@asim Desktop]# chown root f2
Change the group of a file
[root@asim Desktop]# chown :xyz1 f2
Change both owner and grp
[root@asim Desktop]# chown cms:cms f3
Chang the owner of al contents inside
[root@asim Desktop]# chown -R cms /home

chgrp command:

chgrp (change group) is a command which is useful to change group associated to a file or folder
from group to another in a Linux. This is sister command to chown which is used to change
owner of the file or folder as well as group name associate with that file.

Change to group name


[root@asim Desktop]# chgrp root f1
Change the group name of all content inside
[root@asim Desktop]# chown cms folder1

Umask:

UMASK(User Mask or User file Creation Mask) is the default given when a new file or folder is
created. The default umask 002 used for normal size. With this mask default directory
permissions are 775 and default the permissions are 664. The default umask for the root user is
022 result into default directory permissions are 755 and default permissions are 664. The
minimum UMASK value for afile is 000 to 666 .The file has 666 because only scripts and
binaries should have executed permissions, normal and regular files should have just read and
write permissions: Directories require execute permissions for viewing the contents in it, so they
can have 777 permissions. Simple subtract the umask from the default to determine the final
permission for file: 666 -002=664: simply subtract the umask from the default permissions to
determine the final permission for directory :777-002=775

Show the default UMASK in octal information


[root@asim Desktop]# umask
Show the default UMASK in symbolic notation
[root@asim Desktop]# umask -S
To change default umask value numeric value
[root@asim Desktop]# umask 02

Special Permissions:

There will be items when the standard ugo and rwx permissions don’t provide enough flexibility
to allow a group of people to work collaboratively. That’s why another set of permissions, called
“Special Permission” are available. There are three special permission that can be assign to a file
or directory apart from basic file permission (rwx). With the help of “chmod” command we can
implement the special permissions or advance permission on file and directories. SUID- Set User
ID, SGID- Set Group ID and Sticky Bit.

Set User ID(SUID):

This permission only makes sense if you apply it to a file that is an executable (shell script). You
can apply this permission with chmod command and the “s” value:chmod u+s testscript.sh The
“s” under the user’s permission means that if an “other” runs the script, then the script will run
with the same level of privileges as whoever is the owner, of this file. For example, the suid
permission on the passwd command make it possible for a normal user to change passwords by
updating few system files like /etc/passwd and /etc/shadow which cant be update by non-root
accounts. Therefore, passwd command always run with root user rights.

Set Group ID (SGID)


This is a special permission that can be applied to files and folder. You can apply SGID
permission to a file using chmod along with the ‘s’ value being attached to the group setting:
chmod g+s testscript.sh. It is being run as if run by one of the groups member.

SGID can also be used on a directory so that every file created in that directory will have the
directory group owner rather than the group owner of the user creating the file.

Sticky Bit:

If sticky bit is applied on a file or directory, then only root and owner of that file or directory can
delete it. Even if other users are having full permission they cannot delete the file or directory.
chmod o+t folder. “T”, which means sticky bit has been applied. The sticky bit is primarily used
on shared directories.

Control Services and Daemons


June 29, 2019

Daemons:

They are the processes which run in the background and are not interactive. They have no
controlling terminal. They perform certain actions at predefined times or in response to certain
events. In Linux, the names of daemons end in d. Some examples include httpd, nfsd,
sshd,named and lpd. Daemons usually perform critical system tasks such as control swap-space,
memory management and various other tasks. Service run on Windows, Daemons run on Linux.
In short, system service in Linux are called Daemons.

Introduction to Systemd:

Systemd is a system and service manager for Linux-based operating system for managing
services. Systemd as a default “service management tool. Systemd uses “units”, which can be
services (.service), mount point (.mount, device(.device), or socket (.socket). The systemctl
command manages all these types of unis. In short, Systemd is a suie of tools that provides
system and services management for the Linux operating system

Introduction to Systemctl:

system and service manager. To manage services on a systemd enabled for controlling the
systemd the systemctl command. To manage services on a systemd enabled server, our main tool
is the systemctl command. To view, start, stop, restart, enable, or disable system services
daemons, use the systemctl command

Display systemctl version


[root@asim ~]# systemctl –version
Check the installed binaries and libraries
[root@asim ~]# whereis systemctl
To start service
[root@asim ~]# systemctl start httpd.service
Or
[root@asim ~]# systemctl start httpd
Reload the services
[root@asim ~]# systemctl reload httpd
To restart the service
[root@asim ~]# systemctl restart httpd
Check the status of a service
[root@asim ~]# systemctl status httpd
Enable service to start on boot
[root@asim ~]# systemctl enable httpd
Disabled service to not to start on boot
[root@asim ~]# systemctl disabled httpd
Check if service active or not
[root@asim ~]# systemctl is-active httpd
Check if service enabled or not
[root@asim ~]# systemctl is-enabled httpd
Display a list of properties
[root@asim ~]# systemctl show httpd
Making it impossible to start
[root@asim ~]# systemctl mask httpd
Making it possible to start
[root@asim ~]# systemctl umask httpd
kill a service
[root@asim ~]# systemctl kill httpd
Check all the services running
[root@asim ~]# systemctl –t service
Analyze and Storing Logs
July 3, 2019

Introduction:

A standard logging system based on the Syslog protocol is built into Red Hat Enterprise Linux.
Many programs use this system to record events and organize them into log files. In Red Hat
Enterprise Linux 7, syslog messages are handled by two services, systemd-journald and rsyslog.

The systemd-journald daemon provides an improved log management service that collects
messages from the kernel, the early stages of the boot process, standard output and error of
daemons as they start up and run , and syslog. It writes these messages to a structured journal of
events that, by default, does not persist between reboots. This allows syslog messages and events
which are missed by syslog to be called in one central database. The syslog messages are also
forwarded by system-journald to rsyslog for further processing.

To search journald service


[root@asim ~]# yum search journal
To check the status of system-journald
[root@asim ~]# systemctl status systemd-journald
Show full details of system journal
[root@asim ~]# journalctl
Show last 10 log entries
[root@asim ~]# journalctl -n
Show last 5 log entries
[root@asim ~]# journalctl –n 5
To check the last 10 lines of journal and to check new entries as well [root@asim ~]#
journalctl -f
To check the log entry of Priority error
[root@asim ~]# journalctl –p err
Show full details
[root@asim ~]# journalctl -b
To check the today’s recorded entries
[root@asim ~]# journalctl –since today
To check previous days recorded entries
[root@asim ~]# journalctl –since yesterday –until 9:30:00
To check with PID
[root@asim ~]# journalctl _PID=1
To check with UID
[root@asim ~]# journalctl _UID=0
To check the SSH service
[root@asim ~]# journalctl _SYSTEMD_UNIT=sshd
To check the Network Manager service
[root@asim ~]# journalctl _SYSTEMD_UNIT=NetworkManager
To see the configuration file
[root@asim ~]# cat /etc/systemd/journald.conf

Store the system journal permanently:

By default, the systemd journal is kept in /run/log/journal, which means it is cleared when the
system reboots.

If the directory /var/log/journal exists, the journal will log to that directory instead. The
advantage of this is the historic data will be available immediately at boot.

However, even with a persistent journal, not all data will be kept forever. The journal has a built-
in log rotation mechanism that will trigger monthly.

By default, the journal will not be allowed to get larger than 10% of the file system it is on, or
leave less than 15% of the file system free. These values can be tuned in
/etc/systemd/journald.conf

[root@asim ~]#mkdir /var/log/journal


[root@asim ~]#chown root:systemd-journal /var/log/journal
[root@asim ~]#chmod 2755 /var/log/journal
[root@asim ~]#killall -USR1 systemd-journald

set local clocks and time zone:

The NTP (Network Time Protocol) is a standard way for machines to provide and obtain correct
time information on the internet. A machine may get accurate time information from public NTP
services on the internet such as the NTP pool Porject. A high-quality hardware clock to server
accurate time to local clients is another option.

To check time-related settings


[root@asim ~]#timedatectl
To check all time zones
[root@asim ~]#timedatectl list-timezones
To change the current time zone
[root@asim ~]#timedatectl set-timezone Asia/Kolkata
To change the current date and time
[root@asim ~]#timedatectl set-time 9:00:00
Automatically enable or disable time zone
[root@asim ~]#timedatectl set-ntp true

Manage Red Hat Enterprise Linux


networking
July 5, 2019

Introduction of IP Address

An IP address is a 32 bit number assigned to each host on a network. It is a combination


of Network ID and Host ID. It is launched by IANA- Internet Assigned Number
Authority. IANA is a department of ICANN (Internet Corporation for Assigned Names and
Numbers) is the private (non-government) non-profit corporation with responsibility for IP
address space allocation. An IP address is a software (logical) address, not a hardware (physical)
address. IP addressing was designed to allow host on one network to communicate with the host
on a different network.

An IP address is usually represented in dot-decimal notation, consisting of four-decimal numbers


separated by periods (e.g. 192.168.0.1). the first of the address usually represents a network
device (192.168.0.0), while the last part of the address identifies the host device (e.g.
192.168.0.1).

IPv4 IPv6
It has 32 bits It has 128 bits
Contain only 4 block It contain 8 block
8 bits in one block 16 bits in one block
e.g. 192.168.0.1 ABCD:0000:0000:0000:23B2:00FF:B231:12AC
Decimal Hexadecimal
Dotted (.) Colane (:)

Classes of Addressing: The developers of the internet planned to create classes of networks as
per there network size. The classes of network are:

Classes Network Range Use Leading Bits


A 0-127 (1-126 in use) Large network 1 (0)
B 128-191 Medium network 2 (10)
C 192-223 Small network 3 (110)
D 224-239 Multicast address 4 (1110)
E 240-255 R&D 4 (1111)
IP Address Class First bit value Class A 0 Class B 10 Class C 110
Range 1 to 126 128 to 191 192 to 223
Network ID bits 8 16 24
Host ID bits 24 16 8
Total no of network 126 16,384 20,97,152
Total no of host 1,67,77,214 65,534 254
Default Subnet Mask 255.0.0.0 255.255.0.0 255.255.255.0

There are two types of IP address, one is public and other is private.

Public IP address: A public IP address is assigned to every computer that connects to the
Internet where each IP is unique. Hence there cannot exist two computers with the same public
IP address all over the Internet. The public IP address is assigned to the computer by the Internet
Service Provider (ISP) as soon as the computer is connected to the Internet Gateway.

Private IP address: The private IP addresses can be used on the private network of any
organization in the world and are not globally unique.There addresses can be used on a private
network, but they’re not routable through the Internet. It is designed for the purpose of creating a
measure of well-needed security, but it also conveniently saves valuable IP address space.
Network interface Names:

Ethernet interface begin with en, WLAN interface bein with wl, and WWAN interfaces begin
with ww. The next character represents the type of adapter with an o for on-board, s for hot-
plugslot, and p for PCi. a number N is used to represent an index, ID, or port. If the fixed name
cannot be determined, the traditional names such as ethN will be used.

Example: en01, the first embedded network interface and enp2s0, a PI card network interface.

Network Display and Troubleshooting Commands:

ifconfig(interface Configurator) command is using to initialize and interface, assign IP Address


to interface and enable or disable interface on demand. With this command, you can view IP
Address and MAC address assign to interface. PING (Packet INternet Groper) command is the
best way to test connectivity between two nodes. Traceroute is a network troubleshooting utility
which shows number of hops taken to reach destination also determine packets travelling path.
Netstat (Network Statistic) command display connection info, routing table information etc.
Route command also shows and manipulate ip routing table. Host command to find name to IP
or IP to name in IPv4

or IPv6 and also query DNS records. Hostname is to identify in a network. Execute hostname
command to see the hostname of your box. The ss command is used to display Socket Statistics.
It is similar to the netstat command.

Display the ip address


[root@asim ~]# ifconfig
Display IP address for eth0 interface
[root@asim ~]# ifconfig ens33
Display IP address and netmask to all interfaces
[root@asim ~]#ip addr
Details information about interface
[root@asim ~]#ip addr show
Details information about eth0 interface
[root@asim ~]#ip addr show ens33
Display device attributes
[root@asim ~]#ip link show
Display statistics for all interface
[root@asim ~]#ip –s link show
Display statistics for eth0 interface
[root@asim ~]#ip –s link show ens33
Display the routing information
[root@asim ~]#ip route show
Display the routing information
[root@asim ~]#netstat -nr
Display the routing information
[root@asim ~]#netstat -r
Display the routing information
[root@asim ~]#route
Test connectivity
[root@asim ~]#ping
Test connectivity number of replay
[root@asim ~]#ping –c3
Gives routing info
[root@asim ~]#traceroute
Alternative to traceroute
[root@asim ~]#tracepath
Display listening TCP socket
[root@asim ~]#ss -lt

Network Manager:

This is collection of GUI (Graphical User Interface), TUI (Text User Interface), and CLI
(Command Line Interface) utilities that are used to configure your network settings. All these
utilities interact with the NetworkManager service: NetworkManager is a daemon that monitors
and manages network settings.

Configure Network with ifconfig:

ifconfig in short ‘Interface Configuration’ utility for in Linux operating system to configure,
manage and query network interface parameters via command line interface or in a system
configuration scripts. The ‘ifconfig’ command is used for displaying current network
configuration information, setting up an ip address, or netmsk to a network interface, setting up
hardware address and enable or disable network interfaces.

Display all the active interface Details


[root@asim ~]#ifconfig
Display all the active or inactive network details
[root@asim ~]#ifconfig -a
Display details of specific network interface
[root@asim ~]#ifconfig ens33
Activates a network interface
[root@asim ~]#ifconfig ens33 up
Deactivates the specified network Interface
[root@asim ~]#ifconfig ens33 down
Assign and IP address to a specific interface
[root@asim ~]#ifconfig ens33 192.168.1.1
Assign a Netmask to network interface
[root@asim ~]#ifconfig eth0 netmask 255.255.255.254
Assign a IP and Netmask to network interface
[root@asim ~]#ifconfig eth0 1.1.1.1 nestmask 255.0.0.0
Change MTU for a network interface
[root@asim ~]#ifconfig ens33 mtu 1000
Chang the MAC address of network interface
[root@asim ~]#ifconfig eth0 hw ether aa:bb:cc:dd:ee:ff

Configure Network With NMCLI:

NMCLI stands for (Network Manager Command Line Interface). NMCLI is a command-line
tool for controlling NetworkManager and getting its status. nmcli is used to create, display, edit,
delete, activate, and deactivate network connection, as well as control and display network
device status. nmcli add syntax: #nmcli connection add type Ethernet con-name
NAME_OF_CONNECTION ifname interface-name ip4 IP_ADDRESS gw4 GW_ADDRESS

Replacing the NAME_OF_CONNECTION with the name you wish to apply to new connection,
the IP_ADDRESS with the IP address you wish to use and the GW_ADDRESS with the
gateway address you use.

Display detailed info about device


[root@asim ~]#nmcli device show
Display list of network device
[root@asim ~]#nmcli device
Display list of network device state
[root@asim ~]#nmcli device status
Disconnect the interface
[root@asim ~]#nmcli dev dis ens33
Connect the interface
[root@asim ~]#nmcli dev con ens33
Adding an Ethernet connection with static IP
[root@asim ~]#nmcli con add type ethernet con-name eth1 ifname ens33 ip4 192.168.220.2
gw 192.168.220.1
Set the DNS servers for New connection
[root@asim ~]#nmcli con mod eth1 ipv4.dns 8.8.8.8 8.8.4.4
Add additional DNS value
[root@asim ~]#nmcli con mod eth1 +ipv.dns 4.4.4.4
Add additional IP address
[root@asim ~]#nmcli con mod eth1 +ipv4.addresses 192.168.220.10/24
Up the new Ethernet connection ens33
[root@asim ~]#nmcli con up eth1
Display detailed information of New connection
[root@asim ~]#nmcli –p con show eth1
Adding connection using DHCP, con-name
[root@asim ~]#nmcli con add type ethernet eth1_dhcp ifname eth1_dhcp ens33
Activate the connection
[root@asim ~]#nmcli con up eth1
Deactivate the connection
[root@asim ~]#nmcli con down eth1
Delete the connection
[root@asim ~]#nmcli con dell eth1
Display available connection
[root@asim ~]#nmcli con show
Display details of a specific Connection
[root@asim ~]#nmcli con show ens33
Display only active connection
[root@asim ~]#nmcli con show -a
Display help of NMCLI command
[root@asim ~]#nmcli help
Graphical tool for NMCLI
[root@asim ~]#nm-connection-editor
permanently assign hostname using hostnamectl command
[root@asim ~]#hostname set-hostname cms.panvel.com
Display hostname status
[root@asim ~]#hostname status
Display hostname
[root@asim ~]#cat /etc/hostname
Change hostname permanently
[root@asim ~]#vim /etc/hostname
Display hostname details
[root@asim ~]#cat /etc/hosts
Maps hostnames to IP addresses locally
[root@asim ~]#vim /etc/hosts

Configuring Name Resolution:

The /etc/resolv.conf file contains directives with the IP addresses of nameservers available to a
host. The /etc/hosts file keeps a local name database. This file helps in local name resolution if
yourlocal DNS server is not functioning. You can manually populate entries in this file.

Change DNS server


[root@asim ~]#cat /etc/resolv.conf
Change DNS server entries in interface configuration file
[root@asim ~]#vim /etc/syscongif/network-scripts/ifcfg-ens33 DNS1=8.8.8.8 DNS2=4.4.4.4
Configure DNS server entries using nmcli command
[root@asim ~]#nmcli con mod ens33 ipv4.dns 8.8.8.8
Map hostname to IP and IP to hostname
[root@asim ~]#vim /etc/hosts
Lookup IP address of hostname
[root@asim ~]#host www.eiheducation.com

Install and Update Linux Packages


July 5, 2019

Introduction:

Installing, updating and removing installed programs are key responsibilities in a system
administrator’s daily life. When a machine is connected to the internet, these task can be easily
performed using a package management system such as yum. However, when a machine does
not have access to the internet, another method is necessary. Local yum repository is the most
effective way to perform any type of package installation without any internet connection.
RPM:

RPM (Red Hat Package Manager) is a default open source and most popular management utility
for Red Hat based systems. The tool allows system administrators and users to install, update,
uninstall, query, verify and manage system software packages in Linux operating systems. The
RPM formerly known as (.rpm) file, that includes compiled software programs and libraries
needed by the packages. This utility only works with packages that built on (.rpm) format.

Go to Package directory
[root@asim ~]# cd /run/media/cms/CentOS\ 7\ x86_64/
Install package
[root@asim Packages]# rpm -ivh vsftpd-3.0.2-25.el7.x86_64.rpm
Upgrade and Install
[root@asim Packages]# rpm -U vsftpd-3.0.2-25.el7.x86_64.rpm
Upgrade package if already installed
[root@asim Packages]# rpm -F vsftpd-3.0.2-25.el7.x86_64.rpm
Show all queries
[root@asim Packages]# rpm -qa
Queries whether package is install or not
[root@asim Packages]# rpm -q vsftpd
Display information
[root@asim Packages]# rpm -qi vsftpd
Erase or uninstall
[root@asim Packages]# rpm -e vsftpd

YUM (Yellowdog update Modifier) Server:

YUM stands for Yellowdog Updater Modified. It is an interactive, rpm based package manager.
When installing RPM packages most of packages require dependencies but when installing any
package with the help of YUM package management tool it helps to install, remove or update the
package through the network or local, at the same time it provides an easy method to install a
package with its dependent packages.

List all enabled repositories


[root@asim ~]# yum repolist
List all packages that are installed
[root@asim ~]# yum list
List all available packages
[root@asim ~]# yum list all
Searches the package
[root@asim ~]# yum search httpd
Display information about a package
[root@asim ~]# yum info httpd
Installs the specified package
[root@asim ~]# yum install httpd
Checks whether updates exist for all pack
[root@asim ~]# yum check-update
Update all packages
[root@asim ~]# yum update
Remove the specified package
[root@asim ~]# yum remove httpd
Remove the specified package
[root@asim ~]# yum erase httpd
Remove all cached package download
[root@asim ~]# yum clean all
Displays help about yum usage
[root@asim ~]# yum help
Show you history of all install and remove packages
[root@asim ~]# yum history

Local YUM Repository:

To add a new or update an existing repository, go to the /etc/repos.d directory and create or open
a file that end with .repo. Repository sources can be created using the create repo package. The
main aim to create such an offline repository it works faster than online repository which can be
configured locally.

If you have to install software, security updates and fixes often in multiple systems in your local
network, then having a local repository is an efficient way. Because all required packages are
downloaded over the fast LAN connection from your local server, so that it will save your
internet bandwidth.

Local YUM with DVD configuration

Create directory for mounting Linux DVD


[root@asim ~]#mkdir /dev/cdrom/dev
Mount Linux DVD in dvd mounting directory
[root@asim ~]#mount /dev/cdrom/dvd
Move the existing repo files present in folder
[root@asim ~]#mv /etc/yum.repos.d/* .repo /
OR Remove the existing repo files
[root@asim ~]#rm –rf /etc/yum.repos.d/*
Create new repo file call local.repo
[root@asim ~]#vim /etc/yum.repos.d/local.repo
[LocalRepo] Name of the section
name=Local-Repository Name of the Repository
baseurl=file:///dvd location of the package
enabled=1 enable repository to work
gpgcheck=0 checking gpg signature set to no

Creating, Viewing and Editing Text File


June 28, 2019

vi text editor:

vi stand for Visual Interface is a text-editor in Linux. vi is display-oriented: the screen of


terminal acts as a window into the file your are editing. Changes you make to the file are
reflected in what you see. vi editor is a full screen editor and has three modes of operation:

Command Mode:

command which cause action to be taken on the file. This mode is used for the file navigation,
cut and paste, and simple commands such as undo and redo.

Insert Mode:

This mode is used for normal text editing means entered text is inserted into the file. Accessed by
typing the letter “i” or “I”, we simple enter text. Most keystrokes result in text appearing on the
screen. To get out of insert mode, hit the “esc” Escape key. Once you press “Esc” Escape key it
will turns off the insert mode.

Last-Line Mode:

This mode is used to save, quit and open files, as well as search & replace and other operaion.
Press “:” and vi will switch to Last-Line Mode. Enter a command like “:w” to write the file or
“:q” to exit the editor.

Starting vi:
You may use vi to open an already existing file by typing (#vi filename) where “filename” is the
name of the existing file. If the file is not in your current directory, you must use the full
pathname. Or you may create a new file by typing (#vi newname) where “newname” is the name
to give the new file. Once open new file on-screen, you will see blank lines, each with a tidle (~)
at the left, and a line at the bottom giving the name and status of the new file:

The Instructor will demonstrate a typical file editing session using only basic Vim keystrokes.

1. Open a file with vim filename


2. Repeat this text entry cycle as many times as the task require.

Press I to enter insert mode

Enter text

Press esc to return to command mode.

If necessary, press u to undo mistaken edits on the current line.

 Repeat this text deletion cycle, as many times as the task required:

Use arrow key to position the cursor

Press x to delete a selection of text

If necessary, use u to undo mistaken edits on the current line.

 To save or exit, choose one of the following to write or discard file edits:

Enter :w to save the file and remain in command mode for more editing.

Enter :wq to save the file and quim vim.

Enter :q! to quit vim, but discard all file changes since the last write.

Rearranging existing text

In vim, copy and paste is known as yank and put, using command characters y and p. Begin by
positioning the cursor on the first character to be selected, then enter visual mode. Use arrow
keys to expand the visual selection. When ready, press y to yank the selection into memory.
Position the cursor at the new location, then press p to put the selection at the cursor.

The instructor will demonstrate “yank and put” using visual mode.

1. Open file with Vim filename.


2. Repeat this text entry cycle as many times as the task require.
Use arrow key to position the cursor to the first character

Press v to enter visual mode.

Use arrow keys to position the cursor to the last character.

Press y to yank the selection

Use arrow key to position the cursor at the insert location

Press p to put the selection

 To save or exit, choose one of the following to write or discard file edits:

Enter :w to save the file and remain in command mode for more editing.

Enter :wq to save the file and quim vim.

Enter :q! to quit vim, but discard all file changes since the last write.

EXAMPLES:

Creating a vim file


[cms@asim ~]$ touch /home/cms/Desktop/f1
[cms@asim ~]$ touch /home/cms/Desktop/f1

[cms@asim Desktop]$ touch f2


[cms@asim Desktop]$ vim f2

Creating a new file with vim.


[cms@asim Desktop]$ vim f3

Constructing pipelines

Redirection controls channel output to or from files while piping sends channel output to another
process

Examples for processing piping redirection

Paginate a commands long output


[cms@asim ~]$ ls -l /usr/bin | less
total 146420
-rwxr-xr-x. 1 root root 41544 Oct 30 2018 [
-rwxr-xr-x. 1 root root 107904 Oct 30 2018 a2p
-rwxr-xr-x. 1 root root 52720 Apr 24 09:46 ab
-rwxr-xr-x. 1 root root 11336 Nov 13 2018 abrt-action-analyze-backtrace
-rwxr-xr-x. 1 root root 11320 Nov 13 2018 abrt-action-analyze-c
-rwxr-xr-x. 1 root root 1345 Nov 13 2018 abrt-action-analyze-ccpp-local
-rwxr-xr-x. 1 root root 6821 Nov 13 2018 abrt-action-analyze-core
-rwxr-xr-x. 1 root root 11304 Nov 13 2018 abrt-action-analyze-oops
-rwxr-xr-x. 1 root root 11312 Nov 13 2018 abrt-action-analyze-python
-rwxr-xr-x. 1 root root 2814 Nov 13 2018 abrt-action-analyze-vmcore
-rwxr-xr-x. 1 root root 1348 Nov 13 2018 abrt-action-analyze-vulnerability
-rwxr-xr-x. 1 root root 11360 Nov 13 2018 abrt-action-analyze-xorg
-rwxr-xr-x. 1 root root 5002 Nov 13 2018 abrt-action-check-oops-for-hw-error
-rwxr-xr-x. 1 root root 11344 Nov 13 2018 abrt-action-generate-backtrace
-rwxr-xr-x. 1 root root 11328 Nov 13 2018 abrt-action-generate-core-backtrace
-rwxr-xr-x. 1 root root 8341 Nov 13 2018 abrt-action-install-debuginfo
-rwxr-xr-x. 1 root root 3207 Nov 13 2018 abrt-action-list-dsos
-rwxr-xr-x. 1 root root 8958 Nov 13 2018 abrt-action-notify
-rwxr-xr-x. 1 root root 3535 Nov 13 2018 abrt-action-perform-ccpp-analysis
-rwxr-xr-x. 1 root root 1292 Nov 13 2018 abrt-action-save-kernel-data
-rwxr-xr-x. 1 root root 23800 Nov 13 2018 abrt-action-save-package-data
-rwxr-xr-x. 1 root root 15480 Nov 13 2018 abrt-action-trim-files
-rwxr-xr-x. 1 root root 48720 Nov 13 2018 abrt-applet
-rwxr-xr-x.

Count the number of lines in an output or listing.


[cms@asim ~]$ ls | wc -l > /home/cms/Desktop/f1

Grab the first line, last line, or selected lies of command output.
[cms@asim ~]$ ls -t | head -n 10 > /tmp/ten-last-changed-files

Determine the terminal device for the current window. Send the results as mail and view the
same results in this window.

[cms@asim ~]$ tty


/dev/pts/0

Accessing Linux File System


July 7, 2019
Introduction:

Hard disks and storage devices are normally divided up into smaller chunks called partitions. A
partition is a way to compartmentalize a disk. Different parts of it can be formatted with different
file systems or used for different purpose. For example, one partition could contain user home
directories while another could contain system data and logs. If a user fills up the home directory
partition with data, the system partition may still have space available. Placing data in two
separate file systems on two separate partitions helps in planning data storage.

Storage devices are represented by a special file type called block device. The block device is
stored in the /dev directory. In Red Hat Enterprise Linux, the first SCSI, PATA/SATA, or USB
hard drive detected is /dev/sda, the second is /dev/sdb, and so on. This name represents the whole
drive. The first primary partition on /dev/sda is /dev/sda1, the second partition is /dev/sda2 and
so on.

Display the file system and mount points


[root@asim ~]#df

Display file with human readable format


[root@asim ~]#df -h

Show a disk usage report for the /root directory


[root@asim ~]#du /root

Mounting and Unmounting file system manually

The mount command expects the file system argument in one of two different ways:

The device file of the partition holding the file system, residing in /dev

The UUID, a universal unique identifier of the file system.

Check UUID and other details of devices


[root@asim ~]#blkid

Mount by device file of the partition that holds the file system
[root@asim ~]#mount /dev/vdb1 /mnt/xyz

Mount file system by UUID,


[root@asim ~]#mount UUID=”12xz97 1265qd 49624s 78qsz6” /mnt/xyz

Unmounting the device


[root@asim ~]#umount /mnt/xyz
List all open files and the process
[root@asim ~]#lsof /mnt/xyz

Accessing removable storage device

Removable media, such as USB flash device and drives, get automatically mounted by the
graphical desktop environment when plugged in. The mount point for the removable medium is
/run/media/<user>/<label>.

The <user> is the user logged into the graphical environment.

The <label> is the name given to the file system when it was created.

Steps to mount and unmount a removable pen drive

[root@asim ~]#blkid
[root@asim ~]#mkdir /mnt/xyz
Or
[root@asim ~]#mount UUID=”12xz97 1265qd 49624s 78qsz6” /mnt/xyz
[root@asim ~]#cp f1.txt /mnt/xyz
[root@asim ~]#umount /mnt/xyz

Managing links between files

Creating a hard links:

A hard link is a new directory entry with a reference to an existing file on the file system. Every
file in a file system has one hard link by default. To save space, instead of copying, a new hard
link can be created to reference the same file. A new hard link either needs to have a different
file name, if it is created in the same directory as the existing hard link, or it needs to reside in a
different directory. All hard links pointing to the same file have the same permissions, link count,
user/group ownership, time stamps, and file content. Hard link pointing to the same file content
need to be on the same file system.

[root@asim ~]#mkdir –p today/1/2/3/4/5/6


[root@asim ~]#cat>today/1/2/3/4/5/6/original
Contents
[root@asim ~]#tree today/
[root@asim ~]#ln today/1/2/3/4/5/6/original linkname
[root@asim ~]#ls –l (shows linkname entry)
[root@asim ~]#cat linkname
[root@asim ~]#rm today/1/2/3/4/5/6/original
[root@asim ~]#cat linkname (still display the same content because hard link is not deleted
[root@asim ~]#ln –s /dev /root/devicefiles
[root@asim ~]#ls
[root@asim ~]#cd /devicefiles
[root@asim ~]#ls (show all the content of /dev)

Tools for finding files (Locate and Find)

A system administrator needs tools for searching files matching certain criteria on the file
system. This section discusses two commands that can search files in the file system. The locate
command searches a pre generated database for file names or file paths and returns the results
instantly. The find command searches the file system in real time by crawling through the file
system.

When searching entries as a regular user, results are returned only for where the user invoking
the locate search has read permissions on the directory trees readable by user student on
machine.

[root@asim ~]#locate passwd

[root@asim ~]#locate image

[root@asim ~]#locate –l message

[root@asim ~]#locate –n 5 image.png

[root@asim ~]#find / -name sshd_config

[root@asim ~]#find / -name ‘*.txt’

[root@asim ~]#find /etc –name ‘*pass*’

[root@asim ~]#find / – iname ‘*messages*’

[root@asim ~]#find –user student

[root@asim ~]#find -group student

[root@asim ~]#find –uid 1000

[root@asim ~]#find –gid 1000

[root@asim ~]#find /home – perm 764

[root@asim ~]#find –size 10M


[root@asim ~]#find – size +10G

[root@asim ~]#find – size -10K

Kickstart
July 14, 2019

Introduction:

To automate the installation of Red Hat Enterprise Linux a feature called Kicstart. A single file
containing the answers to all the questions that would normally be asked during a typical
installation. Kickstart installation can be performed using a local CD-ROM, a local hard drive, or
via NFS, FTP, or HTTP. Kickstart perform Automatic installations of RHEL/CentOS7, without
the need for user intervention, the machines using a kickstart file read from a local FTP server.
Kickstart in Red Hat Enterprise Linux is similar to unattended installation for Microsoft
Windows. The default configuration file for kickstart “anaconda-ks.cfg” is available in the home
directory of the root user. In kickstart configuration file lines start with # characters are
comments that are ignored by the installer. Line that starts with a % character and end with the
%end is directive. The %packages section specifies the software to be installed on the target
system. %post, Configure the system after all the software has been installed. The %pre, script is
executed before any disk partitioning is done.

Install GUI package of kickstart


[root@asim ~]#yum install –y system-config-kickstart

Install FTP for network access


[root@asim ~]#yum install –y vsftpd

Start FTP service


[root@asim ~]#systemctl start vsftpd

Start FTP service on boot


[root@asim ~]#systemctl enable vsftpd

Mount CentOS DVD to FTP folder


[root@asim ~]#mount /dev/cdrom /var/ftp/pub/

Temporary disable SELinux Security


[root@asim ~]#setenforce 0
Stop Firewall temporary or Add the firewall for FTP
[root@asim ~]#systemctl stop firewalld or [root@asim ~]#firewall-cmd – -permanent – -add-
service=ftp

After add role reload the firewall


[root@asim ~]#firewall-cmd – -reload

Open kickstart from command line Or Open kickstart from graphically


[root@asim ~]#systemctl system-config-kickstart or Application > System Tools > Kickstart

1) Basic configuration

Select Default Language = English USA

keyboard = U.S English

Time zone = Asia/Kolkata

Set root password = 123456

Confirm root password = 123456

Check the check box of “Reboot system after installation”

2) Installation Method

Click the radio button of “Perform new installation”

In installation device select FTP

In FTP server: Type your system IP “192.168.220.138”

In FTP directory: type “pub”

3) Boot loader option

Click on Install new boot loader

In Installation options, choose “Install boot loader on MBR”

4) Partition Information

In Master Boot Record option click on “clear Master Boot Record”

In Partition option click on “Remove all existing partitions”


In disk label click on “Initialize the disk label”

Click on Add

Mount point “/”

File system “xfs”

File size(MB) “20480”

Ok

Click on Add

Mount point “/boot”

File system “xfs”

File size(MB) “2048”

Ok

Click on Add

File system “swap”

File size(MB) “1024”

Ok

5) Network Configuration

Network device :eth0

Network type :DHCP

ok

6) Authentication

Leave as it is

7) Firewall configuration

Disable SELinux
8) Display configuration

Leave as it is

9) Package Selection

Do this later

10) Pre installation and post installation script

Write script or leave this step

Go to file and save with name “ks.cfg” in “/var/ftp” directory

[root@asim ~]#cd ~

[root@asim ~]#ls

[root@asim ~]#gedit anaconda-ks.cfg

Copy packages

[root@asim ~]#gedit /var/ftp/ks.cfg

Paste packages at the end of the file

Save and close

Copy the save kickstart file syntax


[root@asim ~]#cp ks.cfg /var/ftp/

Set permission on kickstart file


[root@asim ~]#chmod 755 /var/ftp/ks.cfg

Check for kickstart file syntax


[root@asim ~]#ksvalidator /var/ftp/ks.cfg

Setup New Virtual Machine and follow the steps below:

Press Tab on Client and type FTP location


ks=ftp://192.168.220.138/pub/ks.cfg

Press Tab on Client and type FTP location ks=ftp://192.168.220.138/ks.cfg with ip=192.168.220.140
netmask=255.255.255.0-static IP and gateway configuration
Creating and Editing Text File with Vim
July 14, 2019

Introduction:

Vim stands for Visual Interface IMprove is an improved version of VI (Visual interface), a
famous text-editor in Linux. VIM is display-oriented: the screen of terminal acts as a window
into the file you are editing. Changes you make to the file are reflected in what you see. Vim is
backward-compatible with vi. Vim editor provides syntax highlighting, completion modes, spell-
checking, scripting in multiple languages, file-type plug-ins, and many other options. VIM editor
is a full screen editor and has three modes of operations”

Command Mode:

Command which cause action to be taken on the file. This mode is used for the file navigation,
cut and paste, and simple commands such as undo and redo.

Insert Mode:

This mode is used for normal text editing means entered text is inserted into the file. Accessed by
typing the letter “i” or “I”, we simple enter text. Most keystrokes result in text appearing on the
screen. To get out of insert mode, hit the “esc” Escape key. Once you press “Esc” Escape key it
will turns off the insert mode.

Last-Line Mode:

This mode is used to save, quit and open files, as well as search & replace and other operation.
Press “:” and vi will switch to Last-Line Mode. Enter a command like “:w” to write the file or
“:q” to exit the editor.

h or left Arrow Go one character to the left

j or Down Arrow Go down one line

12j Move the cursor 12 lines down

k or Up Arrow Go up one line


l or Right Arrow Go one character to the right

$ Go to the end of the current line

G Move to the last line of the document

gg Move to the first line of the document

W Forward one word

5w Forward five words

B Backward one word

( Move cursor to beginning of current or previous sentence

) Move cursor to beginning of next sentence

{ Move to beginning of current/previous paragraph

} Move cursor to beginning of next paragraph

H Go to the top of the screen

L Go to the bottom of the screen

0 (Zero) Go to the beginning of the current line

Ctrl – B Go back one screen

Ctrl – F Go forward one screen

R Replace the character as the current cursor position

R Overwrite at the current cursor position

X Delete the character at the current cursor position

x Delete the character immediately before (to the left)

Dd Cut the entire line

D Cut from the current cursor position to the end of the line

YY or Y Yank (copy) the entire current line

P Paste

.(period) Repeat the last command


u Undo the last command

U Undo the last command in the last line.

n Fine the next match in a search

N Fine the previous match in a search

cw Change current word to a new word

:/ To search forward

:? To search backward

:set number Enables line numbers

:set nu Enables line numbers

:set nonu Turn line numbers off

:set nonumber Turn line numbers off

Managing Priority of Linux Process


July 14, 2019

Introduction:

By default, Linux kernel considers all processes equally important and allocates the same amount
of CPU time for each process. Sometimes, you might want to increase or decrease the priority of
certain processes to utilize more CPU time.

Process Definition:

A process is a running program. So, any running program or a command given to a Linux system
is called a process. Linux can run a lot of processes at a time, which can slow down the speed of
some high priority processes result in poor performance. The default value of all the processes is
0.

Nice and Renice Command:

Sometimes, we might want to increase or decrease the priority of certain processes to utilize
more CPU time. This is where the nice and renice commands comes in help. Nice command is
used for run a process with a user defined priority whereas renice command changing the priority
of an already running process. With the help of nice command in Linux you can set process
priority. If you give a process a higher priority, then kernel will allocate more CPU time to that
process. Nice command will launch a process with a user defined scheduling priority.

Whenever a process start normally, it gets the default nice value (0). If you start a process with
nice command without any arguments, it gets the default value of 10. Here 10 is the niceness
value of priority. Niceness values range from -20 to 19. The negative values such as -20 gives
higher priority to a process and positive values such as 19 gives lower priority.

Regular users are not allowed to start a process with higher priority. You need to be root user to
launch any process with higher priority.

Display process nice values


[root@asim ~]#ps –l

Display customize process


[root@asim ~]#ps axo user, pid, nice, command

Display customize process sorted by nice


[root@asim ~]#ps axo user, pid, command, nice – – sort=nice

Start process with nice default value is 10


[root@asim ~]#nice vim text &

Start the process with 15 nice value


[root@asim ~]#nice – 15 vim text &

Change nice value of running process to 19


[root@asim ~]#renice 19 9182 Or [root@asim ~]#renice 19 –p 9182

Run Top press r to renice a process


[root@asim ~]#top

Another way to change nice value


[root@asim ~]#nice – – 15 vim &

Change priority for all running process of user


[root@asim ~]#renice –n -20 –u champ

Managing SELinux Security


July 19, 2019
Introduction:

Security Enhanced Linux (SELinux) is an additional layer of system security. A primary goal of
SELinux is to protect user data from system services that have been compromised. Most Linux
administrator are familar with the standard user/group/other permission security model. This is a
user and group-based model known as discretionary access control. SELinux provides an
additional layer of security that is object-based and controlled by more sophisticated rules,
known as mandatory access control.

SELinux is a set of security rules that determine which process can access which files,
directories, and ports. Every file, process, directory and port has a special security label called a
SELinux context. A context is a name that is used by the SELinux policy to determine whether a
process can access a file, directory, or port. By default, the policy does not allow any interaction
unless an explicit rule grants access. If there is no allow rule, no access is allowed.

Many commands that deal with files have an option (usually -z) to display or set SELinux
context. For instance, ps, ls, cp, and mkdir all use the -z option to display or set SELinux context.

SELinux modes:

For troubleshooting purpose, SELinux protection can be temporarily disabled using SELinux
modes. There are three modes in SELinux.

1) Enforcing mode: In enforcing mode, SELinux actively denies access to the web server
attempting to read files with tmp_t type context. In enforcing mode, SELinux both logs and
protects.

2) Permissive mode: Permissive mode is often used to troubleshoot issue. In permissive mode,
SELinux allows all interactions, even if no explicit rule, and it logs those interactions it would
have denied in enforcing mode. This mode can be used to temporarily allow access to content
that SELinux is restricting. No reboot is required to go from enforcing to permissive or back
again.

3) Disabled: This mode completely disables SELinux. A system reboot is required to disable
SELinux entirely or to get from disabled mode to enforcing or permissive mode.

SELinux Booleans:

SELinux Booleans are switches that change the behavior of the SELinux policy. SELinux
Booleans are rules that can be enabled or disabled. They can be used by security administrators
to tune the policy to make selective adjustments.

The getsebool command is used to display SELinux Booleans and theri current value. The -a
option causes thi command to list all of the booleans.

[root@asim ~]#getsebool -a
Display the current SELinux mode
[root@asim ~]#getenforce

change the default SELinux mode to permissive and reboot.


[root@asim ~]#vim /etc/selinux/config
[root@asim ~]#grep ‘^SELINUX’ /etc/selinux/config
SELINUX=permissive
SELINUX=targeted
[root@asim ~]#reboot

set the current SELinux mode to enforcing


[root@asim ~]#setenforce 1 [root@asim ~]#getenforce

Display the SELinux Booleans


[root@asim ~]#getsebool –a
[root@asim ~]#getsebool httpd_enable_homedirs

Set the SELinux Booleans


[root@asim ~]#setsebool httpd_enable_homedirs on

[root@asim ~]#semanage boolean -l | grep httpd_enable_homedirs

[root@asim ~]#getsebool httpd_enable_homedirs

[root@asim ~]#setsebool -p httpd_enable_homedirs on

[root@asim ~]#semanage boolean -l | grep httpd_enable_homedirs

To list local modification of SELinux Booleans


[root@asim ~]#semanage boolean -l -c

Adding Disks, Partitions and File Systems to


a Linux System
July 20, 2019

Introduction:
Disk partitioning allows a hard drive to be divided into multiple logical storage units referred to
as portions. By separating a disk into partitions, system administrators can use different
partitions to perform different functions.

MBR partitioning scheme:

MBR is a scheme which supports a maximum of four primary partition. On Linux systems, with
the use of extended and logical partitions, administrator can create a maximum of 15 partitions.
Since partition size data are stored as 32-bit values, disk partitioned with the MBR scheme have
a maximum disk and partition size limit of 2 TiB.

GPT partitioning scheme:

For systems running UEFI (Unified Extensible Firmware Interface) firmware, GPT is the
standard for laying out partition table on physical hard disk. GPT is part of the UEFI standard
and addresses many of the limitation imposed by the old MBR-based scheme. Per UEFI
specification, GPT default to supporting up to size 128 partitions. Unlike MBR which use 32 bits
address. This allows GPT to accommodate partitions and disks of up to 8 zebibyte(ZiB) or 8
billions tebibytes.

Creating disk partition

Step 1 – Create Disk Partitions


fdisk /dev/sdc

Command (m for help): n


Command action
e extended
p primary partition (1-4)
Partition number (1-4): 1
First sector (63-104857599, default 63): 2048
Last sector, +sectors or +size{K,M,G} (2048-104857599, default 104857599): +10G
Save new partitioning table using w command.
Command (m for help): w

Step 2 – Format Disk Partitions


mkfs -t ext4 /dev/sdc1

We can use any other file system type like: ext2, ext3, ext4, fat, vfat, ntfs etc.

mkfs.ext4 /dev/sdc1

3. Mount/Unmount Partitions
Before mounting a disk, you are required to create a mount point. Then use the mount command to
mound disk partition on a mount point. mkdir /newDisk1
mount /dev/sdc1 /newDisk1

Now use one of following command to verify disk is mounted successfully.


mount | grep “/dev/sdc1”
df -h | grep “/dev/sdc1”

4. Mount Disk on Startup

Use /etc/fstab file which is used for mounting disk partitions during system boot up. Add the following
entry in /etc/fstab file at the end of file.
/dev/sdc1 /newDisk1 ext3 defaults 0 2

1.To verify that the Linux kernel can see the partition, you can cat out /proc/partitions like this:

cat /proc/partitions

2.Decide what kind of filesystem you want to create, such as ext4, XFS, or anything else. Here
are a few options:

mkfs.btrfs mkfs.cramfs mkfs.ext2 mkfs.ext3 mkfs.ext4 mkfs.minix mkfs.xfs

3.For the purposes of this exercise, choose ext4. (I like ext4 because it allows you to shrink the
filesystem if you need to, a thing that isn’t as straightforward with XFS.) Here’s how it can be
done (the output may differ based on device name/sizes):

[root@asim ~]# mkfs.ext4 /dev/sda1


mke2fs 1.42.9 (28-Dec-2013)
Filesystem label= OS type: Linux
Block size=4096 (log=2)
Fragment size=4096 (log=2)
Stride=0 blocks, Stripe width=8191 blocks
194688 inodes, 778241 blocks
38912 blocks (5.00%) reserved for the super user
First data block=0
Maximum filesystem blocks=799014912
24 block groups
32768 blocks per group, 32768 fragments per group
8112 inodes per group
Superblock backups stored on blocks:
32768, 98304, 163840, 229376, 294912
Allocating group tables: done
Writing inode tables: done
Creating journal (16384 blocks): done
Writing superblocks and filesystem accounting information: done

Mouting a file system

1.First, identify the UUID of your new filesystem. Issue the blkid command to list all known
block storage devices and look for sda1 in the output:

[root@ asim ~]# blkid


/dev/vda1: UUID=”716e713d-4e91-4186-81fd-c6cfa1b0974d” TYPE=”xfs”
/dev/sr1: UUID=”2019-03-08-16-17-02-00″ LABEL=”config-2″ TYPE=”iso9660″
/dev/sda1: UUID=”wow9N8-dX2d-ETN4-zK09-Gr1k-qCVF-eCerbF”
TYPE=”LVM2_member”
/dev/mapper/test-test1: PTTYPE=”dos”
/dev/sda1: UUID=”ac96b366-0cdd-4e4c-9493-bb93531be644″ TYPE=”ext4″

2.Run the following command to mount the /dev/sd1 device :

[root@ asim ~]# mkdir /mnt/mount_point_for_dev_sda1


[root@ asim ~]# ls /mnt/
mount_point_for_dev_sda1

[root@ asim ~]# mount -t ext4 /dev/sda1 /mnt/mount_point_for_dev_sda1/

[root@ asim ~]# df -h

Filesystem Size Used Avail Use% Mounted on


/dev/vda1 7.9G 920M 7.0G 12% /
devtmpfs 443M 0 443M 0% /dev
tmpfs 463M 0 463M 0% /dev/shm
tmpfs 463M 30M 434M 7% /run
tmpfs 463M 0 463M 0% /sys/fs/cgroup
tmpfs 93M 0 93M 0% /run/user/0
/dev/sda1 2.9G 9.0M 2.7G 1% /mnt/mount_point_for_dev_sda1

Note:The df -h command shows which filesystem is mounted on which mount point. Look for
/dev/sd1. The mount command above used the device name /dev/sda1. Substitute it with the
UUID identified in the blkid command. Also, note that a new directory was created to mount
/dev/sda1 under /mnt.
3.A problem with using the mount command directly on the command line (as in the previous
step) is that the mount won’t persist across reboots. To mount the filesystem persistently, edit the
/etc/fstab file to include your mount information:

UUID=ac96b366-0cdd-4e4c-9493-bb93531be644
/mnt/mount_point_for_dev_sda1/ ext4 defaults 0 0

4.After you edit /etc/fstab, you can umount /mnt/mount_point_for_dev_sda1 and run the
command mount -a to mount everything listed in /etc/fstab. If everything went right, you can still
list df -h and see your filesystem mounted:

root@ asim ~]# umount /mnt/mount_point_for_dev_sda1/


[root@ asim ~]# mount -a
[root@ asim ~]# df -h
Filesystem Size Used Avail Use% Mounted on
/dev/vda1 7.9G 920M 7.0G 12% /
devtmpfs 443M 0 443M 0% /dev
tmpfs 463M 0 463M 0% /dev/shm
tmpfs 463M 30M 434M 7% /run
tmpfs 463M 0 463M 0% /sys/fs/cgroup
tmpfs 93M 0 93M 0% /run/user/0
/dev/sda1 2.9G 9.0M 2.7G 1% /mnt/mount_point_for_dev_sda1

5.You can also check whether the filesystem was mounted:

[root@asim ~]# mount | grep ^/dev/sd


/dev/sda1 on /mnt/mount_point_for_dev_sda1 type ext4
(rw,relatime,seclabel,stripe=8191,data=ordered)

Accessing Network Storage with Network


File System (NFS)
July 21, 2019

Introduction:
NFS, the Network File System, is an internet standard protocol used by Linux, UNIX and similar
operating system as their native netwok file system. It is an open standard under active extension
which supports native Linux permissions and file system features.

Red Hat Enterprise Linux 7 supports NFSv4 (Version 4 of the protocol) by default, and falls
back automatically to NFSv3 and NFSv2 if that is not available. NFSv4 uses the TCP protocol to
communicate with the server, while older version of NFS may use either TCP or UDP.

NFS servers, exports share (directories) and NFS clients mount an exported share to local mount
point (directory). The local mount point must exist. NFS shares can be mounted a number of
ways:

manually mounting an NFS share using the mount command.

automatically mounting an NFS share at boot time using /etc/fstab.

Mounting an NFS share on demand through a process known as automounting.

Table of Contents

 Configuring NFS Server


 Configuration NFS client
 Test the Working of NFS Setup

Configuring NFS Server


Install the required packages
[root@nfsserver ~]# yum install nfs-utils*

Make directory which you want to share


[root@nfsserver ~]# mkdir /public
[root@nfsserver ~]# mkdir /private

Give Full Permission to both Shared directories


[root@nfsserver ~]# chmod 777 /public
[root@nfsserver ~]# chmod 777 /private

Now we need to make an entry in “/etc/exports” and restart the services to make our directory
shareable in the network.
[root@nfsserver ~]# vi /etc/exports
/public (client IP)192.168.0.2(ro,sync)
/private (client IP)192.168.0.2(rw,sync)

Check files are export to client machine or not.


[root@nfsserver ~]# exportfs -arvh
Note: NFS Options

Some other options we can use in “/etc/exports” file for file sharing is as follows.

ro: With the help of this option we can provide read only access to the shared files i.e client will
only be able to read.

rw: This option allows the client server to both read and write access within the shared directory.

sync: Sync confirms requests to the shared directory only once the changes have been
committed.

no_subtree_check: This option prevents the subtree checking. When a shared directory is the
subdirectory of a larger file system, nfs performs scans of every directory above it, in order to
verify its permissions and details. Disabling the subtree check may increase the reliability of
NFS, but reduce security.

no_root_squash: This phrase allows root to connect to the designated directory.

For more options with “/etc/exports“, you are recommended to read the man pages for export.

Add services in firewall


[root@nfsclient ~]# firewall-cmd –permanent –add-service=nfs
[root@nfsclient ~]# firewall-cmd –permanent –add-service= bind
[root@nfsclient ~]# firewall-cmd –permanent –add-service= mountd
[root@nfsclient ~]# firewall-cmd –reload

Configuration NFS client


[root@nfsclient ~]# yum install autofs -y

Add new file in auto.master


[root@nfsclient ~]# vim /etc/auto.master
Add after “/etc/auto.misc”
/mnt /etc/auto.txt
:wq

Create our auto.txt file


[root@nfsclient ~]# vim /etc/auto.txt
public -ro,sync, (server IP) 192.168.0.1:/public
private -rw,sync, (server IP) 192.168.0.1:/private
:wq

Start and enable autofs service


[root@nfsclient ~]# systemctl start autofs
[root@nfsclient ~]# systemctl enable autofs
[root@nfsclient ~]# systemctl status autofs

[root@nfsclient ~]# mount -a


[root@nfsclient ~]# mount
[root@nfsclient ~]# mount | grep mount

Test the Working of NFS Setup


[root@nfsclient]# cd /mnt
[root@nfsclient]# ls
[root@nfsclient]# cd /public
[root@nfsclient]# touch abc
[root@nfsclient]# cd..
[root@nfsclient]# cd /private
[root@nfsclient]# touch abc
[root@nfsclient]# vim abc
This is our NFS Server.
:wq

Server end
[root@nfsserver]# cd /public
[root@nfsserver]# vim xyz
This is our NFS Client
:wq
[root@nfsserver]# cd ..
[root@nfsserver]# cd /private
[root@nfsserver]# vim xyz2
[root@nfsserver]# ls

Client end
[root@nfsserver]# c /mnt
[root@nfsserver]# ls
[root@nfsserver]# cd /private
[root@nfsserver]# ls

Removing the NFS Mount

If you want to unmount that shared directory from your server after you are done with the file sharing,
you can simply unmount that particular directory with “umount” command. See this example below.
root@nfsclient ~]# umount /mnt/public
root@nfsclient ~]# umount /mnt/private
You can see that the mounts were removed by then looking at the filesystem again.
[root@nfsclient ~]# df -h -F nfs

Controlling and Troubleshooting the Linux


Boot Process
July 21, 2019

Introduction:

Modern computer systems are complex combination of hardware and software. Starting from an
undefined, powered-down state to a running system with a (graphical) login prompt requires a
large number of pieces of hardware and software to work together. The following list gives a
high-level overview of the tasks involved for a physical x86_64 system booting Red Hat
Enterprise Linux 7. The list for x86_64 virtual machines is roughly the same, but some of the
hardware-specific steps are handled in software by the hypervisor.

1. The machine is powered on. The system firmware (either modern UEFI or more old-fashioned
BIOS) runs a Power On Self Test (POST), and starts to initialize some of the hardware.

Configured using: The system BIOS/UEFI configuration screens, typically reached by pressing
a certain key combination e.g. F2- early during the boot process.

2.The system firmware searches for a bootable device, either configured in UEFI boot firmware
or by searching for a Master Boot Record (MBR) on all disks, in the order configured in the
BIOS.

Configured using: The system BIOS/UEFI configuration screens, typically reached by pressing
a certain key combination e.g. F2- early during the boot process.

3. The system firmware reads a boot loader from disk, then passes control of the system to the
boot loader. On a Red Hat Enterprise Linux 7 system, this will typically be grub2.

Configured using: grub2-install

4. The boot loader loads its configuration from disk, and presents the user with a menu of
possible configuration to boot.

Configured using: /etc/grub.d/ , /etc/default/grub, and (not manually) /boot/grub2/grub.cfg.


5. After the user has made a choice (or an automatic timeout has happened), the boot loader
loads the configured kernel and initramfs from disk and place them in memory. An initramfs is a
gzip-ed cpio archive containing kernel modules for all hardware necessary at boot, init scripts,
and more. On Red Hat Enterprise Linux 7, the initramfs contain an entire usable system by itself.

Configured using: /etc/dracut.conf

6. The boot loader hands control of the system over to the kernel, passing in any options
specified on the kernel command line in the boot loader, and the location of the initramfs in
memory.

Configured using: /etc/grub.d/ , /etc/default/grub, and (not manually) /boot/grub2/grub.cfg

7. The kernel initializes all hardware for which it can find a driver in the initramfs, the executes
/sbin/init (from the initramfs as PID 1. On Red Hat Enterprise Linux 7, the initramfs contains a
working copy of systemd as /sbin/init, as well as a udev daemon.

Configured using: init = command-line parameter.

8. The systemd instance from the initramfs executes all units for the initrd.target target. This
includes mounting the actual root the system on /sysroot.

Configured using: /etc/fstab

9. The kernel root file system is switched (pivoted) from the initramfs root file system to the
system root file system that was previously mounted on /sysroot. systemd then re-executes itself
using the copy of systemd installed on the system.

10. systemd looks for a default target, either passed in from the kernel command line or
configured on the system, the starts (and stops) units to comply with the configuration for that
target, solving dependencies between units automatically. In its essence, a systemd target is a set
of units that should be activated to reach a desired system state. These targets will typically
include at least a text-based login or a graphical login screen begin spawned.

Configured using: /etc/systemd/system/default.target, /etc/systemd/system/

Recovering the root password

1. Reboot the system

2. Interrupt the boot loader countdown by pressing any key.

3. Move the cursor to the entry that needs to be booted.

4. Press e to edit the selected entry.


5. Move the cursor to the kernel command line (the line that starts with linux16).

6. Append rd.break (this will break just before control is handed from the initramfs to the actual
system).

7. Press Ctrl + x to boot with the changes.

At this point, a root shell will be presented, with the root file system for the actual system
mounted read-only on /sysroot.

1. Remount /sysroot as read-write.

switch_root:/# mount -o remount, rw /sysroot

2. Switch into a chroot jail, where /sysroot is treated as the root of the file system tree.

switch_root:/# chroot /sysroot

3. Set a new root password

sh-4.2# passwd root

4. Make sure that all unlabeled files (including /etc/shadow at this point) get relabeled during
boot.

sh-42.# touch /.autorelabel

5. Type exit twice. The first will exit the chroot jail, and the second will exit the initramfs debug
shell.

Manage Files From Command Line


July 14, 2019

Introduction:

Regular expressions are used to search and manipulate the text, based on the patterns. Grep
command is used to search for a specific string in a file. Also use regular expressions with grep
command when you want to search for a text containing a particular pattern.

Regular Expressions:
Regular Expressions are special characters which help search data, matching complex patterns. A
regular expression, often shortened to “regex” or “regexp”. Regular Expression enhance the
ability to meaningfully process text content, especially when combined with other commands.

Patterns that exactly specify the characters to be matched are called “literals” because they match
the pattern literally, character-for-character.

The period character and the special meta-character (.) is used in regular expressions to mean
that any single character can exist at the specified location.

Anchors are special characters that specify where in the line a match must occur to be valid.

Use the “^” anchor before the literal string. Similarly, the “$” anchor can be used after a string to
indicate that the match will only be valid if it occurs at the every end of a line.

One of the most commonly used meta-characters is the “*”, which means “repeat the previous
character or expression zero or more times”.

We can escape characters by using the backlash character (\) before the character that would
normally have a special meaning.

One of the easiest and most useful abilities that extended regular expressions open up is the
ability to group expressions together to manipulate. Group expressions together using
parentheses.

A bracket expression is a list of characters enclosed by

. It matches any single character in that list

. Match a single character of any value

^ Anchor symbol to match a starting at the beginning of line

$ Dollar symbol to match end of the line

* Matches up zero or more times the preceding character

\ Represent special characters

() Groups regular expressions

? Matches up exactly one character

[] Range of character

^$ Count of empty lines


Grep command:

The grep command which stands for “Graphical Regular Expression Print,” The grep command
is used to search text or searches the given file for lines containing a match to the given string or
words. Use grep to search for lines of text that match one or many regular expressions, and
outputs only the matching lines. Grep is a powerful file pattern searcher in Linux.

Install grep package


[root@localhost ~]#yum install grep

Search the given string in specified file


[root@localhost ~]#grep “linux” file

Case insensitive search


[root@localhost ~]#grep –I “linux” file

Display don’t contain a specified string


[root@localhost ~]#grep –v linux file

Regular expression anything


[root@localhost ~]#grep “fast.*host” file

Display the line numbers contains matches


[root@localhost ~]#grep –n “word” file

Highlighting matched search


[root@localhost ~]#grep –color “linux” file

Display lines starts with root word


[root@localhost ~]#grep ^root /etc/passwd

Display line ends with bash word


[root@localhost ~]#grep bash$ /etc/passwd

Search pattern recursively


[root@localhost ~]#grep –r linux /etc

Counting the lines when word match


[root@localhost ~]#grep –c ‘test’ file

Counting any single character between c and t


[root@localhost ~]#grep c.t /usr/share/dict/words

Display 2 lines after the regex match


[root@localhost ~]#grep –A 2 ‘test’ file
Display 2 lines before the regex match
[root@localhost ~]#grep –B 2 ‘test’ file

Display 2 lines before and after the regex match


[root@localhost ~]#grep –c 2 ‘test’ file

Contains any one character found in bracket


[root@localhost ~]# grep c[aou]t /usr/share/dict/words

Contains either string in the file


[root@localhost ~]# grep -e cat -e tele /usr/share/dict/words

Find every line that begins with a capital letter


[root@localhost ~]#grep “^[A-Z]” file

Schedule Linux Feature Task


July 14, 2019

Introduction:

Schedule tasks to automatically execute in the future. there are two basic daemons for scheduling
tasks on a Linux System “at” command which is very useful for scheduling one time tasks and
“crontab” are the routing tasks.

AT command:

The at command schedules a command to be run once at a particular time. It reads commands
from standard input or script or file which can be executed later once. The at command can’t be
used for any recurring tasks. For recurring tasks Linux crontab is used. For normal users,
permission to use at command is determined by the files /etc/at.allow and /etc/at.deny . If the file
/etc/at.allow exists, only usernames mentioned in tit are allowed to use at. If /etc/at.allow does
not exist, /etc/at.deny is checked, every user name not mentioned in it is then allowed to user at.
If neither exists, only the superuser is allowed use of at command.

Run AT command:

To start at command run at the command line, passing it the scheduled time as an option. It will
place you at a special prompt, type the command or series of commands to be run at the
scheduled time. When done, press control-D on a new line, and the command will be placed in
the queue.
Install at package
[root@asim ~]#yum install at

Start at command service


[root@asim ~]#systemctl starat atd

Enable at package service on boot


[root@asim ~]#systemctl enable atd

At command passing scheduled time Passing touch command to create file Passing another command
to save in file Press ctrl + D to terminate at command
[root@asim ~]#at 5:20pm May 5
At>touch f1
At>date > f1
At>Ctrl +D

Just after 3 minutes


[root@asim ~]#at now + 3 minutes

Just after 1 hour


[root@asim ~]#at now + 1 hour

Just after 1 week


[root@asim ~]#at now + 1 week

just after 2 weeks


[root@asim ~]#at now + 2 week

View currently-queued at jobs


[root@asim ~]#atq

List each of the scheduled jobs


[root@asim ~]#at -l

List job contents


[root@asim ~]#at =c 1

Remove the at job number 1


[root@asim ~]#atrm 1 or at –r1

Crontab command:

Linux crontab is similar to windows task schedules. Crontab are very useful for routin tasks like
scheduling system scanning, daily backup etc. Crontab executes jobs automatically in backend
on specified time interval. For scheduling one time tasks you can use at command in Linux. Cron
is a scheduler that can run commands at regular intervals. It’s often referred to as crontab which
is name of its configuration file and the tool used to edit the configuration file. Crontab file
consists of command per line and have six fields actually and separated either of space or tab.
The beginning five fiels represent time to run tasks and last field is for command.

[Minute][Hour][Day_of_the_Month][Month_of_the_year][Day_Of_the_Week][Command]

Install cron package


[root@asim ~]#yum install cronie

Start cron service


[root@asim ~]#systemctl start crond

Check whether the crond service is running


[root@asim ~]#systemctl status crond

Add or update job in crontab (e=edit)


[root@asim ~]#crontab -e

Add or update job in crontab for another user


[root@asim ~]#crontab –u username -e

View crontab entries of current user (l=list)


[root@asim ~]#crontab -l

View crontab entries of another user


[root@asim ~]#crontab –u username –l

Remove crontable entries


[root@asim ~]#crontab -r

Add job to cron table


[root@asim ~]#crontab -e

Schedule the script to run at 1AM every Friday


minute:0hour:1, Day of month:*(every day of month),
Month:*(every Month) Day:5(Friday)
[root@asim ~]#0 1 * * 5

Add job to cron table


[root@asim ~]#crontab -e

Runs every minute to create test.txt file


[root@asim ~]#* * * * * touch /test.txt
Runs at 6:30 am every day
[root@asim ~]#30 6 * * * touch /test1.txt

Runs at 6:30 pm every day


[root@asim ~]#30 18 * * * touch /test.txt

Runs at 11 am everyday to remove all file from temp


[root@asim ~]#00 11 * * * rm –f /var/tmp/*

Control Access to File with Access Control


List
July 14, 2019

Introduction:

Files and directories have permission sets for the owner of the file along with the group
associated with that file and all other users of that system. But these permission sets have some
limitations. Such as Different permissions cannot be configured for different users. Thus, Access
Control List (ACL) were implemented. ACLs can be configured as per user, per group and for
users not in the user group for the file.

ACL requires kernel support and kernel must support ACL in order to implement ACL on Linux
distribution. Along with support in the kernel, the ACL package is also required to implement
ACLs. ACL package contains the utilities used to add, modify, remove andr retrive ACL
information from a file and folder. The file system needs to be mounted with ACL support
enabled. XFS filesystem have built in ACL support and Ext4 filesystem in RHEL7 have ACL
option enabled by default.

ACL use only two commands getfacl (Get File Access Control List) to see ACL permissions on
directory/file and setfact (Set File Access Control List) to set ACL permissions. The + sign at the
end of the permissions. This confirm that the file has an ACL attached to it. POSIX (Portable
Operating System Interface) ACL are two types ACL:

Access ACLs:

Access ACL is used to grand permission for a particular file or directory.

Default ACLs:
Default ACl can be used on directory level only. Any stub directory or file created within that
directory will inherit the ACLs from its parent directory. Make use of “-d”

for setting default ACLs and Default ACLs are optional.

To check kernel supports ACL or not


[root@asim ~]# cat /boot/config* | grep_ACL

If display ACL=y, kernel support ACL


[root@asim ~]# grep –I acl /boot/config*

To install ACL
[root@asim ~]# yum install acl

Display ACL and permission of file


[root@asim ~]# ls –l f1.txt

Set ACL for user asim on f1.txt


[root@asim ~]# setfacl –m u:asim:rw f1.txt

Set ACL for group xyz on directory dir1


[root@asim ~]# setfacl –m g:xyz:rw dir 1

Set the Default ACL for f1.txt


[root@asim ~]# setfacl –m d:o:rx f1

Set the default ACL for user asim on dir1


[root@asim ~]# setfacl –md –m u:asim:rx dir1

Set ACL on all files and subfolders in a dir1


[root@asim ~]# setfacl –R –m g:xyz:rw dir1

Remove ACL for all uses from directory dir1


[root@asim ~]# setfacl –R –b dir1

Remove ACL for user ahmad only on f1.txt


[root@asim ~]# setfacl –x u:asim f1.txt

Remove ACL for group xyz only on f1


[root@asim ~]# setfacl –x g:xyz f1

Remove entire ACL from file or folder


[root@asim ~]# setfacl –b f1.txt
Connecting to Network-defined Users and
Groups
July 20, 2019

Introduction:

Keeping local user accounts for all these machines and their services in sync is a daunting task,
even more so when passwords need to remain synced.

A solution to this is to not store account information on local system, but instead retrieve this
information from a centralized store. having user information, and the associated authentication
information, centralized also allows for something call Single Sign-On (SSO). With SSO, a user
authenticates once using a password (or other means, and then obtains a form of ticket or cookie
that can be used to automatically authenticate to other services.

A centralized identity management system will need to provide at least two service:

Account information: This includes information such as username, home directory location,
UID ad GID, group membership, etc. Popular solutions include LDAP(Lightweight Directory
Access Protocol), used in multiple products such as Active Directory and IPA Server, and
Network Information Service (NIS).

Authentication information: A means for a system for a system to validate that a user is who
he/she claims to b e. This can be done by providing a cryptographic password hash to the client
system, or by sending the (encrypted) password to the server, and receiving a response. An
LDAP server can provide authentication information in addition to account information.
Kerberos only provides SSO authentication services, and is typically used alongside LDAP user
information. Kerberos is used in both IPA server and Active Directory.

1.Install the LDAP package


[root@linux1 ~]# yum -y install openldap* migrationtools

2.Create a LDAP root password for administration purpose


[root@linux1 ~]# slappasswd
New password:
Re-enter new password:
{SSHA}bHSiwuPJEypHS6zHSE2Uy7M69sQjmkPL

Note: copy the encrypted password and save it somewhere


3.Edit the openLDAP server configuration
[root@linux1 ~]# cd /etc/openldap/slapd.d/cn=config
[root@linux1 cn=config]# vi olcDatabase={2}hdb.ldif

change the variable of “olcSuffix” and “olxRootDN” according to your domain below:
olcSuffix: dc=learnitguide,dc=net
olcRootDN: cn=Manager,dc=learnitguide,dc=net

Add the below three lines additionally in the same configuration file olcRootPW:
{SSHA}bHSiwuPJEypHS6zHSE2Uy7M69sQjmkPL
olcTLSCertificateFile: /etc/pki/tls/certs/learnitguideldap.pem
olcTLSCertificateKeyFile: /etc/pki/tls/certs/learnitguideldapkey.pem

Note: Replace the “olxRootPW” value with your copied password

4.Providing the Monitor privileges


[root@linux1 cn=config]# vi olcDatabase={1}monitor.ldif
olcAccess: {0}to * by dn.base=”gidNumber=0+uidNumber=0,cn=peercred,cn=external, cn=auth” read
by dn.base=”cn=Manager,dc=learnitguide,dc=net” read by * none

Verify the configuration


[root@linux1 cn=config]# slaptest -u 56abba86 ldif_read_file: checksum error on
“/etc/openldap/slapd.d/cn=config/olcDatabase={1}monitor.ldif”
56abba86 ldif_read_file: checksum error on
“/etc/openldap/slapd.d/cn=config/olcDatabase={2}hdb.ldif”
config file testing succeeded

5.Enable and start the SLDAP service


[root@linux1 cn=config]# systemctl start slapd
[root@linux1 cn=config]# systemctl enable slapd
[root@linux1 cn=config]# netstat -lt | grep ldap tcp 0 0
0.0.0.0:ldap 0.0.0.0:* LISTEN tcp6 0 0 [::]:ldap [::]:* LISTEN

6.Configure the LDAP database


[root@linux1 cn=config]# cp /usr/share/openldap-servers/DB_CONFIG.example
/var/lib/ldap/DB_CONFIG
[root@linux1 cn=config]# chown -R ldap:ldap /var/lib/ldap/

Add the following LDAP Schemas


[root@linux1 cn=config]# ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/cosine.ldif
[root@linux1 cn=config]# ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/nis.ldif
[root@linux1 cn=config]# ldapadd -Y EXTERNAL -H ldapi:/// -f
/etc/openldap/schema/inetorgperson.ldif
7.Create the Self-signed Certificate
root@linux1 cn=config]# openssl req -new -x509 -nodes -out
/etc/pki/tls/certs/learnitguideldap.pem -keyout
/etc/pki/tls/certs/learnitguideldapkey.pem -days 365

Country Name (2 letter code) [XX]:IN


State or Province Name (full name) []:Chennai
Locality Name (eg, city) [Default City]:Chennai
Organization Name (eg, company) [Default Company Ltd]:Learnitguide Organizational Unit Name (eg,
section) []:DCOPS
Common Name (eg, your name or your server’s hostname)
[]:linux1.learnitguide.net
Email Address []:root@linux1.learnitguide.net

[root@linux1 cn=config]# ll /etc/pki/tls/certs/*.pem -rw-r–r–. 1 root root 1704 Jan 8 14:52


/etc/pki/tls/certs/learnitguideldapkey.pem
-rw-r–r–. 1 root root 1497 Jan 8 14:52 /etc/pki/tls/certs/learnitguideldap.pem

8.Create base objects in openLDAP


[root@linux1 cn=config]# cd /usr/share/migrationtools/
[root@linux1 migrationtools]# vi migrate_common.ph

Go to line number 71 and change your domain name


$DEFAULT_MAIL_DOMAIN = “learnitguide.net”;

Go to line number 74 and change your base name


$DEFAULT_BASE = “dc=learnitguide,dc=net”;

Go to line number 90 and change your EXTENDED_SCHEMA from 0 to 1


$EXTENDED_SCHEMA = 1;
Finally save and exit.

9.Generate a base.ldif file for your domain


[root@linux1 migrationtools]# touch /root/base.ldif

copy the below and paste inside /root/base.ldif


dn: dc=learnitguide,dc=net
objectClass: top
objectClass: dcObject
objectclass: organization
o: learnitguide net
dc: learnitguide

dn: cn=Manager,dc=learnitguide,dc=net
objectClass: organizationalRole
cn: Manager
description: Directory Manager

dn: ou=People,dc=learnitguide,dc=net
objectClass: organizationalUnit
ou: People

dn: ou=Group,dc=learnitguide,dc=net
objectClass: organizationalUnit
ou: Group

10.Create a local user


[root@linux1 migrationtools} # useradd ldapuser1
[root@linux1 migrationtools} # useradd ldapuser2
[root@linux1 migrationtools] # echo “redhat” | passwd –stdin ldapuser1
[root@linux1 migrationtools] # echo “redhat” | passwd –stdin ldapuser2

[root@linux1 migrationtools]# grep “:10[0-9][0-9]” /etc/passwd > /root/passwd

[root@linux1 migrationtools]# grep “:10[0-9][0-9]” /etc/group > /root/group

[root@linux1 migrationtools]# ./migrate_passwd.pl /root/passwd /root/users.ldif

[root@linux1 migrationtools]# ./migrate_group.pl /root/group /root/groups.ldif

11.Import user into the LDAP database


[root@linux1 migrationtools]# ldapadd -x -W -D “cn=Manager,dc=learnitguide,dc=net” -f
/root/base.ldif

[root@linux1 migrationtools]# ldapadd -x -W -D “cn=Manager,dc=learnitguide,dc=net” -f


/root/users.ldif

[root@linux1 migrationtools]# ldapadd -x -W -D “cn=Manager,dc=learnitguide,dc=net” -f


/root/groups.ldif

12.Test the configuration


[root@linux1 migrationtools]# ldapsearch -x cn=ldapuser1 -b dc=learnitguide,dc=net

[root@linux1 migrationtools]# ldapsearch -x -b ‘dc=learnitguide,dc=net’ ‘(objectclass=*)’

13.Stop firewall to allow connection.


[root@linux1 migrationtools]# systemctl stop firewalld
14.NFS configuration to export home directory
[root@linux1 ~]# vi /etc/exports
/home *(rw,sync)

Enable and restart rpcbind and nfs service


[root@linux1 ~]# yum -y install rpcbind nfs-utils
[root@linux1 ~]# systemctl start rpcbind
[root@linux1 ~]# systemctl start nfs
[root@linux1 ~]# systemctl enable rpcbind
[root@linux1 ~]# systemctl enable nfs

Test the NFS configuration


[root@linux1 ~]# showmount -e
Export list for linux1.learnitguide.net:
/home *

Client End Configuration

1.LDAP client configuration to use LDAP server


[root@linux2 ~]# yum install -y openldap-clients nss-pam-ldapd
[root@linux2 ~]# authconfig-tui

Steps to follow for LDAP Authentication: 1.Put ‘*’ mark on ‘Use LDAP’ 2.Put ‘*’ mark on ‘Use LDAP
Authentication’ 3.Select Next and Enter. 4.Enter the server field as “ldap://linux1.learnitguide.net/”
5.Enter the base DN field as “dc=learnitguide,dc=net” 6.Select ok and Enter

2.Test the client Configuration


[root@linux2 ~]# getent passwd ldapuser1
ldapuser1:x:1000:1000:ldapuser1:/home/ldapuser1:/bin/bash

3.Mount the LDAP user home directory


linux1.learnitguide.net:/home /home auto defaults 0 0s

Managing Logical Volume Management


(LVM) Storage
July 28, 2019
Table of Contents

 Introduction:
 LVM Definitions:
 Implementing LV storage
 Reviewing LVM status information
 Removing a logical volume

Introduction:

Logical Volumes and logical volume management make it easier to manage disk space. If a
LVM-hosted file system needs more space, it can be allocated to its logical volume from the free
space in its volume group and the file system can be resized. If a disk starts to fail, a replacement
disk can be registered as a physical volume with the volume group and the logical volume’s
extents can be migrated to the new disk.

LVM Definitions:

Physical devices are the storage devices used to persist data stored in a logical volume. These are
block devices and could be disk partitions, whole disks, RAID arrays, or SAN disks. A device
must be initialized as an LVM physical volume in order to be used with LVM. The entire
“device” will be used as a physical volume.

Physical Volume (PV): PV are used to register underlying physical devices for use in volume
groups. LVM automatically segments PVs into physical extents (PE); these are small chunks of
data that act as the smallest storage block on a PV.

Volume Group (VG): VG are storage pools made up of one or more physical volumes. A PV
can only be allocated to a single VG. A VG can consist of unused space and any number of
logical volumes.

Logical Volumes (LV): LV are created from free physical extents in a volume group and
provide the “storage” device used by applications, users, and the operating system. LVs are a
collection of logical extents (LE), which map to physical extents, the smallest storage chunk of a
P.V. By default, each LE will map to one PE. Setting specific LV options will change this
mapping; for example, mirroring causes each LE to map two Pes.

Implementing LV storage

The first step is to add external storage like Hard disk or ISCSI to the virtual machine, then
follow the below steps:

Prepare the physical device


[root@asim ~]# fdisk /dev/sdb
Create a physical volume
[root@asim ~]# pvcreate /dev/sdb1 /dev/sdb2

Create a volume group


[root@asim ~]# vgcreate vg-alpha /dev/sdb1 /dev/sdb2

Create a logical volume


[root@asim ~]# lvcreate –a Hercules –L 2G vg-alpha

Add the file system


[root@asim ~]# mkfs –t xfs /dev/vg-alpha/Hercules

To make the file system available access reboots:

Use mkdir to create a mount point directory


[root@asim ~]# mkdir /mnt/Hercules

Add an entry to the /etc/fstab file:


/dev/vg-alpha/hercules /mnt/hercules xfs defaults 1 2

Run mount –a to mount all the file systems in /etc/fstab, including the entry just added.
[root@asim ~]# mount –a

Reviewing LVM status information


Physical Volume
[root@asim ~]# pvdisplay /dev/sdb2

Volume Group
[root@asim ~]# vgdisplay vg-alpha

Logical Volumes
[root@asim ~]# lvdisplay /dev/vg-alpha/hercules

Removing a logical volume


Prepare the file system
[root@asim ~]# umount /mnt/hercules

Remove the logical volume


[root@asim ~]# lvremove /dev/vg-alpha/hercules

Remove the volume group


[root@asim ~]# vgremove vg-alpha
Remove the physical volume
[root@asim ~]# pvremove /dev/sdb1 /dev/sdb2

Accessing Network Storage with SMB


July 21, 2019

Introduction:

Many organization need to provide network storage and print services for a range of desktop
operating systems. Red Hat Enterprise Linux uses the Samba server to provide services that
Microsoft Windows clients can use. Samba implements the Server Message Block(SMB)
protocol, and Common Internet File System(CIFS) is a dialect of SMB. Often the two names are
users interchangeably.

The basic steps for Accessing an SMB share:

1. Identify the remote share to access.

2. Determine a mount point where the share should be mounted and created the mount points
empty directory.

3. Mount the network file system with an appropriate command or configuration change.

INSTALLING SAMBA ON LINUX REDHAT/CENTOS

To install Samba, you will need to become root with the following command (give the root password,
when prompted):
$ su –

Then use Yum to install the Linux Samba package:


# yum install samba

Before you begin to use or configure Samba, the Linux Firewall (iptables) has to be configured to allow
Samba traffic. From the command-line, this is achieved with the use of the following command:
# firewall-cmd –enable –service=samba

CONFIGURING LINUX SAMBA


The Samba configuration is meant to join an RHEL, Fedora or CentOS system to a Windows
Workgroup and setting up a directory on the RHEL system, to act as a shared resource that can
be accessed by authenticated Windows users.

To start with, you must gain root privileges with (give the root password, when prompted):
$ su –

Edit the Samba configuration file:


# vi /etc/samba/smb.conf

THE SMB.CONF [GLOBAL] SECTION

sAn smb.conf file is divided into several sections. the [global] section, which is the first section, has
settings that apply to the entire Samba configuration. However, settings in the other sections in the
configuration file may override the global settings.
To begin with, set the workgroup, which by default is set as “MYGROUP”: workgroup = MYGROUP
Since most Windows networks are named WORKGROUP by default, the settings have to be changed as:
workgroup = workgroup

CONFIGURE THE SHARED RESOURCE

In the next step, a shared resource that will be accessible from the other systems on the Windows
network has to be configured. This section has to be given a name by which it will be referred to
when shared. For our example, let’s assume you would like share a directory on your Linux
system located at /data/network-applications. You’ll need to entitle the entire section as
[NetApps] as shown below in our smb.conf file:

[NetApps]
path = /data/network-applications
writeable = yes
browseable = yes valid users = administrator
When a Windows user browses to the Linux Server, they’ll see a network share labeled
“NetApps”.
This concludes the changes to the Samba configuration file.

CREATE A SAMBA USER

Any user wanting to access any Samba shared resource must be configured as a Samba User and
assigned a password. This is achieved using the smbpasswd command as a root user. Since you
have defined “administrator” as the user who is entitled to access the “/data/network-
applications” directory of the RHEL system, you have to add “administrator” as a Samba user.
You must gain root privileges with the following command (give the root password, when prompted):
$ su –

Add “administrator” as a Windows user –


# smbpasswd -a administrator

The system will respond with


New SMB password: <Enter password>
Retype new SMB password: <Retype password>
This will result into the following message:

Added user administrator

It will also be necessary to add the same account as a simple linux user, using the same password we
used for the samba user:
# adduser administrator
# passwd administrator
Changing password for user administrator
New UNIX password: ********
Retype new UNIX password: ********
passwd: all authentication tokens updated successfully.

Now it is time to test the samba configuration file for any errors. For this you can use the command line
tool “testparm” as root:
# testparm Load smb
config files from /etc/samba/smb.conf
Rlimit_max: rlimit_max (1024) below minimum Windows limit (16384)
Processing section “[NetApps]”
Loaded services file OK.
Server role: ROLE_STANDALONE
Press enter to see a dump of your service definitions

If you would like to ensure that Windows users are automatically authenticated to your Samba
share, without prompting for a username/password, all that’s needed is to add the samba user and
password exactly as you Windows clients usernames and password. When a Windows system
accesses a Samba share, it will automatically try to log in using the same credentials as the user
logged into the Windows system.

STARTING SAMBA AND NETBIOS NAME SERVICE ON RHEL

The Samba and NetBios Nameservice or NMB services have to be enabled and then started for them to
take effect:
# systemctl enable smb.service
# systemctl start smb.service
# systemctl enable nmb.service # systemctl start nmb.service

In case the services were already running, you may have to restart them again:
# systemctl restart smb.service
# systemctl restart nmb.service

ACCESSING THE SAMBA SHARES FROM WINDOWS

Now that you have configured the Samba resources and the services are running, they can be
tested for sharing from a Windows system. For this, open the Windows Explorer and navigate to
the Network page. Windows should show the RHEL system. If you double-click on the RHEL
icon, you will be prompted for the username and password. The username to be entered now is
“administrator” with the password that was assigned.

Again, if you are logged on your Windows workstation using the same account and password as
that of the Samba service (e.g Administrator), you will not be prompted for any authentication as
the Windows operating system will automatically authenticate to the RHEL Samba service
using these credentials.

Limiting Network Communication with


firewalld
July 27, 2019

Table of Contents

 Introduction:
 Default configuration of firewalld zones
 Pre-defined service
 Configure firewall setting

Introduction:

In Re Hat Enterprise Linux 7 a new method of interacting with netfilter has been introduced:
firewalld. Firewalld is a system daemon that can configure an monitor the system firewall rules.
Application can talk to firewall to request porots to be opened using the DBus messaging system,
a feature which can be isabled or locked down. It both covers IPv4, IPv6, and potentially
ebtables settings. The firewalld daemons is installed from the firewall package. This package is
part of a base install, but not part of a minimal install.

Firewalld simplifies firewall management by classifying all network traffic into zones. Based on
criteria such as the source IP address of a packet or the incoming network interface, traffic is
then diverted into the firewall rules for the appropriate zone. Each zone can have its own list of
ports and service to be opened or closed.

Default configuration of firewalld zones


Trusted Allow all incoming traffic.

Reject incoming traffic unless related to outgoing traffic or matching the ssh, mdns, ipp-client,
Home
samba-client, or dhcpv6-client pre-defined services.

Reject incoming traffic unless related to outgoing traffic or matching the ssh, mdns, ipp-client,
Internal
samba-client, or dhcpv6-client pre-defined services(same as the home zone to start with)

Reject incoming traffic unless relate to outgoing traffic or matching the ssh, ipp-client, or
Work
dhcpv6-client pre-defined services.

Reject incoming traffic unless relate to outgoing traffic or matching the ssh, ipp-client, or
Public
dhcpv6-client pre-defined services. The default zone for newly-added network interface.

Reject incoming traffic unless relate to outgoing traffic or matching the ssh, pre-defined
External services. Outgoing ipv4 traffic forwarded through this zone is masqueraded to look like it
originate from the ipv4 address of the outgoing network interface.

Reject incoming traffic unless related to outgoing traffic or matching the ssh pre-defined
Dmz
service.

Block Reject all incoming traffic unless related to outgoing traffic.

Drop all incoming traffic unless related to outgoing traffic (do not even respond with ICMP
Drop
errors).

Pre-defined service

Firewalld also ships with a number of pre-defined services. These service definitions can be
used to easily permit traffic for particular network services to pass through the firewall.

Selected pre-defined firewalld services

ssh Local SSH server. Traffic to 22/tcp

dhcpv6-
Local DHCPv6 client. Traffic to 546/udp on the fe80::/64 IPv6 network
client
ipp-client Local IPP printing. Traffic to 631/udp

samba-
Local Windows file and print sharing client. Traffic to 137/udp and 138/udp.
client

Multicast DNS (mDNS) local-link name resolution. Traffic to 5353/udp to the 224.0.0.251
mdns
(IPv4) or ff02::fb (IPv6) multicast addresses.

Configure firewall setting

[root@asim ~]# yum –y install httpd mod_ssl

[root@asim ~]# bash –c “echo ‘I am alive’ > /var/www/html/index.html”

[root@asim ~]# systemctl start httpd

[root@asim ~]# systemctl enable httpd

[root@asim ~]# systemctl mask iptables

[root@asim ~]# systemctl mask ip6tables

[root@asim ~]# systemctl status firewalld

[root@asim ~]# firewall-config

From the configuration dropdown menu, select Permanent to switch to editing the permanent
configuration

Add the https service to the list of services allowed in the public zone.

In the Zone list, select public. Since this zone is also the default zone, it is highlighted in bold.

In the Service tab, add a checkmark in front of the https service.

Activate your firewall configuration by selecting Options > Reload Firewalld from the menu.

Verify your work by attempting to view your web server contents from client PC.

[root@asim ~]#curl –k http://study.eiheducation.in

[root@asim ~]#curl –k https://study.eiheducation.in

This is how you configure firewalld. Follow are the some other firewalld example:
Query the current default zone.
[root@asim ~]# firewall-cmd – – get – default – zone

Set the default zone.


[root@asim ~]# firewall-cm – – default – zone = <Zone>

List all available zones.


[root@asim ~]# firewall – cmd – get – zones

List all zones currently in use (have an interface or source tied to them), along with their interface and
source information.
[root@asim ~]# firewall – cmd – – get – active – zones

Route all traffic coming from the IP address or network/netmask <CIDR> to the specified zone. If no – –
zone = option is provide, the default zone will be used.
[root@asim ~]# firewall – cmd – – add – source = <CIDR> [ – – zone = <ZONE>]

Remove the rule of routing all traffic coming from the IP address or network/netmask <CIDR> to the
specified zone. If no – – zone = option is provide, the default zone will be used.
[root@asim ~]# firewall – cmd – – remove – source = <CIDR> [- – zone = <ZONE>]

Route all traffic coming from <INTERFACE> to the specified zone. If no –zone= option is provided, the
default zone will be used.
[root@asim ~]# firewall – cmd – – add – interface = <INTERFACE> [ – – zone = <ZONE>]

Associate the interface with <ZONE> instead of its current zone. If no –zone= option is provided, the
default zone will be used.
[root@asim ~]# firewall – cmd — change – interface = <INTERFACE> [- – zone = <ZONE>]

List all Zones.


[root@asim ~]# firewall – cmd – – list – all [- – zone=<ZONE>]

Retrieve all information for all zones.


[root@asim ~]# firewall – cmd – – list – all – zone

Allow traffic to any service.


[root@asim ~]# firewall – cmd – – add – service=<Service> [ – – zone = <ZONE>]

Allow traffic to Ports.


[root@asim ~]# firewall – cmd – – add – port = <PORT/PROTOCOL> [- – zone=<ZONE>]

Remove service from the zone.


[root@asim ~]# firewall – cmd – – remove – service = <Service> [- – zone= <ZONE>]
Remove ports from the zone.
[root@asim ~]# firewall – cmd — remove – port = <PORT/PROTOCOL> [– zone =<ZONE>]

Apply the firewall.


[root@asim ~]# firewall – cmd – – reload

==================================================================================

You might also like