You are on page 1of 74

Introduction

### Course Introduction

  - Take me to the [Video Tutorial]
(https://kodekloud.com/courses/873064/lectures/17080332)
  
### WAR (Story)

  - Take me to the [Video Tutorial]
(https://kodekloud.com/courses/873064/lectures/17080232)

### Bob's First Day at Work

  - Take me to the [Video Tutorial]
(https://kodekloud.com/courses/873064/lectures/17080284)

### Lab Introduction

- Take me to the [Video Tutorial]
(https://kodekloud.com/courses/873064/lectures/17317208)

# Working with the shell - I

### Introduction to Shell

- Take me to the [Video Tutorial]
(https://kodekloud.com/courses/873064/lectures/17074335)

In this section, we will take a look at linux shell in detail. 
- We will learn how to use linux commands and understand how to work with file
s and directories. 
- We will also see different ways to get help with linux commands. 
- Finally, we will learn about different types of shells used in Linux (partic
ulary focusing on the bash shell)

#### Linux shell

![Shell](../../images/Shell.PNG)

- This command line interface (CLI) will enable you to effectively work on lin
ux laptop/server/virtual machine.
- While the graphical version may see more appealing to the users but can be l
imited in case of functionality. These is where the Linux command line ccommon
ly known as **`Linux Shell`** shines.

  #### What is a shell?
  - Linux shell is a program that allows text based interaction between the us
er and the operating system, this interaction is carried out by typing command
s into the interface and receving the response in the same way.
  - The Linux shell is a powerful tool with which you can navigate between dif
ferent locations within the system, however when you login to the shell the ve
ry first directory you were take into is your home directory.

#### The Home Directory

![The-Home-Directory](../../images/The_Home_Directory.JPG)
 
- A user **`michael`** home directory created under **`/home/michael`**, where 
**`/home`** is a system created home directory that contains the home director
ies for almost all users in the linux system. 
- The name of the home directory is by default identical to the name of the us
er, hence **`michael's`** home directory is **`/home/michael`**.
- Remember the home directory is unique for each user. Another user called **`
allen`** will have a different home directory which by default created under *
*`/home/allen`**.

  ##### Why do we need a home directory?
  - The home directory allows users to store their personal data in the form o
f files and directories
  - Each user in the system gets their own unique home directory with complete 
access to it (to be able to save, retreive , delete data).
  - Think of it as a dedicated locker assign to you in which you can store or 
retreive items.
  - Other users can't access your files and folders with in your home director
y (only you can).

**Note** : The representation of the home directory is represented as by the `
~ (tilde symbol).`

#### Command Prompt

- You can configure the command prompt to show whatever you want, such as the 
**`hostname`** , **`date`** or **`time`**. 
- It is currently configured to show the current working directory. The **`~` 
symbol**  here represents the home directory

#### Command and Arguments

- To interact with the linux system using the shell, a user has to type in com
mands
- When a command is run it executes a program to achieve a specific task.
  - **`For example`**: The **`echo`** command is used to print a line of text 
on the screen.
  ```
                          $ echo 
  ```
- An argument acts as an input to command
  - **`For example`**: To print a **`hello`** message type **`echo hello`** co
mmand.
  ```
                          $ echo hello
  ```
- There are several commands that can work without an argument too.
  - **`For example`**: Type in the command called **`uptime`**, this is used t
o print information about how long a system has been running for since the las
t reboot along with the other information (This command doesn't need an argume
nt)
  ```
                          $ uptime 
  ```
- A command can also have options that modify its behaviour in some predetermi
ne way. The option also sometime referred to as a switch or a flag 
  - **`For example`**: To print a same word `hello` but without a trailing lin
e, use **`echo`** command with **`-n`** flag.
  ```
                          $ echo -n hello
  ```
  
![Command-and-Arguments](../../images/Command-and-Arguments.PNG)

#### Command Types

Command types in linux can be generally categorized in two types
 1. Internal or Built-in Commands 
    - Internal commands are part of the shell itself. It come bundled with it, 
there are in total about 30 such commands
    - **`For example`**: echo, cd, pwd, set e.t.c.
 1. External Commands
    - External commands on the other hand are binary programs or scripts which 
are usually located in distinct files in the system. They either come with pre
-install with the distribution package manager or can be created or installed 
by the user
    - **`For Example`**: mv, date, uptime, cp e.t.c.
    
To determine a command is internal or external, use **`type`** command
 
![Command-Types](../../images/Command-Types.PNG)

# Working with the shell - I

### Introduction to Shell
- Take me to the [Video Tutorial]
(https://kodekloud.com/courses/873064/lectures/17074335)

In this section, we will take a look at linux shell in detail. 
- We will learn how to use linux commands and understand how to work with file
s and directories. 
- We will also see different ways to get help with linux commands. 
- Finally, we will learn about different types of shells used in Linux (partic
ulary focusing on the bash shell)

#### Linux shell

![Shell](../../images/Shell.PNG)

- This command line interface (CLI) will enable you to effectively work on lin
ux laptop/server/virtual machine.
- While the graphical version may see more appealing to the users but can be l
imited in case of functionality. These is where the Linux command line ccommon
ly known as **`Linux Shell`** shines.

  #### What is a shell?

  - Linux shell is a program that allows text based interaction between the us
er and the operating system, this interaction is carried out by typing command
s into the interface and receving the response in the same way.
  - The Linux shell is a powerful tool with which you can navigate between dif
ferent locations within the system, however when you login to the shell the ve
ry first directory you were take into is your home directory.

#### The Home Directory

![The-Home-Directory](../../images/The_Home_Directory.JPG)
 
- A user **`michael`** home directory created under **`/home/michael`**, where 
**`/home`** is a system created home directory that contains the home director
ies for almost all users in the linux system. 
- The name of the home directory is by default identical to the name of the us
er, hence **`michael's`** home directory is **`/home/michael`**.
- Remember the home directory is unique for each user. Another user called **`
allen`** will have a different home directory which by default created under *
*`/home/allen`**.

  ##### Why do we need a home directoy?
  - The home directory allows users to store their personal data in the form o
f files and directories
  - Each user in the system gets their own unique home directory with complete 
access to it (to be able to save, retreive , delete data).
  - Think of it as a dedicated locker assign to you in which you can store or 
retreive items.
  - Other users can't access your files and folders with in your home director
y (only you can).

**Note** : The representation of the home directory is represented as by the `
~ (tilde symbol).`

#### Command Prompt

- You can configure the command prompt to show whatever you want, such as the 
**`hostname`** , **`date`** or **`time`**. 
- It is currently configured to show the current working directory. The **`~` 
symbol**  here represents the home directory

#### Command and Arguments

- To interact with the linux system using the shell, a user has to type in com
mands
- When a command is run it executes a program to achieve a specific task.
  - **`For example`**: The **`echo`** command is used to print a line of text 
on the screen.
  ```
                          $ echo 
  ```
- An argument acts as an input to command
  - **`For example`**: To print a **`hello`** message type **`echo hello`** co
mmand.
  ```
                          $ echo hello
  ```
- There are several commands that can work without an argument too.
  - **`For example`**: Type in the command called **`uptime`**, this is used t
o print information about how long a system has been running for since the las
t reboot along with the other information (This command doesn't need an argume
nt)
  ```
                          $ uptime 
  ```
- A command can also have options that modify its behaviour in some predetermi
ne way. The option also sometime referred to as a switch or a flag 
  - **`For example`**: To print a same word `hello` but without a trailing lin
e, use **`echo`** command with **`-n`** flag.
  ```
                          $ echo -n hello
  ```
  
![Command-and-Arguments](../../images/Command-and-Arguments.PNG)
#### Command Types

Command types in linux can be generally categorized in two types
 1. Internal or Built-in Commands 
    - Internal commands are part of the shell itself. It come bundled with it, 
there are in total about 30 such commands
    - **`For example`**: echo, cd, pwd, set e.t.c.
 1. External Commands
    - External commands on the other hand are binary programs or scripts which 
are usually located in distinct files in the system. They either come with pre
-install with the distribution package manager or can be created or installed 
by the user
    - **`For Example`**: mv, date, uptime, cp e.t.c.
    
To determine a command is internal or external, use **`type`** command
 
![Command-Types](../../images/Command-Types.PNG)

# Basic Linux Commands

- Take me to the [Video Tutorial]
(https://kodekloud.com/courses/873064/lectures/17309223)

In this section, we will take a look at basic linux commands 
- Specifically related to navigation and creating new files and directories.
- We will do this by completing a simple task using a linux shell.

#### Our goal is to create a directory structure, the top most directory which 
is **`/home/michael`** which is already created as it as a home directory but 
everything else underneath has to be created. 

![mkdir_cd_working_with_shell_I]
(../../images/mkdir_cd_working_with_shell_I.PNG)

To print the present working directory. Run **`pwd`** command
```
$ pwd
```

To see the contents of the directory. Run **`ls`** command
```
$ ls 
````

To make (or) create a directory. Run **`mkdir`** command
```
$ mkdir Asia
```

To make (or) create multiple directories. Run **`mkdir`** command followed by 
**`<directory_name1> <directory_name2> .. <directory_nameN>`**
```
$ mkdir Europe Africa America
```

To change a directory from the current directory. Run **`cd <directory_name>`*
*
```
$ cd Asia
```

To recursively created directories. Run **`mkdir -p <directory_name1>/<sub_dir
ectory_of_name1>`**
```
$ mkdir -p India/Mumbai
```

To go back to one directory up. Run **`cd ..`**
```
$ cd ..
```

To go back directly to a home directory of the current user from any location 
in the system. Run **`cd`**
```
$ cd
```

#### Lets now look at absolute path and relative path

![Absolute_and_relative_path_working_with_shell_I]
(../../images/Absolute_and_relative_path_working_with_shell_I.PNG)

To change to a directory with absolute path. Run **`cd <directory_path>`**
```
$ cd /home/michael
```

To Change to a directory with relative path. Run **`cd <directoryName>`**
```
$ cd Asia
```
#### Lets now take a look at alternatives to the **`cd`** command

![pushd_popd](../../images/pushd_popd.PNG)

Alternative to the **`cd`** is the **`pushd\popd`** command. To change directo
ry using pushd, run **`pushd <directory_name>`**
```
$ pushd /etc
```

You can change to subdirecties under /etc as many times as you wish
```
$ pushd /var
$ pushd /tmp
$ pwd
/etc/var/tmp
```

To return back to origin directoy(say your home directory), use the **`popd`** 
command
```
$ popd
```

#### Now lets move on to look some more basic commands in linux. To learn thes
e commands we will make use of the same directory structure as before, however 
now there are some new files and directories added as shown in the diagram. Th
e goal of this task is to make sure the directory structure looks like the bel
ow diagram .

![before_after_commands](../../images/before_after_commands.PNG)

To move file or directory. Run **`mv <source> <destination>`** command
```
$ mv /home/michael/Europe/Morocco /home/michael/Africa/ (Absolute path)
$ mv Europe/Morocco Africa/ (Relative Path)
```

To rename a directory. Run **`mv <oldname> <newname>`** command
```
$ mv Asia/India/Munbai Asia/India/Mumbai
```

To copy a file to a directory. Run **`cp <filename> <destination_directorypath
>`** command
```
$ cp Asia/India/Mumbai/City.txt Africa/Egypt/Cairo
```
To delete a file from a directory. Run **`rm /path/<filename>`** command
```
$ rm Europe/UK/London/Tottenham.txt
```

To copy a directory recursively. Run **`cp -r <sourcepath> <destinationPath>`*
* command
```
$ cp -r Europe/UK Europe/UnitedKingdom
```

To print the content of a file. Run **`cat /path/to/<filename>`** command
```
$cat Asia/India/Mumbai/City.txt
```

To add a content to a file with cat(redirect) . Run **`cat > /path/to/<filenam
e>`** command
```
$ cat > Africa/Egypt/Cairo/City.txt
  Cairo
  `Type Ctrl + d from keyboard`
```

To create an empty file. Run **`touch /path/to/filename`** command
```
$ touch /home/michael/Asia/China/Country.txt
```

To see the content of a file in a scrollable manner. Run **`more /path/to/file
name`** command <-- not recommended for large files
```
$ more new_file.txt
```

To see the content of a file and navigate throught the file. Run **`less /path
/to/filename`** command
```
$ less new_file.txt
```

To get the long list of files and directories. Run **`ls -l`** command
```
$ ls -l
```

To list all files including the hidden. Run **`ls -la`** command
```
$ ls -a
```

To list all the files in the order they were modified. Run **`ls -lt`** comman
d
```
$ ls -lt
```

To list all the files form oldest to newest. Run **`ls -ltr`** command
```
$ ls -ltr
```

# Using command line to get help

- Take me to the [Video Tutorial]
(https://kodekloud.com/courses/873064/lectures/17309225)

In this section we will learn how to use **`help`** command to get help in com
mand line
- If you are new to using `linux` or `bash shell`  or if you are not sure whic
h command does what, there are few commands in bash that can help get started. 
- Lets take a look of those

First command is **`whatis`** , this command will displays a one line descript
ion of a command does. 

**`Syntax: whatis <command>`**

```
$ whatis date
```

Most of the commands internal or external come bundled with **`man pages`** wh
ich provides information about the command in detail (with examples, usecases 
and with command options)

**`Syntax: man <command>`**

```
$ man date
```

Several commands will provide **`-h`** or **`--help`** to provide users with t
he options and usecases available in a command
```
$ date -h
$ date --help
```

To search through the man page names and descriptions for instances of the key
word use **`apropos`**. This is useful if you want to look for all commands wi
thin the system that contains the specifc keyword.

**`Syntax: apropos <keyword>`**
```
$ apropos modpr
```

# Lab - Working with shell

- Access Hands-On Labs here [Hands-On-Labs]
(https://kodekloud.com/courses/873064/lectures/17074343)

1. To check the home directory for a particular user say **`bob`**
   ```
   $ grep bob /etc/passwd | cut -d ":" -f6
   ```
1. To check the home directory for a particular user using built in shell vari
ables
   ```
   $ echo $HOME
   ```
1. In the command **`echo Welcome`**, what does the word Welcome represent wit
h respect to the command?
   ```
   $ echo Welcome 
     - Where Welcome is an argument
   ```
   
1. To check **`git`** command type
   ```
   $ type git
   ```
1. To create a directory
   ```
   $ mkdir /home/bob/birds
   ```
1. To create directories recursively
   ```
   $  mkdir -p /home/bob/fish/salmon
   ```
1. Create few more directories
   ```
   $ mkdir -p /home/bob/mammals/elephant
   $ mkdir -p /home/bob/mammals/monkey
   $ mkdir /home/bob/birds/eagle
   $ mkdir -p /home/bob/reptile/snake
   $ mkdir -p /home/bob/reptile/frog
   $ mkdir -p /home/bob/amphibian/salamander
   ```
1. To move a directory
   ```
   $ mv /home/bob/reptile/frog /home/bob/amphibian
   ```
1. To rename a directory
   ```
   $ mv /home/bob/reptile/snake /home/bob/reptile/crocodile
   ```
1. To delete a directory
   ```
   $ rm -r /home/bob/reptile
   ```

# Bash Shell

- Take me to the [Video Tutorial]
(https://kodekloud.com/courses/873064/lectures/17074351)

## Different types of Shells

In this section, we will take a look at different types of shells.
- There are different types of shells in linux, some of the popular ones are b
elow
  - Bourne Shell (sh)
  - C Shell (csh or tsh)
  - Korn Shell (ksh)
  - Z Shell (zsh)
  - Bourne again shell (Bash)
  
To check the shell being used. Use the command **`echo $SHELL`**
```
$ echo $SHELL
```

To change the default shell. Use the command chsh, you will be prompted for th
e password and following that input the name of the new shell. You have to log
in into new terminal session to see this change though.
```
$ chsh
```
## Bash Shell Features

1. Bash supports command auto-completion. What this means is bash means to aut
o-complete commands for you if you type part of it and press the **`tab`** key
   
   ![bash-auto](../../images/bash-auto.PNG)
   
   ![bash-auto1](../../images/bash-auto1.PNG)

1. In Bash we can set custom aliases for the actual commands
   ```
   $ date
   $ alias dt=date
   $ dt
   ```
1. Use the **`history`** command to list the previous run commands that you ra
n earlier
   ```
   $ history
   ```
   
 ## Bash environment variables
 
 To print **`SHELL`** environment variable
 ```
 $ echo $SHELL
 ```
 
 To see a list of all environment variables. Run **`env`** from the terminal
 ```
 $ env
 ```
 
 To set an environment variable with in the shell. The value is not carry forw
ard to any other process.
 ```
 $ OFFICE=caleston
 ```
 
 To set an environment variable we can use the **`export`** command. To make t
he value carry forward to any other process. 
 ```
 $ export OFFICE=caleston
 ```
 
 To persistently set an environment variable over subsequent login or a reboot 
add them to the **`~/.profile`** or **`~/.pam_environment`** in the users home 
directory.
 
 ```
 $ echo "export OFFICE=caleston" >> ~/.profile (or)
 $ echo "export OFFICE=caleston" >> ~/.pam_environment
 ```
 
 To check the value of a environment variable called **`LOGNAME`**
 ```
 $ echo $LOGNAME
 ```
 
## Path Variable

#### Speaking about the environment variables, when a user issues an external 
command into the shell, the shell uses path variable to search for these exter
nal commands
 
To see the directories defined in path variable. Use the command **`echo $PATH
`**.
```
$ echo $PATH
```

To check if the location of the command can be identified. Use the **`which`** 
command

**`Syntax: which <command>`**

```
$ which obs-studio
```

To define a command in the **`PATH`** variable. To add we can use the **`expor
t`** command.
```
$ export PATH=$PATH:/opt/obs/bin
$ which obs-studio
```

## Customize Bash Prompt

Once you login into the shell, the line you see is the bash prompt.

![bash-prompt](../../images/bash-prompt.PNG)
It can be customized to see the **`username`** and the **`hostname`**

![bash-prompt1](../../images/bash-prompt1.PNG)

#### The bash prompt is set in control by a set of special shell environment v
ariables. The most common of these and the one we will focus on is **`PS1`** v
ariable.

![bash-prompt2](../../images/bash-prompt2.PNG)

To see the value assign to **`PS1`**, type **`echo $PS1`**
```
$ echo $PS1
```

To change the PS1 to only display the word **`ubuntu-server`**.
```
$ PS1="ubuntu-server"
$ echo $PS1
```

#### To customize further, have a look at the below special character.

![bash-prompt3](../../images/bash-prompt3.PNG)

To change the bash prompt to display **`date`**, **`time`**, **`username of th
e current user`**, the **`hostname`** and the **`current working directory`**
```
$ PS1="[\d \t \u@\h:\w ] $ "
```

# Lab - Linux Bash Shell

- Access Hands-On Labs here [Hands-On Labs]
(https://kodekloud.com/courses/873064/lectures/17074355)

1. To check the default shell for the current user.Display the shell for the c
urrent user but not necessarily the shell that is running at the movement.
   ```
   $ echo $SHELL
   ```
1. To change the shell for bob from **`Bash`** to **`Bourne Shell`**
   ```
   $ chsh -s /bin/sh bob
   ```
   
  
Welcome Bob.

- Take me to the [Video Tutorial]
(https://kodekloud.com/courses/873064/lectures/17074358)

# Linux Core Concepts

- Take me to the [Video Tutorial]
(https://kodekloud.com/courses/873064/lectures/17080351)

In this section, we will take a look at the core concepts of a linux operating 
system.
- We will start with introduction to the linux kernel.
- We will then learn about the kernel space and user space.

## Linux Kernel

#### If you have worked with any operating system, you have run into the term 
kernel. 

- The Linux kernel is monolithic, this means that the kernel carrries out CPU 
scheduling, memory management and several operations by itselfs. 
- The Linux Kernel is also modular, which means it can extends its capabilitie
s through the use of dynamically loaded kernel modules

  ![linux-kernel](../../images/linux-kernel.PNG)

#### To understand a kernel in simple terms, let us use an analogy of a **`Col
lege Library`**. Here the librarian is equal to Linux Kernel.

![library](../../images/library.PNG)

#### The Kernel is responsible for 4 major tasks

1. Memory Management
1. Process Management
1. Device Drivers
1. System calls and Security

## Linux Kernel Versions

#### let us know identify the ways to identify linux kernel versions

Use **`uname`** command to get the information about the kernel (by itself it 
doesn't provide much information except that the system uses the **`Linux`** K
ernel.
```
$ uname
```

Use the **`uname -r`** or **`uname`** comamnd and option to print the kernel v
ersion
```
$ uname -r
$ uname -a
```
   ![kernel-versions](../../images/kernel-versions.PNG)

## Kernel and User Space

#### One of the important functions of the linux kernel is the **`Memory Manag
ement`** . We will now see how memory is seperated within the linux kernel

Memory is divded into two areas.
1. Kernel Space
   1. Kernel Code
   1. kernel Extensions
   1. Device Drivers
1. User Space
   1. C
   1. Java
   1. Python
   1. Ruby e.t.c
   1. Docker Containers
   
![memory-management](../../images/memory-management.PNG)

#### Let us know see how programs running in the `User Space` work

All user programs function by manipulating data that is stored in memory and o
n disk. User programs get access to data by making special request to the kern
el called **`System Calls`**
- Examples include, allocating memory by using variables or opening a file.

  ![user-space](../../images/user-space.PNG)

- For example, opening a file such as the **`/etc/os-release`** to see the ope
rating system installed, results in a **`system call`**

  ![user-space1](../../images/user-space1.PNG)

# Working with Hardware

- Take me to the [Video Tutorial]
(https://kodekloud.com/courses/873064/lectures/17080373)
In this section, we will look at how linux works with the hardware resources a
vailable to the system and how to make use of kernel modules
- We will look at how linux identifies and manages hardware devices attached t
o the system
- We will then see ways to list and get detailed information about these devic
es from the command line.

Lets take an example of **`USB Disk`** be used in the system.
- As soon as the **`USB device`** is attached to the system a corresponding de
vice driver which is part of the kernel space detects the stage change and gen
erates an event. 
- This event which is called **`uevents`** is then sent to the **`User Space`*
* device manager daemon called **`udev`**. 
- The **`udev`** service is then responsible for dynamically creating a device 
node associated with the newly attached USB drive in the **`/dev/`** filesyste
m. 
- Once the process is complete, the newly attached disk should be visible unde
r **`/dev/`** filesystem.

![working-with-hardware](../../images/working-with-hardware.PNG)

Use **`dmesg`** display messages from the area of kernel called **`Ring Buffer
`** . When a linux operating system boots up there were numerous messages gene
rated by the kernel that appear on the display screen. These messages also con
tain logs from the hardware devices that the kernel detects and provide good i
ndication wheather it is able to configure
```
$ dmesg
$ dmesg | grep -i usb
```

The **`udevadm`** is the management utility for udev which queries the databas
e for device information.
```
$ udevadm info --query=path --name=/dev/sda5
```

The **`udevadm monitor`** listens to the kernel new **`uevents`** upon detecti
ng an event, it prints the details such as the **`device path`** and the **`de
vice name`** on the screen. This command is handy to determine the details of 
the newly attached or removed device.
```
$ udevadm monitor
```

To list all PCI (Peripheral Component Interconnect) devices that are configure
d in the system. Examples of PCI devices are **`Ethernet Cards`**, **`RAID Con
trollers`**, **`Video Cards`** and **`wireless Adaptors`** that directly attac
hed to PCI slots in the motherboard of the computer
```
$ lspci
```
   ![pci](../../images/pci.PNG)
   

To list information about **`Block Devices`**
```
$ lsblk
```
   ![block-device](../../images/block-device.PNG)
   

To display detail information about the **`CPU`** such as CPU architecture, cp
u op-modes (32 bit, 64 bit) etc.
```
$ lscpu
```

To list available memory in the system. 
```
$ lsmem --summary
```

Another alternate command to see the information about the memory. This comman
d will list total used and free memory.
```
$ free -m
```

To extract detail information about the entire hardware information of the mac
hine
```
$ lshw
```

#### To run commands with root privileges. Not every user can run all the comm
ands in the linux system some commands need to be run as the `root` or the `su
per-user`. Use **`sudo`** followed by <command> ( input the sudo password ).

```
$ sudo lshw
```
# Lab - Linux Kernel

- Access Hands-On Labs here [Hands-On Labs]
(https://kodekloud.com/courses/873064/lectures/17074365)

To check the exact kernel version that is running in this system. 
```
$ uname -r
```

what is the kernel version in 4.15.0-88-generic?
```
Look for the first digit. In this case, it is 15
```

What is the major version number of the kernel 4.15.0-88-generic
```
Look for the second digit after the kernel version separated by a . In this ca
se, it is 15
```

Which command would you run to print the messages generated by the kernel?
```
Type the command dmesg to see the messages.
$ dmesg
```

To list/count all block devices of type disk that are present in the system
```
Run: lsblk and count the number of disk devices.
$ lsblk
```

To check total number of **`physical cores`** in the system.
```
Run lscpu and multiply the Core(s) per socket with the number of Socket(s):
$ lscpu
```

To check total online memory
```
Run the lsmem command and look for the value of online memory
$ lsmem
```
# Linux Boot Sequence

- Take me to the [Video Tutorial]
(https://kodekloud.com/courses/873064/lectures/17074372)

In this section, we look at the boot process in a simplied manner by dividing 
it into four broader steps.
- The boot process can be broken down into four stages
  1. BIOS POST
  1. Boot Loader (GRUB2)
  1. Kernel Initialization
  1. INIT Process
  
  ![boot-sequence](../../images/boot-sequence.PNG)
  
 #### How to initiate a linux boot process?
  - This can be achieved in one of the two ways.
    - The first method is to start a linux device which is in a halted or stop
ped state 
    - Second method is to reboot or reset a running system
    
 #### BIOS POST
 
 - The first stage, called **`BIOS POST`** has very little to do with linux it
self.
 - **`POST`** Stands for **`Power On Self Test`**.
 - In this stage, BIOS runs a POST test, to ensure the hardware components tha
t are attached to the device are functioning correctly, if POST fails the comp
uter may not be operable and the system will not be proceed to next stage of t
he boot process
 
 ![BIOS](../../images/BIOS.PNG)
 
 #### Boot Loader
 - The next stage after BIOS POST is **`Boot Loader`** after successful of POS
T test.
 - BIOS loads and executes the boot code from the boot device, which is locate
d in the first sector of the harddisk. In Linux this is located in the **`/boo
t`** file system.
 - The boot loader will provide the user with the boot screen, often with mult
iple options to boot into. Such as Microsoft windows O.S or Ubuntu 18.04 O.S i
n an example of a dual boot system.
 - Once the selection is made at the boot screen, boot laoder loads the kernel 
into the memory supplies it with some parameters and handsover the control to 
kernel
 - A popular example of the boot loader is **`GRUB2`** (GRand Unified Bootload
er Version 2). Its a primary boot loader now for most of the operating system.
 
 ![boot-loader](../../images/boot-loader.PNG)
 
 #### Kernel Initialization
 - After the selected kerenl is selected and loads into the memory, it usually 
decompress and then loads kernel into the memory.
 - At this stage, kernel carries out tasks such as initializing hardware and m
emory management tasks among other things.
 - Once it is completely operational , kernel looks for **`INIT Process`** to 
run. Which sets up the **`User Space`** and the process is needed for the envi
ronment.
 
 ![kernel-initialize](../../images/kernel-initialize.PNG)
 
 #### INIT Process
 
 - In most of the current day linux distribution, the **`INIT`** function then 
calls the **`systemd`** daemon.
 - The **`systemd`** is responsible for bringing the linux host to usable stat
e.
 - **`systemd`** is responsible for mounting the file systems, starting and ma
naging system services.
 - **`systemd`** is the universal standard these days, but not too  long ago a
nother initialization process called **`system V (five) init`** was used. It i
s also called **`Sys5`
   - For example these were used in **`RHEL 6`** or **`CentOS 6`** distributio
n
 - Once of the key advantages of using **`systemd`** over **`system V(five) in
it`**  is that it reduces the system startup time by parallelizing the startup 
of services.
 
 To check the **`init`** system used run **`ls -l /sbin/init`**, if it is syst
emd then you will see a pointer to **`/lib/systemd/systemd`**
 ```
 $ ls -l /sbin/init
 ```
 

# Run Levels

- Take me to the [Video Tutorial]
(https://kodekloud.com/courses/873064/lectures/17074377)

## Systemd Targets (Run Levels)
We can setup the server to boot either into graphical mode or non-graphical mo
de. Linux can run in multiple modes and these modes are set by something calle
d **`runlevel`**
- The operation mode which provide a graphical interface is called **`runlevel 
5`**
- The operation mode which provide a non-graphical mode is called **`runlevel 
3`**

   ![run-levels](../../images/run-levels.PNG)

To see the operation mode run in the system. Run the command **`runlevel`** fr
om the terminal
```
$ runlevel
```

During boot, the **`init`** process checks the **`runlevel`**, it make sure th
at all programs need to get the system operation in that mode are started.
  - For example: The **`Graphical User`** mode requires a **`display manager`*
* service to run for the GUI to work, however this service is not required for 
the **`non-graphical mode`**

    ![run-levels1](../../images/run-levels1.PNG)

In the boot process section, we saw that the **`systemd`** is used as the **`i
nit`** process in most new linux distributions suchs as **`Ubuntu 18.04`**.
- In **`systemd`**, runlevels are called as **`targets`**.
  - The RunLevel 5 is called as the **`graphical target`** 
  - The Runlevel 3 is called as the **`multiuser target`**
  
    ![run-levels2](../../images/run-levels2.PNG)

#### Now that we are familiar with runlevels in systemd target unit. Lets now 
take a look at how we change these values from a shell.

To see the default target, run the command **`systemctl get-default`**. This c
ommand looks at the file located at **`/etc/systemd/system/default.target`** 
```
$ systemctl get-default
```

To change the default target, we can make use of **`systemctl set-target <desi
red target name goes here as an argument>`**
```
$ systemctl set-default multi-user.target 
```
# File Types in Linux

- Take me to the [Video Tutorial]
(https://kodekloud.com/courses/873064/lectures/17074379)

In this section, we will take a look at different types of files in linux.
- Everything is a file in Linux. 
  - Every object in linux can be considered to be a type of file, even a direc
tory for example is a special type of file.

There are three types of files.
1. Regular File
1. Directory
1. Special Files

![file-types](../../images/file-types.PNG)

**`Special files`** are again catagorized into five other file types.
1. Character Files
   - These files represent devices under the **`/dev`** file system.
   - Examples include the devices such as the **`keyboard`** and **`mouse`**.
1. Block Files
   - These files represent block devices also located under **`/dev/`** file s
ystem.
   - Examples include the **`harddisks`** and **`RAM`**
1. Links
   - Links in linux is a way to associate two or more file names to the same s
et of file data.
   - There are two types of links
     - The Hard Link 
     - The Soft Link
1. Sockets
   - A sockets is a special file that enables the communication between two pr
ocesses.
1. Named Pipes
   - The Named Pipes is a special type of file that allows connecting one proc
ess as an input to another  
   
     ![file-types1](../../images/file-types1.PNG)
     
#### Let us now see how to identify different file types in Linux.
 
One way to identify a file type is by making use of the **`file`** command. 
```
$ file /home/michael
$ flle bash-script.sh
$ file insync1000.sock
$ file /home/michael/bash-script
```

Another way to identify a file type is by making use of the **`ls -ld`** comma
nd
```
ls -ld /home/michael
ls -l basg-script.sh
```
   ![file-types2](../../images/file-types2.PNG)

# Filesystem Hierarchy

- Take me to the [Video Tutorial]
(https://kodekloud.com/courses/873064/lectures/17074387)

In this section, lets take a look at the **`filesystem hierarchy`**
- Linux uses  single rooted, inverted tree like file system
  - **`/home`**  : It is the location that contains the home directories for a
ll users, except the **`root`** user (root user home directory is located at *
*`/root`**)
  - **`/opt`**   : If you want to install any third party programs put them in 
the **`/opt`** filesystem.
  - **`/mnt`**   : It is the default mount point for any partition and it is e
mpty by default. It is used to mount filesystems temporarly in the system
  - **`/tmp`**   : It is used to store temporary data
  - **`/media`** : All external media is mounted on **`/media`**
  - **`/dev`**   : Contains the special block and character device files
  - **`/bin`**   : The basic programs such as binaries **`cp`**, **`mv`**, **`
mkdir`** are located in the **`/bin`** directory
  - **`/etc`**   : It stores most of the configuration files in Linux.
  - **`/lib`**   : The directory **`/lib`** and **`/lib64`** is the place to l
ook for shared libraries to be imported into your program
  - **`/usr`**   : In older systems, **`/usr`** directory is used for **`User 
Home Directories`**, however in the modern linux operating systems it is the l
ocation where all user land applciations in their data reside
  - **`/var`**   : It contains variable data like mails, log files
  
      ![filesystem](../../images/filesystem.PNG)
      
 To print all the mounted filesystems, run **`df`** (disk filesystem) command
 ```
 $ df -hP
 ```
 
 

# Lab - Linux Runlevels and Filesystem Hierarchy 
     
- Access Hands-On Labs here [Hands-On Labs]
(https://kodekloud.com/courses/873064/lectures/17074394)

To run commands that need **`sudo`**(super-user) privilages. Run **`sudo`**
```
$ sudo ls /root
```

To check the **`init process`** (systemd or sysV) used by the system
```
$ sudo ls -l /sbin/init
```

To check **`default systemd target`** (eg. graphical.target or multi-
user.target) set in the system
```
$ sudo systemctl get-default
```

To change the systemd target to **`multi-user.target`**
```
$ sudo systemctl set-default multi-user.target
```

To check what type of file is **`firefox.deb`** which is located at /root
```
$ sudo file /root/firefox.deb
```

To check what type of file is **`sample_script.sh`** which is located at /root
```
$ sudo file /root/sample_script.sh
```

You were asked to install a new **`third-party IDE`** in the system. Which dir
ectory  is the recommended choice for the installation?
```
Third-party software is usually installed under **`/opt`**
```

Which directory contains the files related to the block devices that can be se
en when running the **`lsblk`** command?
```
Block Device or Device Node files are located under **`/dev`** directory
```

What is the name of the **`vendor`** for the **`Ethernet Controller`** used in 
this system?
```
Use: sudo lshw and lookup the vendor for Ethernet Controller under the network 
section.   
     $ sudo lshw
```

# Package Management Distribution

- Take me to the [Video Tutorial]
(https://kodekloud.com/courses/873064/lectures/17074407)

In this section, we will take a look at the Linux Package Management tools use
d in different linux distribution
- Will start with introduction to the package management.

## Introduction to Package Managers

For **`Debain/Ubuntu`**, it is **`apt/dpkg`** and for CentOs/Redhat, it is **`
RPM`**

![package-managers](../../images/package-managers.PNG)

**Question** : What is the difference between **`CentOS`**, **`RHEL`** and **`
Ubuntu`***?
- There are hundreds of Linux distributions in use today

One of the common ways to catagorize linux distribution is by the package mana
ger it uses.
- For example: Distributions such as **`RHEL`**, **`Fedora`** and **`CentOS`**
. are based on RPM. Hence they are known as **`RPM`** based distribution. The 
**`Debian`** family including **`Ubuntu`**, **`Debian`** and **`Linux Mint`** 
e.t.c. make use of **`Debian`** based package managers such as the **`DPKG`**. 

![deb-rpm](../../images/deb-rpm.PNG)

#### Now, Lets compare **`RHEL`** and **`CentOS`** Operating Systems.

![rhel-centos](../../images/rhel-centos.PNG)

#### What is a package?
- A package in its simplest defination is a compressed archieve that contains 
all the files that are required by a particular software to run.
- For example: Lets consider an Ubuntu System, we want to install a simple edi
ting system such as **`gimp`** which stands for **` GNU Image Manipulation Sys
tem`**. To do this, we can make use of the **`gimp.deb`** package which contai
ns all the software binaries and files needed to for the image editor to run a
long with the metadata which provides the information about the software itsel
f.

![package](../../images/package.PNG)

#### Thats seems to be a quite easy process, why don't we do all the time? dow
nload a package and install it on a linux servers. Wondering the need of packa
ge managers?
- There are hundreds of linux distributions are there, these distributions run
s different sets of tools and libraries, software and possibly even different 
linux kernels as a result of this a linux program may not run the same way fro
m one system to another. To fix this problem packages include a manifest of de
pendencies or list of programs in versions that must be satified for the packa
ge software to run correctly on a given computer.
- Take a look at the errors in the installation while attempting to install **
`gimp.deb`** on this ubuntu 18.04 system, the dependencies failed as a result 
the installations failed. Bare in mind that each of these dependent packages m
ay have dependencies of their own which makes package installation management 
a very tedious process. This is where a **`Package Manager`** comes into save 
the day.

  ![package-errors](../../images/package-errors.PNG)
  
#### A package manager is a software in a linux system that provides the consi
stent and automated process in installing, upgrading, configuring and removing 
packages from the operating system.

![pkg-mgr](../../images/pkg-mgr.PNG)

## Functions of Package Manager

![functions-of-pkg](../../images/functions-of-pkg.PNG)

## Types of Package Managers

A Linux distribution supports different types of package managers, some of the 
common ones are below

![types-of-pkg](../../images/types-of-pkg.PNG)

# RPM and YUM Package Managers

- Take me to the [Video Tutorial]
(https://kodekloud.com/courses/873064/lectures/17074421)
In this section, we will take a look at **`RPM`** and **`YUM`** package manage
rs in detail.
- RPM
- YUM

## RPM (Redhat Package Manager)

This package manager is used in RHEL as well as other linux distributions but 
these are the most common ones. The File extensions for packages manage by RPM 
is **`.RPM`**

![rpm](../../images/rpm.PNG)

#### Working with RPM

RPM has five basic modes of operations. Each of these modes can be run using *
*`rpm`** command followed by a specific command **`options`**. Despite of this
, RPM doesn't resolve dependencies on its own. This is why we make use of a hi
gher level of package manager called **`YUM`**.
1. Installing
1. Uninstalling
1. Upgrade
1. Query
1. Verfiying

   ![rpm-modes](../../images/rpm-modes.PNG)

## YUM (Yellowdog Updater Modifier)

YUM is a free and opensource package manager.
- Works on RPM based Linux systems
- Works with Software repositories which are essentially a collection of packa
ges and provides package independency management on RPM based distro. The repo
sitory information is stored in **`/etc/yum.repos.d/`** and repository files w
ill have the **`.repo`** extension.
- Acts as a high level package manager but under the hood it still depeneds on 
**`RPM`** to manage packages on the linux systems.
- Unlike RPM, YUM handles package dependencies very well (Automatic Dependency 
Resolution). It is able to install any dependencies packages to get the base p
ackage install on the linux system.

  ![yum](../../images/yum.PNG)
  
#### Let us see how YUM installs a package.

![yum-repo](../../images/yum-repo.PNG)
#### Now, lets take a look at sequence of steps envolve while installing the p
ackage.
- Once yum runs **`yum install`** command is issued YUM first runs transaction 
check, if the package is not installed in the system yum checks the configured 
repositories under **`/etc/yum.repos.d/`** for the availability of the request
ed package. 
- It also checks if there are any dependent packages are already installed in 
the system or if it needs to be upgrade.

  ![yum-cmd](../../images/yum-cmd.PNG)
  
- After this step, transaction summary is displayed on the screen for the user 
to review, if we wish to proceed with the install enter the **`y`** button (th
is step can be skipped by providing the **`-y`** flag with the **`yum install
`** command).
- Yum will download and install necessary RPMs to linux system

  ![yum-cmd1](../../images/yum-cmd1.PNG)
  

If you want to update a single package, use **`yum update`** command. If the p
ackage is already in the latest version in the repository and hence no action 
will be taken

![yum-update](../../images/yum-update.PNG)

#### Common Commands

To list all the repos added to your system. Run **`yum repolist`**
```
$ yum repolist
```

To check which package should be installed for specific command to work. Use *
*`yum provides`** command followed by <command> name.
```
$ yum provides scp
```

To Install a package
```
$ yum install httpd
```

To Install a package to automatically answer "yes" to any question prompt duri
ng the operation. Use **`-y`** flag with the **`yum install`** command.
```
$ yum install httpd -y
```

To remove a package
```
$ yum remove httpd
```

To update a package
```
$ yum update telnet
```

To update all packages in the system, use the **`yum update`** command without 
any arguments.
```
$ yum update
```

  

# Lab - RPM and YUM

- Access Hands-On Labs here [Hands-On Labs]
(https://kodekloud.com/courses/873064/lectures/17080533)

Which package managers would you use on centos machine
```
Centos makes use of RPM and YUM
```

Use an **`rpm`** command and find out the exact package name for **`wget`** in
stalled in this server
```
$ rpm -qa |grep wget
```

To install a package for **`firefox`** browser that has been downloaded under 
**`/home/bob`** in the system. Caution: It might fail due to failed dependenci
es
```
$ sudo rpm -ivh /home/bob/firefox-68.6.0-1.el7.centos.x86_64.rpm
```
To install a package for **`firefox`** browser along with its dependencies
```
$ sudo yum install firefox -y
```

To check how many software repositories are configured for YUM in the system
```
$ sudo yum repolist
```

To check which package provides **`tcpdump`**  command
```
$ sudo yum provides tcpdump
```

# DPKG and APT Package Managers

- Take me to the [Video Tutorial]
(https://kodekloud.com/courses/873064/lectures/17074424)

In this section, we will look at debian package managers for distributions lik
e **`Ubuntu`**, **`Debian`** and **`PureOS`**.
- DPKG
- APT

## DPKG Utility

- DPKG stands for Debian Package Manager
- It is a low level package manager

![dpkg](../../images/dpkg.PNG)

#### Working with DPKG

Similar to RPM, DPKG can be used for the below. The package extension is .deb.
1. Installing
1. Uninstalling
1. Upgrade
1. List
1. Status
1. Verfiying

   ![dpkg-modes](../../images/dpkg-modes.PNG)
   
## APT and APT-GET
Similar to RPM, DPKG doesnt resolve the dependencies when it comes to package 
management.
- Install may fail due to dependencies issues. This is the reason why we use h
igher level debian package managers such as **`APT`** and **`APT-GET`**.
  
  ![dpkg-fail](../../images/dpkg-fail.PNG)
  
- Instead of relying on DPKG, you can install software along with its dependen
cies using **`APT`** or **`APT-GET`**.
- **`APT`** or **`APT-GET`** although sounds similar, but they do not depend o
n each other.
- **`APT`** stands for advanced package managers, it is more user friendly and 
overall better tool compared to **`APT-GET`**.
  ```
  $sudo apt install gimp
  $sudo apt-get install gimp
  ```

- APT act as a frontend package manager that relies on DPKG utility. In simila
r to YUM, APT relies on software repository that contains packages that would 
eventually be installed on a system.
- The software repository for APT is defined in **`/etc/apt/sources.list`**  f
ile.

  ![apt](../../images/apt.PNG)
  
#### Let us know see some common commands

To refresh a repository. Run **`apt update`** command.
```
$ sudo apt update
```

To install available upgrades of all packages currently installed on the syste
m from the sources configured.
```
$ sudo apt upgrade
```

Another way to update the repository is to use **`apt edit-sources`** command. 
This opens up the **`/etc/apt/sources.list`** file in the text editor of your 
choice.
```
$ sudo apt edit-sources
```

To install the package
```
$ sudo apt install telnet
```

To remove the package
```
$ sudo apt remove telnet
```

To search or look for a package in the repository.
```
$ sudo apt search telnet 
```

To list all the available packages 
```
$ sudo apt list |grep telnet
```

# APT vs APT-GET

- Take me to the [Video Tutorial]
(https://kodekloud.com/courses/873064/lectures/17074428)

#### Difference between APT vs APT-GET
- APT is a more user friendly tool when compared to APT-GET
- In all the latest debian based distros APT is already installed by default.

#### Lets take a look why **`APT`** is better when compare to **`APT-GET`**

Lets try to install **`firefox`** package using both APT and APT-GET
- You will notice APT does easy on the eyes, you get just enough information a
nd also a nice little progress bar
- APT-GET is just effective and doesn't provide the output in user-friendly fo
rmat.

  ![apt-vs-apt-get](../../images/apt-vs-apt-get.PNG)
 
Lets try another comparision by search a **`telent`** package.
- You will notice with apt, all its options are located in one place. You can 
search with **`apt search telnet`** command.
- On the other hand, you cannot use search command with **`apt-get`** command. 
Instead, you have to use another tool called **`apt-cache search telnet`**.
- If you compare the results of the two commands, you will also see the **`apt
-cache`** throws in a lot of extra information in the search result, which may 
not be really useful for the end user.
  ![apt-vs-apt-get1](../../images/apt-vs-apt-get1.PNG)
 

# Lab - DPKG and APT

- Access Hands-On Labs here [Hands-On Labs]
(https://kodekloud.com/courses/873064/lectures/17074429)

Package managers that you use on a debian based distro
```
Debain distros use dpkg.
```

To install a package for **`firefox`** browser which has been downloaded at /r
oot/firefox.deb. The dependencies might fail.
```
$ sudo dpkg -i /root/firefox.deb
```

To install a package using **`APT`**
```
$ sudo apt install firefox
```

Lets now locate the package to install Chromium browser in the system. Use **`
apt search`** functionality to locate the correct package name. The browser ha
s the description of: Chromium web browser, open-source version of Chrome
```
$ sudo apt search chromium-browser
```

To install the **`chromium-browser`**
```
sudo apt install -y chromium-browser
```

To remove the **`firefox`** browser from the system.
```
$ sudo apt remove firefox
```

# Behind Schedule (Story)

- Take me to the [Video Tutorial]
(https://kodekloud.com/courses/873064/lectures/17080747)

# File Compression and Archival
- Take me to the [Video Tutorial]
(https://kodekloud.com/courses/873064/lectures/17080556)

In this section, we will take a look to compress and archive files
- File Compression and Archival

## Viewing file sizes

The **`du`** command, which stands for **`disk usage`** is a popular command t
o inspect the size of the file.
- **`du`** with **`-sk`** shows the size of a file or directory in *
*`Kilobytes`**
  ```
  $ du -sk test.img
  ```  
  
- **`du`** with **`-sh`** shows the size of a file or directory in **`human re
adable format`**
  ```
  $ du -sh test.img
  ```
  
- we can also use **`long list`** , **`ls -lh`** to print the size of the file
.
  ```
  $ ls -lh test.img
  ```
  
## Archiving Files

Let us know take a look at widely used utility called **`tar`** 
- **`tar`** is used to group multiple files and directories into a single file
. Hence it is specially used for archiving data.
- tar is an abrevation for **`tape archive`**.
- Files created with tar are often called **`tarballs`**.

To archive a file or directory. Use **`tar`** command followed by **`-c`** to 
create an archive and the **`-f`** is used to specify the name of the tar file 
to be created. These is followed by files or directories to be archive.
```
$ tar -cf test.tar file1 file2 file3 
$ ls -ltr test.tar
```

The **`tar`** command followed by **`-tf`** option followed by the tar filenam
e is used to see the contents of the tarball.
```
$ tar -tf test.tar
```

The **`tar`** command followed by **`-xf`** option followed by the tar filenam
e is used to extract the contents from the tarball.
```
$ tar -xf test.tar
```

The **`tar`** command followed by **`-zcf`** option is used to compress the ta
rball to reduce its size.
```
$ tar -zcf test.tar
```

## Compression

Compression is the technique used to reduce the size consumed by a file or a d
ataset.
- To reduce the size of a file or directory in the linux file system, there ar
e commands specificly used for compression. 
- Let us now look at the three popular ones
  - bzip2 (.bz2 extension)
  - gzip (.gz extension)
  - xz (.xz extension)
    
    ```
    $ bzip2 test.img
    $ gzip test1.img
    $ xz test2.img
    ```
  
#### The space of the compressed files created by these three commands depends 
on a few factors, such as the type of data being compressed, the other factors 
that effect the size are the compression algorithm used by these commands and 
the compression level used.

- The compressed files can be uncompressed by using the below commands
  - bunzip2
  - gunzip
  - unxz
    ```
    $ bunzip2 test.img
    $ gunzip test1.img
    $ unxz test2.img
    ```
  
     ![compress-uncompress](../../images/compress-uncompress.PNG)
    
#### Compressed files need not to be uncompressed everytime
- Tools such as **`zcat`** , **`bzcat`** and **`xzcat`** allow the compressed 
files to be read without an uncompress
  ```
  $ zcat hostfile.txt.bz2
  $ zcat hostfile.txt.gz
  $ zcat hostfile.txt.xz
  ```
     ![compress-cat](../../images/compress-cat.PNG)

# Searching for files and Patterns

- Take me to the [Video Tutorial]
(https://kodekloud.com/courses/873064/lectures/17080595)

In this section, we will take a look at how to locate a file or directory in t
he filesystem.
- locate
- find
- grep

## locate
Lets say you want to find the files with the name **`City.txt`**. Easiest way 
to do this is to make use of **`locate`** command.
- Run **`locate`** command followed by the filename you are searching as an ar
gument. This should return all paths matching the pattern.
  ```
  $ locate City.txt
  ```

- The downside of the locate command is it depends on a database called **`mlo
cate.db`** for querying the filename.
- If you have just installed linux or if the file you are trying to locate was 
created recently. The locate command may not give you useful results. This is 
because it is possible that the DB is not been updated yet.
- To manually update the DB, run the command **`updatedb`** and then run the l
ocate command again
  ```
  $ sudo updatedb
  ```
- Please note that the **`updatedb`** command needs to be run as root user to 
work.

## find
Another way to do this is make use of the **`find`** command. Use the find com
mand followed by the directory under which you want to search. To search file 
by a name use the **`-name`** option followed by the name of the file.
```
$ find /home/michael -name City.txt
```
   ![locate-find](../../images/locate-find.PNG)
   
## Grep

To search within files, the most popular command in linux is grep. 
- Grep is commonly used to print lines of a file matching a pattern but it als
o offers a variety of other options as well.
- The grep command is case-sensitive  

To search for the word **`second`** from the **`sample.txt`**
```
$ grep second sample.txt
```

To search for the word **`capital`** with **`case-insensitive`** use **`-i`** 
flag.
```
$ grep -i capital sample.txt
```

To search for a pattern recursively.
```
$ grep -r "thrid Line" /home/michael
```

To print the lines that don't matches the pattern
```
$ grep -v "printed" sample.txt
```

  ![grep](../../images/grep.PNG)
  
#### What if you want to match a pattern that form a whole word?

To search for the whole word called **`exam`**. Use **`grep`** followed by **`
-w`** flag  
```
$ grep -w exam examples.txt
```
You can also combine multiple options together. For example, to reverse the se
arch and print all lines of the same file that doesn't match the whole word ex
am. Use **`grep -vw`** 
```
$ grep -vw exam examples.txt
```

To print the number of lines after and before matching a pattern. Use **`grep`
** command with **`-A`** and **`-B`** flags respectively.
```
$ grep -A1 Arsenal premier-league-table.txt
$ grep -B1 4 premier-league-table.txt
```

   ![grep1](../../images/grep1.PNG)

Finally, the **`-A`** and **`-B`** can be combined into one single search.
```
$ grep -A1 -B1 Chelsea premier-league-table.txt
```
  ![grep2](../../images/grep2.PNG)
   

  

# IO Redirection

- Take me to the [Video Tutorial]
(https://kodekloud.com/courses/873064/lectures/17080597)

In this section, we will take a look at IO **`Redirection`**.
- IO Redirection
- Standard Streams in Linux

There are three data streams created when you launch a linux commnad.
- Standard Input (STDIN)
  - STDIN is the standard input stream which accepts text as an input.
- Standard Output (STDOUT)
  - Text output is delivered as STDOUT or the standard out stream
- Standard ERROR (STDERR)
  - Error messages of the command are sent through the standard ERROR stream (
STDERR)
  
  ![io](../../images/io.PNG)
  
With IO Redirection, the STDIN, STDOUT and STDERR can be redirected to a text 
file.

## REDIRECT STDOUT

To redirect STDOUT to a file instead of printing it on the screen.
```
$ echo $SHELL > shell.txt
```

To append STDOUT to an exisiting file
```
$ echo $SHELL >> shell.txt
```

## REDIRECT STDERR

To redirect just the ERROR message we need to use **`2`** followed by forward 
arrow **`>`** symbol and then the name of the filename in which the errors are 
written.
```
$ cat missing_file 2> error.txt
```

To append the STDERR to the exisiting file
```
$ cat missing_file 2>> error.txt
```

If you want to execute and not print ERROR messages on the screen even if it g
enerates a standard ERROR. You can redirect to **`/dev/null`** 
```
$ cat missing_file 2> /dev/null
```

## Command Line Pipes

Command Line Pipes allow the linking of multiple commands.
- In simple terms, pipes allows the first commands standard output to be used 
as the standard input for the second command.
- The pipes are defined using vertical bar symbol (|).

  ```
  $ grep Hello sample.txt | less 
  ```
    ![pipe](../../images/pipe.PNG)
    
Another command to work with STDIN and STDOUT is the **`tee`** command.
- Instead of the redirect operator, we can use the command line pipe **`(|)`** 
followed by **`tee`** command.
  ```
  $ echo $SHELL | tee shell.txt
  ```
     
 - Use **`tee`** with -a option, to append instead of overwritting it
   ```
   $ echo "This is the bash shell" | tee -a
   ```
   
      ![tee](../../images/tee.PNG)
  

# Lab - Working With Shell Part - II

- Access Hands-On Labs here [Hands-On Labs]
(https://kodekloud.com/courses/873064/lectures/17080558)

Create a tarball of the directory called **`python`** and compress it using **
`gzip`**. The compressed tar file should be available at **`/home/bob/python.t
ar.gz`**
```
$ tar -cf /home/bob/python.tar /home/bob/reptile/snake/python
$ gzip /home/bob/python.tar
```

There is a compressed file called eaglet.dat.gz located under the eagle direct
ory. Extract it in the same location
```
$ gunzip /home/bob/birds/eagle/eaglet.dat.gz
```

A file has been copied to the laptop by the name of caleston-code. But he does 
not remember which directory he saved it in.Can you find it?
```
$ sudo find / -name caleston-code
```

Find the location of the file called **`dummy.service`** and redirect its abso
lute path to the file **`/home/bob/dummy-service`**. You can use the redirect 
operator with the echo command to save the answer to the file.
```
$ sudo find / -name dummy.service
$ echo /etc/systemd/system/dummy.service > /home/bob/dummy-service 
```
Find the file under **`/etc`** directory that contains the string **`172.16.23
8.197`**. Save the answer using the absolute path in the file **`/home/bob/ip*
*`
```
$ sudo grep -ir 172.16.238.197 /etc/ > /home/bob/ip
```

Create a new file called **`/home/bob/file_wth_data.txt`**. This file should h
ave one line of text that says **`a file in my home directory`**. Make use of 
the redirect operator.
```
$ echo "a file in my home directory" > /home/bob/file_wth_data.txt
```

Run the command python3 **`/home/bob/my_python_test.py`** and redirect the **`
standard error`** to the file **`/home/bob/py_error.txt`**.
```
$ python3 /home/bob/my_python_test.py 2>/home/bob/py_error.txt
```

Read the file **`/usr/share/man/man1/tail.1.gz`** and without extracting it co
py the first line of this file to **`/home/bob/pipes`**
```
$ zcat /usr/share/man/man1/tail.1.gz | head -1 > /home/bob/pipes
```

# Vi Editor

- Take me to the [Video Tutorial]
(https://kodekloud.com/courses/873064/lectures/17080600)

In this section, we will take a look at console based text editors in linux.
- It is not feasible using **`cat`** when dealing with large amounts of text o
r for writing code. This is why we use text editors

## Text Editor

There are several options available, we will be focusing on the **`VI Editor`*
*.
- Most popular text editor in linux is the **`VI`** Editor.
- The VI EDITOR is available in all most all of the linux distribution out of 
the box. 
- The command to open the vi editor is **`vi`** followed by the filename that 
you want to create or append.
  ```
  $ vi /home/michael/sample.txt
  ```
- The VI EDITOR has three operation modes.
  1. Command Mode
     - When the vi editor opens a file, it always goes to the **`COMMAND MODE`
** first.
     - In this mode, the editor only understands the commands
  1. Insert Mode
     - To switch from command mode to **`INSERT MODE`** type lower case **`i`*
*
     - This mode allows you to write text into the file.
     - Once you are done with editing the file, to go back to command mode hit 
the **`ESC`** button.
     - While going into insert mode from command mode you may use other option
s such as **`I`**, **`o`**, **`O`**, **`a`**, or **`A`**
  1. Last Line Mode
     - Pressing the **`:`** key will take you to the **`LAST LINE MODE`** 
     - In this mode you can choose to save changes to the file, discard change
s, or save and edit.
     - From the last line mode hit the **`ESC`** key to go back to the command 
mode.
     
     ![vi](../../images/vi.PNG)
     
 ## Command Mode
   
   ![command1](../../images/command1.PNG)
   
   ![command2](../../images/command2.PNG)
   
   ![command3](../../images/command3.PNG)
   
   
 ## Insert Mode

   ![insert](../../images/insert.PNG)
    
 ## Last Line Mode
 
   ![lastline](../../images/lastline.PNG)
    
 
 #### There is another popular editor called **`VIM`** which is an improved ve
rsion of **`VI`** with added features but very similar in appereance to VI.
 
 - In the most distros today, the VI is the symblic to the VIM editor
   
   ![VIM](../../images/VIM.PNG)
   

# Lab - VI Editor
- Access Hands-On Labs here [Hands-On Labs]
(https://kodekloud.com/courses/873064/lectures/17080603)

Go to **`insert mode`**
```
Press i
```

Exit from **`insert mode`** and go to **`command mode`**
```
Press ESC
```

To **`remove`** a character
```
Move Cursor to the characters to be removed and press x to remove them
```

Change the file contents to **`Welcome to KodeKloud`** and **`save`** file.
```
Go to insert mode by pressing i and delete all content and type in new content
. Once done press ESC key and go to command mode. Then type in command :w!
```

Update the port it listens on from **`80`** to **`5000`** in apache webserver.
```
Go to insert mode by pressing i and replace 80 with 5000 in line 10
```

Remove the line that starts with **`LogFormat`**.
```
Go to the line 33 and press dd (d twice) to remove the entire line.
```

To undo the previous change
```
Press u to undo previous change
```

There's a 6 hiding in the file. Find it.
```
find command /6
```

# Security Incident (story)
  Take me to the[Story]
(https://kodekloud.com/courses/873064/lectures/17074490)
# LINUX ACCOUNTS

  - Take me to the [Tutorial]
(https://kodekloud.com/courses/873064/lectures/17074499)
  - In this section we will take a look at basic access control in Linux.
  - We will also learn about about the file permissions. Lets Get Started!

    ![linux](../images/linux.PNG)

  #### User Accounts

  - User's informations are stored under **`/etc/passwd`** file.

    ```
    [~]$ cat /etc/passwd
    ```

  - Information about groups is stored into  **`/etc/group`** file.

    ```
    [~]$ cat /etc/group
    ```
   
    ![user](../images/user.PNG)
    
  - Each user has a username and a unique ID assigned to them known as user ID 
or UID.
  - The user also has a GID, the group id they are part of, **`id`** command c
an be use to check these details. for eg:

    ```
    [~]$ id michael
    uid=1001(michael) gid=1001(michael)groups=1001(michael),1003(developers)
    ```
  
  - More details about the user account can be found eg. default shell, home d
irectory using.

    ```
    [~]$ grep -i michael /etc/passwd
    michael:x:1001:1001::/home/michael:/bin/sh
    ```
   
    ![group](../images/group.PNG)

  - To see the list of users currently logged use **`who`** command.
    ```
    [~]$ who
    bob pts/2 Apr 28 06:48 (172.16.238.187)
    ```

  - The **`last`** command displays the record of all logged-in users along wi
th the date and time when the system was rebooted.

    ```
    [~]$ last
    michael :1 :1 Tue May 12 20:00 still logged in
    sarah :1 :1 Tue May 12 12:00 still running
    reboot system boot 5.3.0-758-gen Mon May 11 13:00 - 19:00 (06:00)
    ```

  #### Switching users

  - To switch to any user use **`su`** command.

    ```
    [~]$ su –
    Password:

    root ~#
    ```
 
  - To run a specific command you can use **`su -c "whoami"`** (This is not re
commended way)

    ```
    [michael@ubuntu-server ~]$ su -c "whoami"
    Password:
    root
    ```

  - To run a command as a root user **`sudo`** command is recommended.

    ```
    [michael@ubuntu-server ~]$ sudo apt-get install nginx
    [sudo] password for michael:
    ``` 
    
    ![who](../images/who.PNG)

  - Users listed in /etc/sudoers file can make use of sudo command for privled
ge escalation.
    ```
    [~]$ cat /etc/sudoers
    ```
    ![sudo](../images/sudo.PNG)

  - To restrict anyone from directly login as root login, this can be done by 
setting **`nologin`** shell.

    ```
    [~]$ grep -i ^root /etc/passwd
    /root:x:0:0:root:/root:/usr/sbin/nologin
    ```
    
# USER MANAGEMENT

  - Take me to the [Tutorial]
(https://kodekloud.com/courses/873064/lectures/17074501)
  - In this lecture we will learn how to create and manage user accounts in Li
nux.

  #### User Add

  - To create a new local user **`bob`** in the system use **`useradd`** comma
nd.

    ```
    [~]$ useradd bob
    ```

  - To get more details about **`bob`** account like, home director, uid, and 
shell use **`/etc/passwd`**

    ```
    [~]$ grep -i bob /etc/passwd
    bob:x:1002:1002::/home/bob:/bin/sh
    ```

    ![useradd](../images/useradd.PNG)
  
  - To check the uid or username of the user logged in user **`whoami`** comma
nd.

    ```
    [~]$ whoami
    bob
    ```

  - All user's password are store under **`/etc/shadow`**
    ```
    [~]$ grep -i bob /etc/shadow
    bob:!:18341:0:99999:7:::
    ```
 
  - To change the password of current user use **`passwd`** or for any specifi
c user use **`passwd <username>`** 

    ```
    [~]$ passwd bob
    Changing password for user bob.
    New UNIX password:
    Retype new UNIX password:
    passwd: all authentication tokens updated
    successfully.
    ```

  # Managing Users

  - **`useradd`** command be used along with many attributes as show below.

    ```
    [~]$ useradd -u 1009 -g 1009 -d /home/robert -s /bin/bash -c ”Mercury Proj
ect member" bob
    ```

    ![manage](../images/manage.PNG)
     
  - To delete a user use **`userdel`** command

    ```
    [~]$ userdel bob
    ```

  - To add a group use **`groupadd`** command 

    ```
    [~]$ groupadd –g 1011 developer
    ```

  - To delete a group user **`groupdel`** command

    ```
    [~]$ groupdel developer
    ``` 
# ACCESS CONTROL FILES
  - Take me to the [Tutorial]
(https://kodekloud.com/courses/873064/lectures/17074502)
  
  - Access Ccontrol files are stored under **`/etc`**.
  - Can be read by anyone and can be only edited by **`root`** user.

  ### Control files

  - To get more details about one's account for example **`bob`** account, hom
e director, uid, and shell check **`/etc/passwd`** 

    ```
    [~]$ grep -i ^bob /etc/passwd
    bob:x:1002:1002::/home/bob:/bin/sh
    USERNAME:PASSWORD:UID:GID:GECOS:HOMEDIR:SHELL
    ```
   
    ![passwd](../images/passwd.PNG)

  - Password are stored under **`/etc/shadow`**

    ```
    [~]$ grep -i ^bob /etc/shadow
    bob:$6$0h0utOtO$5JcuRxR7y72LLQk4Kdog7u09LsNFS0yZPkIC8pV9tgD0wXCHutY
    cWF/7.eJ3TfGfG0lj4JF63PyuPwKC18tJS.:18188:0:99999:7:::

    USERNAME:PASSWORD:LASTCHANGE:MINAGE:MAXAGE:WARN:INACTIVE:EXPDATE
    ```

    ![shadow](../images/shadow.PNG)

  - Check the groups **`bob`** belongs too

    ```
    [~]$ grep -i ^bob /etc/group
    NAME:PASSWORD:GID:MEMBERS
    ```

    ![egp](../images/egp.PNG)

# HANDS-ON LABS

  - Lets start with Managing and User Accounts [here]
(https://kodekloud.com/courses/the-linux-basics-course/lectures/17074503)
# LINUX FILE PERMISSIONS

  - Take me to the [Tutorial]
(https://kodekloud.com/courses/873064/lectures/17074504)
  
  - In this lecture we will learn about various file type identifiers.
  - We will also learn about various Linux file permissions that can be applie
d on the file or the directory.

    ![perm](../images/perm.PNG)

    ![type](../images/type.PNG)

  #### Directory Permission

  - To list the directory permission use

    ```
    [~]$ ls -ld /home/bob/random_dir
    ```

  - To know the current user 

    ```
    [~]$ whoami
    ```
 
  - To change the change the directory

    ```
    [~]$ cd /home/bob/random_dir
    ```

  #### File Permissions

  - Linux file permissions are defined as 

    ![filep](../images/filep.PNG)

  #### Modifying file permissions

  - Use **`chmod`** command to modify the file permissions.

  - Provide full access to owners

    ```
    [~]$ chmod u+rwx test-file
    ```

  - Provide Read access to Owners, groups and others, Remove execute access
    ```
    [~]$ chmod ugo+r-x test-file
    ```

  - Remove all access for others

     ```
     [~]$ chmod o-rwx test-file
     ```

  - Full access for Owner, add read , remove execute for group and no access f
or others

    ```
    [~]$ chmod u+rwx,g+r-x,o-rwx test-file
    ```
 
  - Provide full access to Owners, group and others

    ```
    [~]$ chmod 777 test-file
    ```

  - Provide Read and execute access to Owners,groups and others

    ```
    [~]$ chmod 777 test-file
    ```

  - Read and Write access for Owner and Group, No access for others.

    ```
    [~]$ chmod 660 test-file
    ```

  - Full access for Owner, read and execute for group and no access for others
.

    ```
    [~]$ chmod 750 test-file
    ```

  #### Change Ownership 
   
  - Changes owner to bob and group to developer
   
    ```
    [~]$ chown bob:developer test-file
    ```
    
  - Changes just the owner of the file to bob. Group unchanged.

    ```
    [~]$ chown bob andoid.apk
    ```

  - Change the group for the test-file to the group called android. 

    ```
    [~]$ chgrp android test-file
    ```

# HANDS-ON LABS

  - Lets do some hands on labs to understand File Permission better. [Take me 
to Labs](https://kodekloud.com/courses/873064/lectures/17074516)
# SSH and SCP

  - Take me to the [Tutorial]
(https://kodekloud.com/courses/873064/lectures/17074517)
  - In this lecture we will learn about SSH and SCP commands.
  - SSH is used to login to the remote computer.
  - SCP is used to copy of files/directories within the file system also can c
opy data to remote computer.

  #### SSH

  - To login to the remote server use **`ssh`** command with hostname or IP ad
dress.

    ```
    ssh <hostname OR IP Address>
    ```

  - To login to the remote server with specific username and password.

    ```
    ssh <user>@<hostname OR IP Address>
    ```

    **`-l`** attribute can also be used as 

    ```
    ssh –l <user> <hostname OR IP Address>
    ```
  #### Password-Less Authentication

  - Passwordless authentication can be setup via key-pair authentication in or
der to login to the remote server with password.

  - Public and Private key are stored at below location.
    
    ```
    Public Key: /home/bob/.ssh/id_rsa.pub
    ```

    ```
    Private Key: /home/bob/.ssh/id_rsa
    ```

  - To generate a keypair on the **`Client`** run this command

    ```
    bob@caleston-lp10 ~]$ ssh-keygen –t rsa
    ```

    ![key](../images/key.PNG)

  - To copy the Public key from the client to the remote server

    ```
    bob@caleston-lp10 ~]$ ssh-copy-id bob@devapp01
    ```

    ![copy](../images/copy.PNG)

 
  - Now **`Bob`** can login to remote server without password

    ```
    [bob@caleston-lp10 ~]$ ssh devapp01
    ```

    ![pless](../images/pless.PNG)

  - Public Key is copied to the remote server at :

    ```
    [bob@caleston-lp10 ~]$ cat /home/bob/.ssh/authorized_keys
    ```
   
    ![auth](../images/auth.PNG)
  #### SCP

   - To copy a compresses file to a remote server

     ```
     bob@caleston-lp10 ~]$ scp /home/bob/caleston-code.tar.gz devapp01:/home/b
ob
     ```
 
   - To copy a directory to a remote server

     ```
     [bob@caleston-lp10 ~]$ scp –pr /home/bob/media/ devapp01:/home/bob
     ```
     
     ![scp](../images/scp.PNG)
# The Networking Story

  - Click [here](https://kodekloud.com/courses/873064/lectures/17074519) to kn
ow The Networking Story.
# DNS

  - Take me to the [Tutorial]
(https://kodekloud.com/courses/873064/lectures/17074529)

  - The domain name system is a distributed way to share these name-to-IP asso
ciations instead of requiring each computer to synchronize a hosts file. A nam
e server publishes the IP address for a domain and provides a single location 
to update when an IP changes.

  
  #### Ping 

  - **`Ping`** Command is use to check the remote machine is reachable or not.

    ```
    [~]$ ping 192.168.1.11
    Reply from 192.168.1.11: bytes=32 time=4ms TTL=117
    Reply from 192.168.1.11: bytes=32 time=4ms TTL=117
    ```

  - To **`Ping`** the remote host with a name instead of **`IP Address`** make 
an entry in **`/etc/hosts`** file

    ```
    [~]$ cat >> /etc/hosts
    192.168.1.11 db
    ```
    
    ```
    [~]$ ping db
    PING db (192.168.1.11) 56(84) bytes of data.
    64 bytes from db (192.168.1.11): icmp_seq=1 ttl=64 time=0.052 ms
    64 bytes from db (192.168.1.11): icmp_seq=2 ttl=64 time=0.079 ms
    ```
  - You can configure as many hosts you want in the **`/etc/hosts`** file.

    ```
    [~]$ cat >> /etc/hosts
    192.168.1.10 web
    192.168.1.11 db
    192.168.1.12 nfs
    192.168.1.20 web
    192.168.1.21 db-1
    192.168.1.22 nfs-1
    192.168.1.30 web-1
    192.168.1.31 db-2
    192.168.1.32 nfs-2
    192.168.1.40 web-2
    192.168.1.41 sql
    192.168.1.42 web-5
    192.168.1.50 web-test
    192.168.1.61 db-prod
    192.168.1.52 nfs-4
    192.168.1.60 web-3
    192.168.1.61 db-test
    192.168.1.62 nfs-prod
    ```

  - Every host has a DNS resolution file **`/etc/rsolve.conf`**

    ```
    [~]$ cat /etc/resolv.conf
    nameserver 192.168.1.100    
    ```

  - The **`/etc/nsswitch.conf`** file is used to configure which services are 
to be used to determine information such as hostnames, password files, and gro
up files.There is a specific search order according to which it is performed. 
This order is set in this configuration file.

    ```
    [~]$ cat /etc/nsswitch.conf
    …
    hosts: files dns
    …
    ```

# DOMAIN NAMES

  ![DNS](../images/dns.PNG)

  - .com - Commerical or General Purpose.
  - .net - Network or General Purpose.
  - .edu - Education Purpose
  - .org - Organizations for non profit organizations etc.

  ![Root](../images/root.PNG)

# RECORD TYPES

  ![Record](../images/record.PNG)
  
  - A - IP to host names.
  - AAAA - Storing ipv6 to hostnames.
  - CNAME - Mapping one name to another.
  
  - To test the DNS resolution you can use **`nslookup`** command, this will q
uery a hostname from a DNS Server.

  ```
  [~]$ nslookup www.google.com
  Server: 8.8.8.8
  Address: 8.8.8.8#53
  Non-authoritative answer:
  Name: www.google.com
  Address: 172.217.0.132
  ```

  - Another useful tool to query a hostname from a DNS server is **`dig`** whi
ch return more detailed information as shown.

  ```
  [~]$ dig www.google.com
  ; <<>> DiG 9.10.3-P4-Ubuntu <<>> www.google.com
  ;; global options: +cmd
  ;; Got answer:
  ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 28065
  ;; flags: qr rd ra; QUERY: 1, ANSWER: 6, AUTHORITY: 0, ADDITIONAL: 1
  ;; OPT PSEUDOSECTION:
  ; EDNS: version: 0, flags:; udp: 512
  ;; QUESTION SECTION:
  ;www.google.com. IN A
  ;; ANSWER SECTION:
  www.google.com. 245 IN A 64.233.177.103
  www.google.com. 245 IN A 64.233.177.105
  www.google.com. 245 IN A 64.233.177.147
  www.google.com. 245 IN A 64.233.177.106
  www.google.com. 245 IN A 64.233.177.104
  www.google.com. 245 IN A 64.233.177.99
  ;; Query time: 5 msec
  ;; SERVER: 8.8.8.8#53(8.8.8.8)
  ;; WHEN: Sun Mar 24 04:34:33 UTC 2019
  ;; MSG SIZE rcvd: 139
  ```

# HANDS-ON LABS
  
  - Lets have some fun and challenging [excerises]
(https://kodekloud.com/courses/873064/lectures/17074530)
# Switching & Routing 

  - Take me to the [Tutorial]
(https://kodekloud.com/courses/873064/lectures/17074531)

  #### Switching

  - Switching helps to connect the interface within same network.

    ![switch](../images/switch.PNG)

  - To see the interfaces on the hosts use **`ip link`** command

  ```
  [~]$ ip link
  eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP mod
e
  DEFAULT group default qlen 1000
  ```

  -  To connect to the switch we use **`ip addr add`** command

  ```
  [~]$ ip addr add 192.168.1.10/24 dev eth0
  ```

  #### Routing

  - Router helps to connect to two seprate networks together.

    ![route](../images/routing.PNG)
  - To see the existing routing table configuration run the **`route`** comman
d.

  ```
  [~]$ route
  Kernel IP routing table
  Destination Gateway Genmask Flags Metric Ref Use Iface
  ```

  - To configure a gateway on system B to reach the system on other network ru
n

  ```
  [~]$ ip route add 192.168.2.0/24 via 192.168.1.1
  ```
  
  ```
  [~]$ route
  
  Kernel IP routing table
  Destination Gateway Genmask Flags Metric Ref Use Iface
  192.168.2.0 192.168.1.1 255.255.255.0 UG 0 0 0 eth0
  ```

  - To see the ip addresses assign to interfaces use

  ```
  [~]$ ip addr
  ```

  - 

  ```
  [~]$ ip route
  ```

  - To make this changes permanent you must set them in **`/etc/network/interf
aces`** file.

# HANDS-ON LAB

  -  Lets get our hands on [LABS]
(https://kodekloud.com/courses/873064/lectures/17074533)
# TROUBLESHOOTING 

  - - Take me to the [Tutorial]
(https://kodekloud.com/courses/873064/lectures/17074532)
  - In this lecture we will be going to troubleshooting the issue that **`Bob`
** is facing.
  - Bob is not able to reach to the repository server and he get the error as 
show below.

    ![site](../images/site.PNG)

  #### Check Interfaces

  - Use the **`ip link`** to ensure the primary interface is up.
  - In this case, the network interface named **`enp1s0f1`** state is up.

    ```
    [~]$ ip link
    1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc
        noqueue state UNKNOWN mode DEFAULT group default qlen 1000
        link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    2: enp1s0f1: <BROADCAST,BROADCAST,MULTICAST,UP> mtu 1500 qdisc
        fq_codel state UP mode DEFAULT group default qlen 1000
        link/ether 08:97:98:6e:55:4d brd ff:ff:ff:ff:ff:ff
    ```

  - Check if we can resolve the hostname to IP address via **`nslookup`**

    ```
    [~]$ nslookup caleston-repo-01
    Server:      192.168.1.100
    Address:     192.168.1.100 #53

    Non-authoritative answer:
    Name: caleston-repo-01
    Address: 192.168.2.5
    ```

  - **`ping`** to check the connectivity.

    ```
    [~]$ ping caleston-repo-01
    PING caleston-repo-01 (192.168.2.5) 56(84) bytes of data.

    --- localhost ping statistics ---
    3 packets transmitted, 0 received, 100% packet loss, time 2034ms
    ```
 
  - **`traceroute`** to check the number of hops between the source. 

    ```
    [~]$ traceroute 192.168.2.5
    Tracing route to example.com [192.168.2.5]
    over a maximum of 30 hops:
    1 <1 ms <1 ms <1 ms 192.168.1.1
    2 <2 ms <1 ms <1 ms 192.168.2.1
    3 * * * Request timed out.
    ```

  - To check the port status use **`netstat`** command and to use it along wit
h port number use below command.

    ```
    [caleston-repo-01: ~]$ netstat -an | grep 80 | grep -i LISTEN
    ```

    ![net](../images/net.PNG)
    
  - To bring up the interface up use below command.

    ```
    [caleston-repo-01: ~]$ ip link set dev enp1s0f1 up
    ```

    ![iplink](../images/iplink.PNG)
# Where's my Storage

  Lets hear the [Story]
(https://kodekloud.com/courses/873064/lectures/17080739)

# DISK'S & PARTITIONS

- Take me to the [Tutorial]
(https://kodekloud.com/courses/873064/lectures/17074601)

- In this lecture we will learn about Disk Partitions. 
- We will look at the File Systems such as EXT series and NFS.
- External Storage Devices such as DAS,NAS, and SAN.
- LVM in Action.

  ![Disk](../images/disk.PNG)
  
  #### List all Block devices
  
  - Block devices are special files that refer to or represent a device (which 
could be anything from a hard drive to a USB drive). So naturally, there are c
ommand line tools that help you with your block devices-related work.
  - Major Number is used to identigy the type of block device, value 8 represe
nt a SCSI device starts with SD.
  - Minor Number is uset to distuinguish individual, physical or logical devic
es.

     ```
     [~]$ lsblk 
     ```

     ```
     [~]$ ls -l /dev/ | grep "^b"
     ```

  - To Print,Create and Delete the parition table use **`fdisk -l`** command 
 
     ```
     [~]$ sudo fdisk -l /dev/sda
     ```

  #### Partition Types - 
  
  ![Part](../images/partition.PNG)

  - PRIMARY - Use to Boot an Operating System.
  - EXTENDED - Can host logical partitions but cannot be used on its own.
  - LOGICAL - Created within an extended partition.

  #### Creating Partitions - 

  - **`Gdisk`** is an improved version of the **`fdisk`** that works with the 
GTP partition table.
  - To create a partition on **`sdb`** use
     
    ```
    [~]$ gdisk /dev/sdb
    GPT fdisk (gdisk) version 1.0.1

    Partition table scan:
      MBR: protective
      BSD: not present
      APM: not present
      GPT: present
    Found valid GPT with protective MBR; using GPT.
    
    Command (? for help): ?
    b back up GPT data to a file
    c change a partition's name
    d delete a partition
    i show detailed information on a partition
    l list known partition types
    n add a new partition
    o create a new empty GUID partition table (GPT)
    p print the partition table
    q quit without saving changes
    r recovery and transformation options (experts only)
    s sort partitions
    t change a partition's type code
    v verify disk
    w write table to disk and exit
    x extra functionality (experts only)
    ? print this menu

    Command (? for help): n
    Partition number (1-128, default 1): 1
    First sector (34-41943006, default = 2048) or {+-}size{KMGTP}: 2048
    Information: Moved requested sector from 34 to 2048 in
    order to align on 2048-sector boundaries.
    Use 'l' on the experts' menu to adjust alignment
    Last sector (2048-41943006, default = 41943006) or {+-}size{KMGTP}: 419430
06
    Current type is 'Linux filesystem'
    Hex code or GUID (L to show codes, Enter = 8300):
    Changed type of partition to 'Linux filesystem'
    Command (? for help): w
    Final checks complete. About to write GPT data. THIS WILL OVERWRITE EXISTI
NG
    PARTITIONS!!
    Do you want to proceed? (Y/N): Y
    OK; writing new GUID partition table (GPT) to /dev/vdb.
    The operation has completed successfully.
    ```

    ```
    [~]$ sudo fdisk -l /dev/sdb
    Disk /dev/sdb: 20 GiB, 128035676160 bytes, 250069680 sectors
    Units: sectors of 1 * 512 = 512 bytes
    Sector size (logical/physical): 512 bytes / 512 bytes
    I/O size (minimum/optimal): 512 bytes / 512 bytes
    Disklabel type: gpt
    Disk identifier: 7CABF26E-9723-4406-ZEA1-C2B9B6270A23
    Device Start End Sectors Size Type
    /dev/sdb1 2048 41943006 204800 20GB Linux filesystem
    ```

 # HANDS-ON LABS

   -  [Troubleshoot](https://kodekloud.com/courses/873064/lectures/17074602) w
hy **`Bob's`** System is not displaying the entire size of the physical disk
# File System in Linux

  - Take me to the [Tutorial]
(https://kodekloud.com/courses/873064/lectures/17074603)

  - In this lecture we will cover the most commonly used file systems from EXT
2 to EXT4.
  
    ![fs](../images/fs.PNG)

  #### Working with Ext4 

  - To create a file system we will make use of **`/dev/sdb`** disk, run below 
command 

    ```
    [~]$ mkfs.ext4 /dev/sdb1
    ```

  - Now create a directory to mount the filesystem use below commands

    ```
    [~]$ mkdir /mnt/ext4;

    [~]$ mount /dev/sdb1 /mnt/ext4
    ```    
  - To verify if the filesystem is mounted use 

    ```
    [~]$ mount | grep /dev/sdb1

    [~]$ df -hP | grep /dev/sdb1
    ```
  - Add an entry into **`/etc/fstab`** for the filesystem to be available afte
r reboot.

    ```
    # /etc/fstab: static file system information.
    #
    # Use 'blkid' to print the universally unique identifier for a
    # device; this may be used with UUID= as a more robust way to name devices
    # that works even if disks are added and removed. See fstab(5).
    #
    # <file system> <mount point> <type> <options> <dump> <pass>
    /dev/sda1 / ext4 defaults,relatime,errors=panic 0 1 ~
    ```

    ```
    echo "/dev/sdb1 /mnt/ext4 ext4 rw 0 0" >> /etc/fstab
    ```
  - **`fstab`** file attributes

    ![fstab](../images/fstab.PNG)

# HANDS-ON LABS

  - Lets Play around with [FileSystems]
(https://kodekloud.com/courses/873064/lectures/17074604)
# DAS NAS AND SAN

  - Take me to the [Tutorial]
(https://kodekloud.com/courses/873064/lectures/17074605)

  - Now that you are familiar with basic of storage in Linux lets learn about 
external storage.

  - DAS - Direct Attached Storage, external storage is attached directly to th
e host system tha requires the space.
  - NAS - Network Attached Storage quite similar to NFS server.
  - SAN - Storage Aread Network, this technology uses a fiber channel for prov
iding high-speed storage.

  #### NFS
  
  - NFS - Does not store data in blocks. Instead, it saves data in form of fil
es. It works on service-client model.

  - NFS server maintains an export configuration file at **`/etc/exports`** th
at defines the clients which should be able to 
  access the directories on the server. **`/etc/exports`** looks like this

    ```
    [~]$ /etc/exports
    /software/repos 10.61.35.201 10.61.35.202 10.61.35.203
    ```

  - To exports all the mounts defined in **`/etc/exports`** use 

    ```
    [~]$ exportsfs -a
    ```

  - To manually export a directory use below command

    ```
    [~]$ exportsfs -o 10.61.35.201:/software/repos
    ```
  
# HANDS-ON LABS

  - Lets had over to the [NFS LABS]
(https://kodekloud.com/courses/873064/lectures/17311763)
# LOGICAL VOLUME MANAGER

 - Take me to the [Tutorial]
(https://kodekloud.com/courses/873064/lectures/17074606)
 
 - LVM allows grouping of multiple physical volumes, which are hard disks or p
artitions into a volume group.
 - Volumegroups can be carve out logical volumes.

   ![LVM](../images/lvm.PNG)

  #### Working with LVM

  - To make use of LVM, install the package **`LVM`** .

    ```
    [~]$ apt-get install lvm2
    ```

  - Use **`pvcreate`** command to create a Physical Volume.

    ```
    [~]$ pvcreate /dev/sdb
    Physical volume "/dev/sdb" successfully created
    ```

  - Use **`vgcreate`** command to create a Volume Group.

    ```
    [~]$ vgcreate caleston_vg /dev/sdb
    Volume group "caleston_vg" successfully created
    ```

  - Use **`pvdisplay`** command to list all the PVs their names, size and the 
Volume group it is part of.

    ```
    [~]$ pvdisplay
    --- Physical volume ---
      PV Name /dev/sdb
      VG Name caleston_vg
      PV Size 20.00 GiB / not usable 3.00 MiB
      Allocatable yes
      PE Size 4.00 MiB
      Total PE 5119
      Free PE 5119
      Allocated PE 0
      PV UUID iDCXIN-En2h-5ilJ-Yjqv-GcsR-gDfV-zaf66E
    ```

  - Use **`vgdisplay`**  to see more details of the VG. 

    ```
    [~]$ vgdisplay
    --- Volume group ---
      VG Name caleston_vg
      System ID
      Format lvm2
      Metadata Areas 1
      Metadata Sequence No 1
      VG Access read/write
      VG Status resizable
      MAX LV 0
      Cur LV 0
      Open LV 0
      Max PV 0
      Cur PV 1
      Act PV 1
      VG Size 20.00 GiB
      PE Size 4.00 MiB
      Total PE 5119
      Alloc PE / Size 0 / 0
      Free PE / Size 5119 / 20.00 GiB
      VG UUID VzmIAn-9cEl5bA-lVtm-wHKX-KQaObR
    ```
    
  - To create the Logical Volumes, you can use **`lvcreate`** command

    ```
    [~]$ lvcreate –L 1G –n vol1 caleston_vg
    Logical volume "vol1" created.
    ```

  - To display the Logical Volumes, you can use **`lvdisplay`** command

    ```
    [~]$ lvdisplay
    --- Logical volume ---
      LV Path /dev/caleston_vg/vol1
      LV Name vol1
      VG Name caleston_vg
      LV UUID LueYC3-VWpE31-UaYk-wjIR-FjAOyL
      LV Write Access read/write
      LV Creation host, time master, 2020-03-31 06:26:14
      LV Status available
      # open 0
      LV Size 1.00 GiB
      Current LE 256
      Segments 1
      Allocation inherit
      Read ahead sectors auto
      - currently set to 256
      Block device 252:0
    ```

  - To list the volume, you can use **`lvs`** command

    ```
    [~]$ lvs
     LV VG Attr LSize Pool
     vol1 caleston_vg -wi-a----- 1.00g
    ```
 
  - Now to create an filesystem you can use **`mkfs`** command

    ```
    [~]$ mkfs.ext4 /dev/caleston_vg/vol1
    ```

  - To mount the filesystem use **`mount`** command

    ```
    [~]$ mount –t ext4 /dev/caleston_vg/vol1 /mnt/vol1
    ```

  - Now logical volume is now available for use. Lets resize the filesystem on 
vol1 while it is mounted. Check the free space available.

    ```
    [~]$ vgs
    VG #PV #LV #SN Attr VSize VFree
    caleston_vg 1 1 0 wz--n- 20.00g 19.00g
    ```

    ```
    [~]$ lvresize -L +1G -n /dev/caleston_vg/vol1
    Logical volume vol1 successfully resized.
    ```
    ```
    [~]$ df –hP /mnt/vol1
    Filesystem Size Used Avail Use% Mounted on
    /dev/mapper/caleston_vg-vol1 976M 1.3M 908M 1% /mnt/vol1
    ```

  - Now to resize the file system use **`resize2fs`** command.

    ```
    [~]$ resize2fs /dev/caleston_vg/vol1
    resize2fs 1.42.13 (17-May-2015)
    Filesystem at /dev/mapper/caleston_vg-vol1 is mounted on
    /mnt/vol1; on-line resizing required
    old_desc_blocks = 1, new_desc_blocks = 1
    The filesystem on //dev/mapper/caleston_vg-vol1 is now 524288
    (4k) blocks long.
    ```

   - Now run **`df -hp`** command to verify the size of the mounted filesystem

     ```
     [~]$ df –hP /mnt/vol1
     Filesystem Size Used Avail Use% Mounted on
     /dev/mapper/caleston_vg-vol1 2.0G 1.6M 1.9G 1% /mnt/vol1
     ```

     ![LVM2](../images/lvm2.PNG)

# HANDS-ON LABS

  - Lets head over to the hands-on labs of [LVM]
(https://kodekloud.com/courses/873064/lectures/17074607)
# Project Status Meeting

  - Join the [Meeting](https://kodekloud.com/courses/873064/lectures/17314533)
# Working Overtime

  Lets hear the [Story]
(https://kodekloud.com/courses/873064/lectures/17074642)

# Creating your own SYSTEMD Service

- Take me to the [Tutorial]
(https://kodekloud.com/courses/873064/lectures/17074644)
In this lecture we will learn how to create a SYSTEMD Service.
- All the major distributions, such as Rhel, CentOS, Fedora, Ubuntu, Debian an
d Archlinux, adopted systemd as their init system.
- Systemd is a Linux initialization system and service manager that includes f
eatures like on-demand starting of daemons, mount and automount point maintena
nce etc.
- Systemd also provides a logging daemon and other tools and utilities to help 
with common system administration tasks.

#### What is a service unit? 

- A file with the .service suffix contains information about a process which i
s managed by systemd. It is composed by three main sections:

  #### 1.Unit

  - The **`Unit`** section of a .service file contains the description of the 
unit itself, and information about its behavior and its dependencies: (to work 
correctly a service can depend on another one). Here we discuss some of the mo
st relevant options which can be used in this section
  - First of all we have the **`Description`** option. By using this option we 
can provide a description of the unit. The description will then appear, for e
xample, when calling the systemctl command, which returns an overview of the s
tatus of systemd.
  - Secondly, we have **`Documentation`** option. By using this option we can 
get the details of the service and documentation related to it.
  - By using the **`After`** option, we can state that our unit should be star
ted after the units we provide in the form of a space-separated list.

    ```
    [~]$ cat /etc/systemd/system/project-mercury.service
    [Unit]
    Description=Python Django for Project Mercury
    Documentation=http://wiki.caleston-dev.ca/mercury
    After=postgresql.service
    ```

  #### 2.Service

  - In the **`Service`** section of a service unit, we can specify things as t
he command to be executed when the service is started, or the type of the serv
ice itself.

    ```
    [Service]
    ExecStart=/usr/bin/project-mercury.sh
    User=project_mercury
    Restart=on-failure
    RestartSec=10
    ```

  #### 3.Install

  - This **`Install`** section contains information about the installation of 
the unit

    ```
    [Install]
    WantedBy=graphical.target
    ```

#### How to Start the Service now ?

- The system to detect the changes you have done in the file, we need to reloa
d the daemon and start the service.

  ```
  [~]$ systemctl daemon-reload

  [~]$ systemctl start project-mercury.service
  ```
# SYSTEMD Tools to Manage SYSTEMD service

  - Take me to the [Tutorial]
(https://kodekloud.com/courses/873064/lectures/17074645)

  In this lecture we will explore two major SYSTEMD tools:
  - SYSTEMCTL
  - JOURNALCTL

  ## SYSTEMCTL

   - __Systemctl__ is the main command used to manage services on a **`SYSTEMD
`** managed server.
   - It can be used to manage services such as **`START/STOP/RESTART/RELOAD`** 
as well as **`ENABLE/DISABLE`** services
     during the system boot.
   - It is also used to **`LIST AND MANAGE UNITS`** and **`LIST AND UPDATE TAR
GETS`**
   
      ![Systemctl](../images/systemctl.png)

    ### Systemctl Commands 

    - To start a service use the start command, for example to start a docker 
service use **`systemctl start docker`**
    
      ```
      [~]$ systemctl start docker
      ```

    - To stop a service use the stop command, for example to stop a docker ser
vice use **`systemctl stop docker`**
    
      ```
      [~]$ systemctl stop docker
      ```
    - To restart a service use the restart command, for example to restart a d
ocker service use **`systemctl restart  docker`** this will stop and start aga
in.

      ```
      [~]$ systemctl restart docker
      ```
    - To reload a service use the reload command, for example to reload a dock
er service use **`systemctl reload docker`**, this will reload all the configu
ration without interrupting the normal functionaltiy of the service
    
      ```
      [~]$ systemctl reload docker
      ```
    - To enable a service and make it persistent accross reboots use the enabl
e command, for example to enable a docker service use **`systemctl enable dock
er`**
      
      ```
      [~]$ systemctl enable docker
      ```

    - To disable a service at boot use the disable command, for example to dis
able a docker service use **`systemctl disable docker`** command.
      
      ```
      [~]$ systemctl disable docker
      ```

    - To know the status of the service use **`systemctl status docker`** comm
and. This command provided the state of the service. If running properly is sh
ould show **`active (running)`** state as shown in screenshot below.
    
      ```
      [~]$ systemctl status docker
      ```
    - Besides **`active (running)`** state there are few other state that you 
should be aware off.
        
      ![Other](../images/otherstate.PNG)

    - Running **`systemctl daemon reload`** command after making changes to se
rvice unit file reloads the system manager configuration and makes the systemd 
aware of the changes. 

    - To edit the service file use command **`systemctl edit project-
mercury.service --full`** this will open a text editor, you can make the chang
es and re-write the settings as needed, making changing this way applied immed
iately without running the **`systemctl daemon reload`** command
      
      ```
      [~]$ systemctl daemon-reload
      ```
      ```
      [~]$ systemctl edit project-mercury.service --full
      ```
    - To see the current runlevel use **`systemctl get-default`**
      
      ```
      [~]$ systemctl get default
      ```

    - To change the runleve to a different target use  **`systemctl set-
default multi-user.target`**
      
      ```
      [~]$ systemctl set-default multi-user.target
      ```

    - To list all the units that systemd has loaded use **`systemctl list-
units --all`**, this lists all the unit which are active, inactive or anyother 
state.
      
      ```
      [~]$ systemctl list-units --all
      ```

    - To list only active units use **`systemctl list-units`** command
      
      ```
      [~]$ systemctl list-units
      ```
        
  ## JOURNALCTL

   - __Journalctl__ is a command for quering/viewing logs collected by systemd
.
   - The systemd-journald service is responsible for systemd’s log collection, 
and it retrieves messages from the kernel    systemd services, and other sourc
es.
   - Very useful when you are troubleshooting issues with systemd services.
     
      ![Journalctl](../images/journalctl.png)

   - Using **`journalctl`** commands print all the log entries from oldest to 
the newest.
   - Using **`journalctl -b`** command print all the logs from the current boo
t.
   - Using **`journalctl -u docker.service`** command print all the logs speci
fic to the unit specified, for example docker in this case.

      ```
      [~]$ journalctl
      ```

      ```
      [~]$ journalctl -b
      ```      

      ```
      [~]$ journalctl -u docker.service 
      ```
## HANDS-ON LABS

  - Now lets troubleshoot and help **`Bob`** [Let's Help Bob]
(https://kodekloud.com/courses/the-linux-basics-course/lectures/17074647)
# Client Demonstration in Jeopardy!

  Let's hear the [Story]
(https://kodekloud.com/courses/873064/lectures/17074646)
# Troubleshoot the Development Environment

  [Troubleshoot](https://kodekloud.com/courses/873064/lectures/17074648) the D
evelopment Environment
# Finale (story)

  Lets Hear the Finale[Story]
(https://kodekloud.com/courses/873064/lectures/17074664)

You might also like