Categories
RHCE 7 Study Guide

How to Configure VNC Server in Linux

This tutorial explains how to configure VNC Server and VNC client in Linux step by step with examples. VNC Server and Client are used to share and access desktop from remote system for troubleshooting. Learn how to share Desktop through VNC Server and access shared Desktop from VNC Client in detail.

VNC server is a used to share desktop with remote computer. VNC works on client server architecture. To share desktop you need vnc-server package and to access from other computers you need vnc-viewer. In this tutorials I will show you how to configure vnc server.

For demonstration purpose we will use two linux systems. Both systems should have graphics installed.

To configure VNC- Server

Boot system in init 5 or graphic mode. vnc-server rpm is required to configure
server check it if not found install it.

rpm

now click on preferences from system and select
remote desktop

vnc

This will launch a new window where you can set sharing and security for remote desktop

set password on server

Allow other users to view your desktop check this option if you to present your desktop on other computer

Allow other users to control your desktop Check this options if you want to grant permission to control
user desktop to other user

In security tab you can set password for the user who want to connect
with server [Recommended]

Configure Linux client

Go on client system and ping server. vnc-viewer rpm is required to
configure clients

vnc viewer

check it and if not found install

Now select accessories from application menu and click on vnc viewer

vnc viewer

this will launch a window Give vnc server ip in it and click on
ok

give ip in vnc vieawer

Once connected it will ask for password Give the password which you set
on server

enter password in vnc

On server side it will show a pop up and ask for permission click on
allow

grant permission

After getting permission from server side you can use server
desktop
on client side

use server desktop

Full Version EX300 Dumps

Try EX300 Dumps Demo

Categories
RHCE 7 Study Guide

Tar command and Syntax Explained with Examples

This tutorial explains the basic usages of tar command in Linux with practical examples. Learn how to create an archive file, list the contents of tarball and extract the archived file in current directory or in specified directory.

The tar command is used to manage the archives. An archive is the collection of multiple files that can be transferred as a single file or can be stored as a backup copy. An archive file, created with tar command, is also known as a tarball.

The tar command syntax

To create, list and extract an archived file, the tar command uses following syntax respectively.

tar -cvf [destination-file-name.tar] [source-files or directories]
tar -tvf archive-file.tar
tar -xvf archive-file.tar

The tar command options



The option c creates archive or tarball from the supplied files or directories.
If a directory is supplied, all of its files and sub-directories are also included in the archived file recursively.

The option v displays the progress of archiving process at the command prompt.
This option is optional. You can use it; if you want see what the tar command is actually doing.
Or you can skip it; if you don’t want to print the progress of archiving process at the command prompt.

The option f specifies the file or device name. If it is used with option c,
it instructs the tar command to store the output data to the specified device or file.
If we don’t specify this option, the tar command uses the standard output device
(console or command prompt) to store the output data. In other words,
if we don’t specify the output location with this option, the tar command simply dumps all output data to the command prompt.

While specifying a file to store the output data, usually the extension .tar is used with file name.
Although it’s not required, still you should always use this extension with the file name.
Using an extension for archived files helps keeping them separate from other files.

The option t lists the contents of archive or tarball. Since this option lists the content of archive,
the archive file or device must to be specified with the option f.

The option x extracts the archive. Just like option t, this option also need an archive file or device specified with the option f.

Key points
  • While specifying options, you can use a dash () before the options or not. For example, you can specify options as -cvf or as cvf.
    Tar supports both styles.
  • The order of options is important. First you have to specify the action (create, list or extract),
    next specify any additional requirement such verbose message and in the last specify the file or device name
    where the desired action need to be performed.

tar command options order

This tutorial is the second part of the article \”Compressing and archiving explained in Linux\”. This tutorial explains following RHCSA/RHCE topic.

Archive, compress, unpack, and uncompress files using tar, star, gzip, and bzip2

Other parts of this article are following.

Compress and Decompress Files in Linux with gzip and bzip2

This tutorial is the first part of the article. It explains how to compress and decompress files in Linux with gzip and bzip2.

Tar Command Examples in Linux

This tutorial is the last part of the article. It explains how to use the tar command in Linux with practical examples.

Creating archive or tarball

To create an archive, three options c, v and f are used together.



Let’s take some examples to understand how these options are used with the tar command to create archives.

Following command creates an archive from a single file named test and puts that archive file in the same directory.

#tar -cvf  test.tar test

creating archive with tar

To add multiple files in an archive, specify them as arguments.
For example, following command creates the archive file files.tar from files; a, b, c, d and f.

#tar -cvf files.tar a b c d f

creating archive with multiple files

Just like the files, we can also specify the directories as arguments.
If we specify a directory as an argument, all of its files and sub-directories are added in archived file recursively.
For example, following command creates the archive file data.tar from the directory testdir.

#tar -cvf data.tar testdir

creating archive with directories

If files and directories that you want to add in archive file are not available in current directory,
use their full path. For example, following command creates the archive conf.tar from the files; /etc/hosts, /etc/hostname and /etc/host.conf.

adding files in archive from other directories

Just like we can create an archive from the files which are not available in current directory,
we can also put the archived file in any location or device. For example,
following command adds all files and directories from home partition in the archive home.tar and stores that archive in /tmp partition.

#tar -cvf /tmp/home.tar /home

adding all files and directories recursively  in archive

Listing the content of tarball or archive file

Once an archive or tarball file is created, its contents (name of files and directories) can be listed with
the options -tvf. For example, to see what files are stored in the archive data.tar, you can use following command.

#tar -tvf data.tar

Following figure shows few more examples of listing the contents from archive file.

tar command listing the contents of archive file

Extracting files and directories from a tarball or an archive file

To extract an archive or tarball file, the option x is used with options v and f.
For example, following command extracts an archive file test.tar.

#tar -xvf test.tar
 

In extraction process, if a file already exists, it will be overwritten without any warning and notification message.
While extracting an archive file, we must take care of this default behavior. Let’s understand it with an example.

You added a file in an archive on Sunday. On Monday, you made some changes in original file.
On Tuesday, you extracted the archived created on Sunday in the same directory.

What will happen in this case?

In this case, all changes which were made on Monday will be lost as the updated file will be overwritten with the file which was backed up on Sunday.

default extraction process tar command

In extraction process, the tar command uses the same directory structure in which files and directories were added in archive.
It first creates directories and then extracts files in respective directories.

extract directories and files from tar command

The tar command, instead of the directory where the archived file is stored,
extracts it in the directory from which it is executed. In simple words, it extracts archive in the current directory.

tar extracts archive in current directory

To extract archive in a specific directory, we have two choices.

  1. Switch to the directory before executing the tar command.
  2. Specify the directory path with option -C

Following figure shows examples of both.

extract archive in specific directory

That’s all for this part. In next part of this tutorial I will explain how to perform some advance operations with the tar command. If you like this tutorial, please don’t forget to share with friends.

Full Version EX300 Dumps

Try EX300 Dumps Demo

Categories
RHCE 7 Study Guide

How to create swap partition in Linux

This tutorial explains how to view, list, activate, deactivate, add, remove, increase, decrease mount and format swap space and swap partition in Linux step by step with practical examples. Learn essential swap space management tasks including what swap space is and how swap space is used in Linux.

What is the swap space?

Traditionally Linux was developed for server system. Server systems are built to process several processes simultaneously. Sometime some process may use more than expected memory. For example a university website which is hosted in Linux server system may consume more memory on the day when exam result is announced. This kind of memory spike is very common in server system. Any service may use more memory in its peak time. Linux uses swap space to deal with the shortage of physical memory. The swap space is the space of hard disk that can be used as the memory.

swap hard disk ram

Let’s understand it in more detail. System divides RAM in smaller chunks known as memory pages. Memory pages are assigned to service or process running in CPU. CPU processes services or applications in round-robin fashion.

Round-robin Fashion

In round-robin fashion, all processes are scheduled in a queue based on time sharing technique. Further each process is assigned a quantum
(allowed CPU Time slot). If process is not finished in allowed time slot then it will be terminated and resumed next time when this
process gets its next time slot. For example, if the time slot is 100 milliseconds, and job1 takes a total time of 250 ms to complete,
the round-robin scheduler will suspend the job after 100 ms and give other jobs their time on the CPU. Once the other jobs have had their
equal share (100 ms each), job1 will get another allocation of CPU time and the cycle will repeat. This process continues until the job
finishes and needs no more time on the CPU.

Suppose there are two processes running. Both processes are assigned memory pages. CPU is processing process one. Following figure illustrates this scenario.

swap space example

As we can see in above figure, no memory pages available for another process. System will not start new process until any existing process is finished. Swap space can improve this situation a little bit. If swap space is configured and RAM is filled, idle pages will be moved in swap space.

For example, when process A is executing, memory pages occupied by process B will be moved in swap space. Vice versa when process B is executing, memory pages occupied by process A will be moved in swap space. This way by using same physical memory Linux can run more processes with swap space.

The process of moving idle memory pages from RAM to swap is known as page out. The process of moving required memory pages back from swap to RAM in known as page in.

Following figure illustrates this process

linux swap space example

Key points



  • The swap space is the hard disk space which is used to supplement the system RAM by holding idle memory pages.
  • Since swap space resides in hard disk, it is incredibly slow in comparison with RAM.
  • Swap space is the essential part of Linux configuration.
  • If swap space is configured, a threshold value for physical memory will also be configured. The swap space is used only when physical memory is used beyond the threshold.
  • As long as free memory remains below the threshold, no swap space will be used.
  • Swap usage should be monitored closely. If swap starts being used intensively, the performance of system would be decrease.

This tutorial is the fifth part of our article “Linux Disk Management Explained in Easy Language with Examples”. You can read other parts of this article here.

Linux Disk Management Tutorial

This is the first part of this article. This part explains basic concepts of Linux disk management such as BIOS, UEFI, MBR, GPT, SWAP, LVM, RAID, primary partition, extended partition and Linux file system type.

Manage Linux Disk Partition with fdisk Command

This is the second part of this article. This part explains how to create primary, extended and logical partitions from fdisk command in Linux step by step with examples.

Manage Linux Disk Partition with gdisk Command

This is the third part of this article. This part explains how to create GPT (GUID partition table) partitions from gdisk command in Linux step by step with examples.

Linux Disk Management with parted command

This is the fourth part of this article. This part explains how to create primary, extended, logical and GPT partitions from parted command in Linux step by step with examples.

Learn how to configure LVM in Linux step by step

This is the sixth part of this article. This part explains basic concepts of LVM in detail with examples including how to configure and manage LVM in Linux step by step.

How to configure RAID in Linux Step by Step Guide

This is the last part of this article. This part explains basic concepts of RAID in detail with examples including how to configure and manage software RAID in Linux step by step.

How to create swap partition



We can create a new partition or can use free space from existing partition for swap space. We will learn both methods. Let’s start with partition method.

Since swap partition is created as a regular partition,
we can use any disk utility from fdisk, gdisk or parted. Second, third and fourth part of this article explains fdisk,
gdisk and parted in detail with examples respectively.
In this tutorial we will use fdisk utility to create a swap partition.

New partitions can be created only from un-partitioned disk space. For this tutorial I assume that either you have un-partitioned disk space or have a blank disk for practice. For demonstration purpose I added one additional 2GB hard disk (/dev/sdc) in system.

Let’s initiate fdisk command

fdisk dev sdc

Replace /dev/sdc with your disk.

Use p command to get the overview of hard disk.

fdisk commnad p option

The p command provides information about available space in hard disk to create a new partition. If last partition ends before the last sector of hard disk, we have available space to create a new partition. As we can see in above output currently no value is available in partition section which means there is no partition available and entire disk space is available for new partition. Let’s create a 500MiB partition.

Type n and press Enter key.

Type p and press Enter key.

Type the partition number (or keep the default number) and press Enter key.

Type the first available sector for partition (or accept the default sector) and press Enter key.

Type the last available sector for partition. Alternatively we can use KiB, MiB or GiB units to define the size of partition.

Verify the creation of partition with p command

Following figure illustrates above process step by step

fdisk command create new partition

Each partition uses a special marking known as partition system identifier. This marking is used to identify the purpose of partition. To print all available partition types type l and press Enter key.

fdisk list partition type

As we can see in above output value 82 is used as partitions type identifier for swap space.

Unless we change the type of any partition it is marked as Linux Standard default.

To use partition for swap space we have to change the partition type.

Type t and press Enter key

Type 82 and press Enter key

Verify the change with p command

Following figure illustrates above process

fdisk change partition type

The fdisk will not save anything in disk until we confirm the action. To accept the change type w and press Enter key

fdisk save partition table

The fdisk cannot update the in-memory kernel partition table. Run following command to force the kernel to reread the partition table.

partprobe dev sdc

Replace /dev/sdc with your disk name.

We have successfully created swap partition.

Formatting swap partition

We have to format a partition with appropriate file system before it can be used for data storage. File system allows us to create files and directories in partition. Unlike a regular partition which is used to store the user data, the swap partition is used to store the system data.

The mkswap command is used to format a partition for swap space. Since swap partition is never used for user data, this command does not create a file system in partition; it only applies a swap signature in partition. It writes signature in a single block of data, leaving the rest of the partition unformatted. This unformatted space is used to store the memory pages.

Let’s format the partition with mkswap command.

mkswap format command

Now this partition is ready to use for swap space. Before we learn how to update the system about this additional swap space let’s have a quick look on two important commands which are frequently used to view the current status of swap space.

free : – This command display the current status of memory.

swapon –s :- This command display the status of swap space.

free swapon -s command linux

As we can see in above output a partition of 1023996MiB is configured as a swap space. From this space 12596MiB is currently used and 1011400MiB is available.

Activating swap partition

To activate new swap partition following command is used.

# swapon  [device_name]

Here device_name is name of partition or file which we want to use for swap space. Partition or file must be marked with swap signature.

Let’s activate the recently created swap partition.

activate swap partition

As we can see in above output, before activating this swap partition total swap space was 1023996MiB which increased to 1535992MiB after
activating this swap partition. This additional 511996MiB swap space came from new swap partition (/dev/sdc1) which can also be verified with
swapon –s command. This increased swap space will be available only for this session. After reboot we have to mount this swap partition again.
If we want to use this swap partition permanently, we have to make an entry in fstab file. Kernel reads fstab file to mount the file system in boot process.

Mounting swap space permanently

System configuration files should always be backed up before editing. Let’s take the backup of fstab file and open it for editing

fstab file backup

By default this file has entry for those partitions which were created during the installation. To mount any additional partition automatically we have to make an entry for that partition in this file. Each entry in this file has six fields.

default fstab file

Number Filed Description
1 What to mount Device which we want to mount. We can use device name, UUID and label in this filed to represent the device.
2 Where to mount The directory in main Linux File System where we want to mount the device.
3 File system File system type of device.
4 Options We can use supported options here to control the mount process. For this tutorial we will use default options.
5 Dump support To enable the dump on this device use 1. Use 0 to disable the dump.
6 Automatic check Whether this device should be checked while mounting or not. To disable use 0, to enable use 1 (for root partition) or 2 (for all partitions except root partition).

Let’s updated each filed one by one.

What to mount

As we know each resource in file system has a unique ID called UUID. When mounting a partition permanently we should use UUID instead of its name.

The UUID stands for Universally Unique Identifier. It is a 128-bit number, expressed in hexadecimal (base 16) format.

To know the UUID of all partitions we can use blkid command. To know the UUID of a specific partition we have to use its name as argument with this command.

Once we know the UUID, we can use it instead of device name. We can also use copy and paste option to type the UUID.

To use copy and paste operation, open another terminal and run blkid command. Now copy the UUID of partition from second
terminal and paste in fstab file which is opened in first terminal. Once we are done close the second terminal.

copy and paste uuid

Where to mount

Since swap partition is used as a hardware device by system, it cannot be mounted in file system which is accessible through the directory structure. Use value swap in this filed as a placeholder value.

File system type

The file system type for swap space is swap.

Mount option

Use default mount option.

Dump support

Since it is used only to store temporary memory pages, disable this option.

Automatic check

Since it does not contain any user or system data, disable this option also.

After updating all fields save the file.

swap partition fstab entry

We can check fstab file entries with mount –a command. This command will mount everything listed in /etc/fstab file.
So if we made any mistake while updating this file, we will get an error as the output of this command.

If you get any error as the output of mount –a command, correct that before rebooting the system.
If there is no error, reboot the system.

reboot the system

After reboot we can use free and swapon command again to verify that swap partition is mounted correctly.

confirm swap partition

Above output confirms that swap partition is mounted correctly.

Swap space is used only if physical memory consumption extends the threshold. Swap space is used in a series. Swap space series is displayed in Priority filed. First swap space will be used first. Second swap space will be used only if first swap space is filled completely.

Removing swap space partition

Swap space can be removed in following three steps: –

  • Deactivate the swap space
  • Remove entry from fstab file
  • Delete the swap partition

The swapoff command is used to deactivate the swap space. For example following command will be used to deactivate the /dev/sdc1 swap partition

#swapoff /dev/sdc1

We took the backup of /etc/fstab file before starting this practice. We can either restore that file back or
can delete swap partition entry from current file.

Following figure illustrates both steps

restore fstab file

Finally delete the partition and update the kernel with following steps: –

  • Run fdisk /dev/sdc command to initiate fdisk utility. [Replace /dev/sdc with your disk name]
  • Use p command to know the partition number
  • Use d command to delete the swap partition. If disk has only one partition, it will be selected automatically. If disk has multiple partitions, provide the correct partition number.
  • Use p command again to confirm that partition is removed
  • Save the change with w command
  • Run partprobe command to update the kernel about this change.

Following figure illustrates above steps

delete swap partition

How to create swap space from file

As we know to create a new swap partition, un-partitioned disk space is required. If we don’t have un-partitioned disk space, we cannot create new swap partition. In that case we can increase swap space from file.

To create swap space from file we first need to create a swap file. Use df –h command to figure out the partition which has enough free space to store the swap file and run following to create swap file in that partition.

#dd if=/dev/zero of=/swap-file count=1000 bs=1M

Let’s understand this command in detail.

dd :- The dd (disk duplicator) command is used to copy or backup the low level data.

if=/dev/zero :- This is the first option. This option accepts source location as argument.
In this example I copied from /dev/zero disk file. The /dev/zero is a special file in Linux system which supplies endless zero bytes.

of=/swap-file :- This is the second option. This option accepts destination location as argument.
In this example I copied at /swap-file. The swap-file is the name of file. You can use any descriptive name here.

count=1 :- This is the third option. It is used to define the number of block which we want to copy.

bs=1 :- This is the last option. It is used to define the size of block. 1M stands for one megabyte.

Basically this command creates a file of 1GB (1M x 1000 count) from null characters (zero bytes).

Following figure illustrates above process step by step

dd command

We can also verify the size of swap file with du –h command.

du -h command

Since this file is created with null characters for memory pages, we cannot read its content with regular commands.

cat swap file

Usually there is no need to read the file which contains only null characters, but if you are still interested in reading zero bytes, use –v option with cat command or use od command.

od swap file

Now we can use this file for swap space. Let’s put swap signature in this file.

mkswap swap file

Since this file will be used only by system, change its permission to 0600.

change swap file permission

Same swapon command will be used to activate this swap space also.

swapon swap file

From performance point of view, there is no difference between both methods. From security point of view partition method is more secure and stable in comparison with file method. Since swap file is created in user accessible directory structure, it could be moved or deleted. So we should use swap file only if we do not have free disk space to create a swap partition and we have to increase swap space immediately.

Removing swap file

To remove a swap file first deactivate it with swapoff command

swapoff swap file

We can also use free and swapon –s command to confirm the remove operation.

Now use rm –rf command to delete the file

rm -rf swap file

That’s all for this tutorial. In next part we will learn how to create and manage LVM partitions in Linux step by step with examples.

Full Version EX300 Dumps

Try EX300 Dumps Demo

Categories
RHCE 7 Study Guide

Linux alias List, Set, Create & Remove with alias Command

This tutorial explains linux alias command with syntax and options in details including how to list, set, add, remove, create and delete alias in Linux temporary and permanently step by step with practical examples. Learn how to customize the Linux environment with local and global alias in detail.

How to check default alias

To check default alias run following command

$alias

alias command

Some of the aliases listed are likely to be system-wide aliases that apply to all users and are created automatically for each new user for a particular shell. Aliases for any other shell can be seen by first switching to that shell and than using the alias command as above.

alias command allows you to launch any command or group of commands with simple names or abbreviations.

Syntax of alias is

alias name=\"value\"
  • name is the name of the new alias
  • value is the command(s) which it initiates.
  • No spaces are permitted before or after the equals sign. Any number of aliases can be created simultaneously by enclosing the name in each name-value pair in quotes.
  • The alias name and the replacement text can contain any valid shell input except for the equals sign ( = ).
  • The commands, including any options, arguments and redirection operators, are all enclosed within a single pair of quotation marks, which can be single quotes or double quotes.

Take a simple example of ls command. ls command list the content of directory.

ls command

With -l switch it list content in long format with details

ls command with l switch

With the use of alias command we can create an alias for ls command with -l switch so when you run ls command it execute with -l switch

alias ls with l

You can use any simple easy to remember name instead of command and than use them in the same way that ordinary commands are used.

For example you can use list keyword

alias list

alias set in this way are known temporary alias. Temporary alias would not be available after logout.

How to make alias permanent

You can make alias permanent locally and globally.

To make an alias permanent on user level edit ~/.bashrc file.

In Linux world on command prompt any file or folder deleted once would be deleted forever. But we can make TRASH folder using alias command.

Make a trash folder. Keep it hidden. [Put a DOT in front of folder name ]

$mkdir .trash

mkdir trash

Open .bashrc file

user vi bashrc

In the end of file add following command

alias rm=\"mv -t ~/.trash\"
  • rm command used to delete file or folder [with switch]
  • ~ In Linux ~ (tilde sign) represent users home directory

alias edit user bashrc

.bashrc file initialized when user login.

Logout from current session

user exit

login back

user login alias

Now when a user run rm command shell will actually execute mv command. Create a test file and delete it with rm command

create test file

you can restore deleted file from trash folder. Restore our deleted file

restore test file

To make an alias permanent on system level login form root and open /etc/bashrc

roo vi bashrc

add your custom alias at the bottom of file and save it

bashrc root edit

logout form current session login back and test alias

root test alias

How to unset alias

If you need new alias with same name than best way to remove an alias is by use the alias command to create a new alias with the same name. This overwrites the existing alias with that name.

If you only want to remove alias use unalias command

unalias

If you have created permanent alias than open that file again and remove alias entry from configuration file.

remove system level

Use of Linux alias command for system administrator

alias command can be used in several ways. Most popular use of alias command among the Linux system administrators are following

Use alias command to reduce the amount of typing

For example you frequently need to go in directory which have long path. You can create an alias for that directory and use it. Like we have a directory with the path

~/custom_script/linux/web_script/php/new_script

we can create an alias for it

$ alias new_php_script=\"cd ~/custom_script/linux/web_script/php/new_script\"

Now whenever we need to go in that directory, we only need to type new_php_script on command prompt

$new_php_script

Use alias command to specify default options for command.

Like we have specified for ls command in above

Use alias command to create trash on command prompt

As we create in above example

Use alias command for safety of the system

A system administrator use alias to increase the safety of the system by making commands interactive. This forces the user to confirm that it is desired to perform a specific action and thereby reduces the risk from accidental or impulsive abuse of powerful commands.

For example cp command which is used to copy the contents of one file to another file, can also be reduced by making it interactive by default. If the name for the file to be written to does not exist in the specified directory (by default the current directory), it will be created, but if it already exists, its contents will be overwritten.

$alias cp=\"cp -i\"

Above alias will reduce the chances of an unintended overwriting. Now if it detects any existing file with same name rather than overwriting that file shell would ask for confirmation.

Use alias to correct misspellings of commands.

For example a user which switched from window platform, he has a habit of typing dir instead of ls. We can create an alias for it in following way

$alias dir=\"ls\"

Now user can use dir also to list the content.

Full Version EX300 Dumps

Try EX300 Dumps Demo

Categories
RHCE 7 Study Guide

Linux Disk Management with parted command

Learn how to create, list, format, mount (temporary and permanent), remove and delete MBR & GPT partitions step by step in detail. This tutorial explains how to manage MBR disk partition (Primary, Extended and Logical) and GPT disk partition in Linux from parted command with practical examples.

For this tutorial I assume that you have two separate disks for exercise.
If you are using virtual program (such as VMware or Virtual Box) for the practice,
I suggest you to add two new virtual hard disks for this practice.

MBR partition scheme and GPT partition scheme both use different method to store partition information in disk. We cannot use both scheme in a single disk.
Since in this tutorial we will create both types of partitions, we need two separate disks. We have already added two virtual disks in our system.

To learn more about MBR partition, GPT partition and how to add virtual disks in VMware see the first part of this tutorial.

This tutorial is the fourth part of our article “Linux Disk Management Explained in Easy Language with Examples”. You can read other parts of this article here.

Linux Disk Management Tutorial

This is the first part of this article. This part explains basic concepts of Linux disk management such as BIOS, UEFI, MBR, GPT, SWAP, LVM, RAID, primary partition, extended partition and Linux file system type.

Manage Linux Disk Partition with fdisk Command

This is the second part of this article. This part explains how to create primary, extended and logical partitions from fdisk command in Linux step by step with examples.

Manage Linux Disk Partition with gdisk Command

This is the third part of this article. This part explains how to create GPT (GUID partition table) partitions from gdisk command in Linux step by step with examples.

How to create SWAP partition in Linux

This is the fifth part of this article. This part explains how to create swap partition in Linux with examples including basic swap management tasks such as how to increase, mount or clear swap memory.

Learn how to configure LVM in Linux step by step

This is the sixth part of this article. This part explains basic concepts of LVM in detail with examples including how to configure and manage LVM in Linux step by step.

How to configure RAID in Linux Step by Step Guide

This is the last part of this article. This part explains basic concepts of RAID in detail with examples including how to configure and manage software RAID in Linux step by step.

Before we start let’s have an overlook of all attached hard disks with fdisk –l command.

As above figure shows there are two un-partitioned disks /dev/sdb and /dev/sdc. We will use /dev/sdb for the practice of GPT partitions
and /dev/sdc for the practice of MBR partitions.



Before making any system change we should always take the backup of associate files.
Backup copy allows us to revert in original state if anything goes wrong.
Run following commands to create a backup copy of files which will change in this practice.

dd command backup

In first command we created a directory to store the backup files.

In second command we took the backup of first megabyte of raw blocks of /dev/sdb hard disk. Let’s understand this command in detail.

dd :- The dd (disk duplicator) command is used to copy or backup the low level data.

if=/dev/sdb :- This is the first option. This option accepts source location as argument.
In this example I copied from /dev/sdb disk. Change the disk name with the disk name which you want to use for the practice.

of=/root/backup/sdb-backup-file :- This is the second option. This option accepts destination location as argument.
In this example I copied at /root/backup/sdb-backup-file. The sdb-backup-file is the name of file. You can use any descriptive name here.

bs=1 :- This is the third option. It is used to define the size of block. 1M stands for one megabyte.

count=1 :- This is the last option. It is used to define the number of block which we want to copy.

In third command we took the backup of first megabyte of raw blocks of /dev/sdc hard disk.

In fourth command we took the backup of /etc/fstab file. This file contains partitions information.
This information is used to mount the file system while system boots.

Now we are ready to create the partitions.

Creating MBR Partition with parted command



The parted command needs the name of disk where we want to create the partition as its argument.

parted command

Always use parted command with argument. Without argument it will start with first available disk. The parted command includes several sub-commands which may erase entire disk data without any warning or notification. Always make sure, you are working with correct disk before executing any sub-command in parted. If wrong disk is selected, exit immediately with quit command.

Before we start working with disk let’s have the overview of current disk layout. The print command is used to print the current disk layout.

prated print command

The print command provides important information about the hard disk. This information includes manufacturer information,
disk model, disk size, Partition Table and disk flag. If this is a new disk, we will get unrecognised disk label error.
Disk label is the information which is used to determine the type of disk. The parted command needs a valid disk label before it
can do anything with disk. To see it practically run mkpart command. The mkpart command is used to create new partition.

unrecozinsed error

As above output confirmations that we are not allowed to create new partition unless it has a valid disk label.
The msdos and gpt are two valid disk labels which we can use here.
The msdos label is used to define the disk as MBR disk and the
gpt label is used to define the disk as GPT disk.

To understand the difference between MBR and GPT see the first part of this tutorial.

To assign the label mklabel command is used. Let’s assign the msdos label to this disk.

  • Type mklabel and press Enter key.
  • Type msdos and press Enter key.
  • Verify the action with print command.

parted mklabel command

Do not use this command if disk contains data. This command is very risky. This command will convert disk in un-partitioned blank disk silently. Neither it will generate a warning message if disk contains partitions nor it will ask for confirmation. To add worse, changes are written in disk immediately. Before hitting Enter key make sure that disk is either blank or you really want to delete all partitions from the disk.

Now disk has label. We can create partition in it. To create partition following steps are used.

Type mkpart and press Enter key.

As we know in MBR partition scheme we are allowed to create maximum four primary partitions. If more partitions are required, we have to use one primary partition as extended partition. Further Extended partition can be used to create 15 logical partitions.

To learn more about MBR and GPT partition scheme, see the first part of this tutorial which explains these and other relative topics in detail with examples.

Type the partition type and press Enter key.

Type the starting point for partition and press Enter key.

The parted utility supports very limited file system types. To add worse, most of them are out dated nowadays. We will make file system individually later. By now just keep the default file system type.

Type the ending point for partition. We can use KB, MB or GB units to define the size of partition.

We can verify the creation of partition with print command

Following figure illustrates above steps

parted mkpart command

Always start first partition with 1MB even only first 512 bytes are used to store the MBR data. This way we can avoid several entry point errors.

Following same process create two more partitions

parted mkpart command

We have created three primary partitions from maximum (four) allowed. Now we can create one more primary partition or can create one extended partition.

Let’s create one allowed extended partition. Since extended partition is used to create all allowed logical partitions, we should allocate the maximum disk space in this partition. We will assign all remaining disk space in this partition.

parted command extended partition

All logical partitions will be created in extended partition. The sum (of size) of all logical partitions cannot go beyond the extended partition. In this example we created an extended partition of 1145MB, so we can create logical partitions from 1145MB. We are allowed to create up to 15 logical partitions in extended partition. We can create any number of partitions from range of one to fifteen. The only limit is that the sum of all partitions must be below the size of extended partition.

This concept is explained in detail with example in second part of this tutorial.

Let’s create a single logical partition of all available space.

parted command logical partition

We have used all space of extended partition in one logical partition. So even we are allowed to create up to 15 logical partitions and free space is available outside the extended partition, we cannot create the another logical partition. To create another logical partition we need free space inside the extended partition not outside the partition.

So far we have created all possible partitions including primary, extended and logical partitions.

To exit from parted use quit command.

parted quit command

The parted cannot update the in-memory kernel partition table. Kernel reads partition table when system boots. So the kernel will be updated about this change at next reboot automatically. Meanwhile if we want to update the kernel immediately, we can use partprobe command which force kernel to reread the partition table.

partprobe command

Replace /dev/sdc with your disk name.

We have successfully created MBR partitions. To view the partitions use fdisk –l command.

fdisk -l command

Creating GPT partition with parted command

GPT is the new partition scheme. It allows us to create up to 128 partitions. It does not divide partitions in primary,
extended and logical. First part of this article explains basic concepts of GPT in detail with examples.

We will create GPT partition in /dev/sdb disk. Let’s initiate parted again for /dev/sdb disk

parted sdb

As we know, we cannot create partitions until disk has a valid label. Assign the gpt label in disk

parted mklabel command

Now disk has a valid label. We can create partition in it. Creating partition is a six steps process.

  • Type mkpart and press Enter key
  • Set desired descriptive name for partition
  • Accept default file system type
  • Enter starting point of partition
  • Enter ending point of partition
  • Verify the partition with print command

Following figure illustrates above steps

parted command gpt partition

Following same steps create two more partitions

mkpart gpt partition

Exit from parted with quit command

parted quit command

Finally update kernel about this change

partprobe command

So far we have created MBR and GPT partitions in /dev/sdc and /dev/sdb respectively.

These partitions are useless unless we put a file system in them. File system is a logical container which allows us to store files and directories.

How to create file system

To create a file system in partition we format it with supported file system. To format a partition following command is used.

#mkfs –t [supported file system type] [partition]

Some common supported file systems are ext3, ext4 and xfs. Let’s format the recently created partitions with these file systems.

Format MBR partitions

format mbr partition

Format GPT partitions

format gpt partition

Now partitions have file system, can we use them for data storage? No, even though partitions are ready to use, we cannot use them until they are connected with primary directory structure (Main Linux file system).

mount error

Linux file system (primary directory structure) starts with root (/) directory and everything goes under it or its subdirectories. We have to mount partitions somewhere under this directory tree. We can mount partitions temporary or permanently.

Mounting partitions temporary

Following command is used to mount partition temporary.

#mount [what to mount] [where to mount]

Mount command accepts several options and arguments which I will explain separately in another tutorial. For this tutorial this basic syntax is sufficient.

what to mount :- This is the partition.

where to mount :- This is the directory which will be used to access the mounted resource.

Once mounted, whatever action we will perform in mounted directory will be performed in mounted resources. Let’s understand it practically.

  • Create a mount directory in / directory
  • Mount /dev/sdc1 partition
  • List the content
  • Create a test directory and file
  • List the content again
  • Un-mount the /dev/sdc1 partition and list the content again
  • Now mount the /dev/sdb1 partition and list the content
  • Again create a test directory and file. Use different name for file and directory
  • List the content
  • Un-mount the /dev/sdb1 partition and list the content again

Following figure illustrates this exercise step by step

temporary mount

As above figure shows whatever action we performed in mount directory was actually performed in respective partition.

Temporary mount option is good for partitions which we access occasionally. If we access partition on regular basis then this approach will not be helpful. Each time we reboot the system all temporary mounted resources are get un-mounted automatically. So if you have a partition which is going to be used regularly, mount it permanently.

Mounting partitions permanently

Each resource in file system has a unique ID called UUID. When mounting a partition permanently we should use UUID instead of its name. From version 7, RHEL also uses UUID instead of device name.

The UUID stands for Universally Unique Identifier. It is a 128-bit number, expressed in hexadecimal (base 16) format.

If you have a static environment, you may use device name. But if you have dynamic environment, you should always use UUID. In dynamic environment device name may change each time when system boot. For example we attached an additional SCSI disk in system; it will be named as /dev/sdb. We mounted this disk permanently with its device name. Now suppose someone else removed this disk and attached new SCSI disk in the same slot. New disk will also be named as /dev/sdb. Since name of old disk and new disk is same, new disk will be mounted at the place of old disk. This way, device name could create a serious problem in dynamic environment. But issue can solve with UUID. No matter how we attach the resource with system, its UUID will remain always fix.

If you have static environment, you may consider device name to mount the partition. But if you have dynamic environment, you should always use UUID.

To know the UUID of all partitions we can use blkid command. To know the UUID of a specific partition we have to use its name as argument with this command.

blkid command

Once we know the UUID, we can use it instead of device name. We can also use copy and paste option to type the UUID. Following figure illustrates the temporary mounting process using UUID.

mount through the uuid

When system boots, it looks in /etc/fstab file to find out the partitions which need to be mount automatically. By default this file has entry for those partitions which were created during the installation. To mount any additional partition automatically we have to make an entry for that partition in this file. Each entry in this file has six fields.

cat fstab file

Number Filed Description
1 What to mount Device which we want to mount. We can use device name, UUID and label in this filed to represent the device.
2 Where to mount The directory in main Linux File System where we want to mount the device.
3 File system File system type of device.
4 Options Just like mount command we can also use supported options here to control the mount process. For this tutorial we will use default.
5 Dump support To enable dump on this device use 1. Use 0 to disable dump.
6 Automatic check Whether this device should be checking while mounting or not. To disable use 0, to enable use 1 (for root partition) or 2 (for all partitions except root partition).

Let’s make some directories to mount the partitions which we have created recently

mkdir rhcelab dir

Now open the fstab file and make entries for partitions. We can also use copy and paste operation here to type the UUID.
To use copy and paste operation, open another terminal and run blkid command. Now copy UUID of partition from second terminal and paste in fstab file
which is open in first terminal. Once you are done close the second terminal.

fstab entry

As I mentioned earlier we can also use device name or label here. Let’s use device name for remaining partitions and save the file.

fstab entry

After saving always check the entries with mount –a command. This command will mount everything
listed in /etc/fstab file. So if we made any mistake while updating this file, we will get an error as the output of this file.

To explain it more practically I intentionally made some typo in file.

mount -a error

If you get any error as the output of mount –a command, open /etc/fstab file again and correct the corresponding errors.

fstab file entry

Run mount –a command again and if there is no error, reboot the system.

reboot command

The df –h command is used to check the available space in all mounted partition. We can use this command to verify that all partitions are mounted correctly.

df -h command

Above output confirms that we have successfully mounted all partitions.
We created few files and folder in /dev/sdb1 and in /dev/sdc1 partitions while doing the practice of temporary mount.
Let’s check that files and folder are still there.

listing temporary data

We have successfully completed this practice. Now it’s time to clean up the system for next practice.

How to delete MBR partitions

To delete a partition rm sub-command is used. Before we delete a partition it must be un-mounted. We cannot delete a mounted partition. Let’s see it practically.

delete partition error

Un-mount all partitions which we created in this exercise

umount partition

Run parted /dev/sdc command again

parted dev sdc command

The rm sub-command needs partition number. We can view partition number from print command.

parted rm command

We have removed all primary and logical partitions. Now remove extended partition and exit from utility

parted rm command

Delete GPT partitions

Deleting a GPT partition is as same as deleting a MBR partition. Initiate parted command with GPT disk (/dev/sdb) and use print command to view the number of partition and use rm sub command to delete that partition.

remove gpt partition

We have deleted all partitions from both disks but they still contain MBR and GPT records. If we use any disk management utility such as fdisk, gdisk or parted, the existing record will be used.

To remove current record we have to overwrite the area in disk which contains these records with raw data. For this purpose we took the backup of first 1Mb from both disks. Let’s restore that data back.

restore data back

Finally remove the mount directory and copy the original fstab file back.

If you haven’t taken the backup of original fstab file, remove all entries from this file which you made.

remove the fstab entry

Now reboot the system and use df –h command again to verify that all partitions which we created in this exercise are gone.

df -h command

That’s all for this part. In next part we will learn how to create and manage swap partition in Linux.

Full Version EX300 Dumps

Try EX300 Dumps Demo

Categories
RHCE 7 Study Guide

Manage Linux Disk Partition with gdisk Command

This tutorial explains how to manage GPT disk partitions and convert MBR disk in GPT disk from gdisk command in detail. Learn how to create, list, format, mount (temporary and permanent), remove and delete GPT partitions in Linux step by step with practical examples.

For this tutorial I assume that you have either non-partitioned disk space or have a separate disk for exercise. If you are using virtual program (such as VMware or Virtual Box) for the practice, I suggest you to add a new virtual hard disk. To learn how to add new virtual disk in VMware please see the first part of this tutorial.

This tutorial is the third part of our article “Linux Disk Management Explained in Easy Language with Examples”. You can read other parts of this article here.

Linux Disk Management Tutorial

This is the first part of this article. This part explains basic concepts of Linux disk management such as BIOS, UEFI, MBR, GPT, SWAP, LVM, RAID, primary partition, extended partition and Linux file system type.

Manage Linux Disk Partition with fdisk Command

This is the second part of this article. This part explains how to create primary, extended and logical partitions from fdisk command in Linux step by step with examples.

Linux Disk Management with parted command

This is the fourth part of this article. This part explains how to create primary, extended, logical and GPT partitions from parted command in Linux step by step with examples.

How to create SWAP partition in Linux

This is the fifth part of this article. This part explains how to create swap partition in Linux with examples including basic swap management tasks such as how to increase, mount or clear swap memory.

Learn how to configure LVM in Linux step by step

This is the sixth part of this article. This part explains basic concepts of LVM in detail with examples including how to configure and manage LVM in Linux step by step.

How to configure RAID in Linux Step by Step Guide

This is the last part of this article. This part explains basic concepts of RAID in detail with examples including how to configure and manage software RAID in Linux step by step.

Creating GPT Partitions



For this exercise we added one additional virtual disk in our system. We can list all attached hard disks with fdisk –l command.

fdisk -l command

As above figure shows there are two un-partitioned disks /dev/sdb and /dev/sdc. To figure out which disk we added recently check its sequence number. Recently added disk will be last in sequence. Sequence starts with sda and goes up to the last disk. For example if there are three SCSI disk, first disk will be sda and last disk will be sdc.
We will use /dev/sdc disk in this tutorial.

Although we can use fdisk command to create GPT partitions, but GPT support in fdisk is added recently and not in stable stage.
So it is better to use gdisk utility which is specially created for GPT disk.

Let’s initiate gdisk command. This command needs the name of disk where we want to create the partition as its argument.

gdisk command

We can use only one partition scheme from MBR or GPT. If disk is used for MBR partition previously or it contains any MBR partition currently, we will get above warning message.

We used the same disk /dev/sdc in second part of this article to practice the MBR partition with fdisk command. At the end of that practice we deleted all partitions but kept MBR record in hard disk.

Before we start creating partitions let’s view the current layout of disk with p command.

gdisk p command

The p command also provides information about available space in hard disk to create a new partition. If last partition ends before the last sector of hard disk, we have available space to create new partition. As we can see in above output currently no value is available in partition section that means there is no partition available and entire disk space is available for partition.

Type n and press Enter key to create new partition

gdisk n command

In GPT partition scheme we are allowed to create maximum 128 partitions.



Due to huge numbers of supported partition, GPT does not distinguish partitions in primary, extended and logical partitions. In GPT all partitions are equal.

To learn more about GPT partition scheme, see the first part of this tutorial which explains this and other relative topics in detail with examples.

Type the partition number (or keep the default number) and press Enter key.

Type the first available sector for partition (or accept the default sector) and press Enter key.

Type the last available sector for partition. Alternatively we can use KiB, MiB or GiB units to define the size of partition. (To learn what are the differences between KiB, MiB, GiB and KB, MB, GB, see the first part of this article.)

Each partition uses a special marking known as partition system identifier. This marking is used to identify the purpose of partition. To print all available partition types we can use l command.

Unless we change the type of any partition it is marked as Linux Standard partition. But if requires, we can change it here. In next part of this tutorial we will learn how to change the partition type, for this part let’s keep the default and press Enter key.

Following figure illustrates above process step by step

gdisk new partition

We can verify the creation of partition with p command

gdisk print command

Following same process create two more partitions

gdisk create new partition

Following the same way we can create more partitions (maximum allowed 128) as per requirement. To view the available space for new partition use p command.

gdisk print command

As above output shows there are total 4194270 sectors available in hard disk. From which we used only 2508799 sectors in partitions. 1685471 sectors are still available for partitions.

Just like fdisk, gdisk also keep all changes in memory, nothing will be saved in hard disk until we confirm the same.

To accept the change type w and press Enter key

gdisk save partition

Since changes once written in disk cannot be reverted, gdisk will ask for final confirmation. This is the important feature. If you made any mistake in above process, just type N here and nothing will be changed in hard disk.

If we are working with a disk which contains mounted partitions, we may get following warning.

WARNING: Re-reading the partition table failed with error 16: Device or resource busy. The kernel still uses the old table. The new table will be used at the next reboot or after you run partprobe(8) or kpartx(8) Syncing disks.

This message indicates that gdisk cannot update the in-memory kernel partition table because disk is busy (mounted). Kernel reads partition table when system boots. So the kernel will be updated about this change at next reboot automatically. Meanwhile if we want to update the kernel immediately, we have to use partprobe command which force kernel to reread the partition table.

Run following command.

partprobe command

Replace /dev/sdc with your disk name.

We have successfully created the partitions. To view the partitions use fdisk –l command.

fdisk gpt command

These partitions are useless unless we put a file system in them. File system is a logical container which allows us to store files and directories. To learn more about file system see the first part of this tutorial.

How to create file system

To create a file system in partition we have to format it with supported file system. To format a partition following command is used.

#mkfs –t [supported file system type] [partition]

Some common supported file systems are ext3, ext4 and xfs. Let’s format the recently created partitions with these file systems.

File system type ext3 partition /dev/sdc1

mkfs ext3

File system type ext4 partition /dev/sdc2

mkfs ext4

File system type xfs partition /dev/sdc3

mkfs xfs

If disk was formatted with xfs system previously, mkfs will detect that and display a warning message. To ignore this message and create new file system use –f option.

Now partitions have file system, can we use them for data storage now? No, even though partitions are ready to use, we cannot use them until they are connected with primary directory structure (Main Linux file system).

Linux file system (primary directory structure) starts with root (/) directory and everything goes under it or its subdirectories. We have to mount partitions somewhere under this directory tree. We can mount partitions temporary or permanently.

Mounting partitions temporary

Following command is used to mount partition temporary.

#mount [what to mount] [where to mount]

Mount command accepts several options and arguments which I will explain separately in another tutorial. For this tutorial this basic syntax is sufficient.

what to mount :- This is the partition.

where to mount :- This is the directory which we will use to access the mounted resource.

Once mounted, whatever action we will perform in mounted directory will be performed in mounted resources. Let’s understand it practically.

  • Create a mount directory in / directory
  • Mount /dev/sdc1 partition
  • List the content
  • Create a test directory and file
  • List the content again
  • Un-mount the /dev/sdc1 partition and list the content again
  • Now mount the /dev/sdc2 partition and list the content
  • Again create a test directory and file. Use different name for file and directory
  • List the content
  • Un-mount the /dev/sdc2 partition and list the content again

Following figure illustrates this exercise step by step

temproary mount

As above figure shows whatever action we performed in mount directory was actually performed in respective partition.

Temporary mount option is good for partitions which we access occasionally. If we access partition on regular basis then this approach will not work. Each time we reboot the system all temporary mounted resources are get un-mounted automatically. So if we have a partition which is going to be used regularly, we should mount it permanently.

Mounting partitions permanently

Each resource in file system has a unique ID called UUID. When mounting a partition permanently we should use UUID instead of its name. From version 7, RHEL also uses UUID instead of device name.

The UUID stands for Universally Unique Identifier. It is a 128-bit number, expressed in hexadecimal (base 16) format.

If you have a static environment, you may use device name. But if you have dynamic environment, you should always use UUID. In dynamic environment device name may change each time when system boots. For example we attached an additional SCSI disk in system; it will be named as /dev/sdb. We mounted this disk permanently with its device name. Now suppose someone else removed this disk and attached new SCSI disk in the same slot. New disk will also be named as /dev/sdb. Since name of old disk and new disk is same, new disk will be mounted at the place of old disk. This way, device name could create a serious problem in dynamic environment. But this issue can be solved with UUID. No matter how we attach the resource with system, its UUID will remain always fix.

If you have static environment, you may consider device name to mount the partition. But if you have dynamic environment, you should always use UUID.

To know the UUID of all partitions we can use blkid command. To know the UUID of a specific partition we have to use its name as argument with this command.

blkid commnad

Once we know the UUID, we can use it instead of device name. We can also use copy and paste option to type the UUID.

  • Use blkid command with partition name to print the UUID of partition.
  • Copy the UUID of partition.
  • Use mount command to mount the partition. Use paste option instead of typing UUID.

Following figure illustrates above steps

mount using uuid

When system boots, it looks in /etc/fstab file to find out the partitions which need to be mount automatically.
By default this file has entry for those partitions which were created during the installation.
To mount any additional partition automatically we have to make an entry for that partition in this file.
Each entry in this file has six fields.

default fstab file

Number Filed Description
1 What to mount Device which we want to mount. We can use device name, UUID and label in this filed to represent the device.
2 Where to mount The directory in main Linux File System where we want to mount the device.
3 File system File system type of device.
4 Options Just like mount command we can also use supported options here to control the mount process. For this tutorial we will use default options.
5 Dump support To enable dump on this device use 1. Use 0 to disable dump.
6 Automatic check Whether this device should be checking while mounting or not. To disable use 0, to enable use 1 (for root partition) or 2 (for all partitions except root partition).

Let’s make some directories to mount the partitions which we have created recently

mkdir command

Now open the fstab file and make entries for partitions. We can also use copy and paste operation here to type the UUID.
To use copy and paste operation, open another terminal and run blkid command. Now copy UUID of partition from second terminal
and paste in fstab file which is opened in first terminal. Once you are done close the second terminal.

fstab copy paste uuid

As I mentioned earlier we can also use device name or label here. Let’s use device name for remaining partitions and save the file.

fstab gdisk partition entry

After saving always check the entries with mount –a command. This command will mount everything listed in /etc/fstab file. So if we made any mistake while updating this file, we will get an error as the output of this command.

If you get any error as the output of mount –a command, correct that before rebooting the system. If there is no error, reboot the system.

mount -a command

The df –h command is used to check the available space in all mounted partition. We can use this command to verify that all partitions are mounted correctly.

df -h command

Above output confirms that all partitions are mounted correctly. We put some data in /dev/sdc1 and in /dev/sdc2 while these partitions were mounted temporary. Let’s verify that is available in respective partitions.

listing partition

We have successfully finished this practice. Now it’s time to clean up the system for next practice.

How to delete partitions

We cannot delete a mounted partition. Un-mount all partitions which we created in this exercise

unmount partition

Run gdisk /dev/sdc command again

gdisk commnad

The d command is used to delete a partition. If there are multiple partitions, command will ask for partition number which we want to delete. Delete all partitions one by one.

delete gpt partition

As we know whatever change we made in this utility will not apply until we save them with w command. Use p command to view the changes. If everything is fine, confirm the change and exit form gdisk.

gdisk delete partition

Finally remove the mount directory and copy the original fstab file back. If you haven’t taken the backup of original fstab file, remove all entries from this file which you made.

restore fstab file

Now reboot the system and use df –h command again to verify that all partitions which we created in this exercise are gone.

df -h command

Right now we have deleted all partitions from disk but this disk still contains valid GPT record with empty partition table.

fdisk -l

We cannot create MBR partition in this disk until we convert it back to MBR and vice versa a MBR disk cannot be used for GPT partition. Remember we started this tutorial with a MBR disk. So we had to covert that disk in GPT disk. If we use this disk in next practice we will be able to create only GPT partition. To make this disk blank again we have to replace first Mb of this disk with raw data. In second part of this tutorial when we started to work with this disk we took the backup of first Mb. Let’s restore that data back to the disk.

restore disk

In second part of this article we took the backup of first MB in /root/backup/mbrbackupfile.

Now this disk is reverted back in its original state. It doesn’t contain any record or partition table. This disk will appear as a blank disk in any disk management utility.

That’s all for this part. In next part we will learn how to create and manage partitions with parted command.

Full Version EX300 Dumps

Try EX300 Dumps Demo

Categories
RHCE 7 Study Guide

How to Configure Apache Web Server in Redhat Linux

This tutorial explains how to configure Apache Web Server in Linux step by step with practical examples. Learn how to configure virtual hosts, configure user’s home directory as web root, change document root, deploy a basic CGI application and allow HTTP & HTTPS traffic through Linux firewall and SELinux.

Apache is the most popular, secure, robust, reliable and powerful web server.
Apache is used by more websites than all other web servers combined.

In this tutorial I will use three systems Server, linuxclient and windowclient from our LAB environment.
I will configure Apache Web Server on Server system and test from inuxclient and windowclient system. If you want to check the network
topology used in this article please check following article. Lab set up for RHEL practice

Installation of Apache

Two packages are required for Apache server

  • httpd
  • mod_ssl
  • elinks

httpd package install Apache web server.

mod_ssl is the additional package which required to create secure websites

elinks is the additional package for text based web browser.

If you have yum repository configured use following command to install Apache web server with additional package

# yum install –y httpd mod_ssl

yum-httpd

# yum install elinks

yum-elinks

Or you can do it in more simpler way by using groupinsatall. With following command you can install mandatory and all default packages.

# yum groupinstall \"Web Server\"

yum-groupinstall-httpd

If yum repository is not configured use rpm command to install necessary RPM. Mount installation disk of RHEL6 in media folder and move in Packages folder.

cd-media-packages

Run following command to install httpd

#rpm -ivh httpd* --nodeps --force

rpm-httpd

Run following command to install mod_ssl

#rpm -ivh mod_ssl* --nodeps --force

rpm-mod-ssl

Run following command to install elinks

#rpm -ivh elinks* --nodeps --force



rpm-elink

Verify that the packages were installed correctly

verfiy-rpm

Run following command to start service when the system boots

chkconfig-httpd-on

Start httpd service

arp-scok-add-fail

httpd service requires at least one active network connection, if it does not detect any active connection it will throw following message

Starting httpd: httpd: apr_sockaddr_info_get() failed for Server

httpd service try to resolve system IP with domain name. It will throw following error, If it fails to resolve.

httpd: Could not reliably determine the server\'s fully qualified domain name, using 127.0.0.1 for ServerName

In real world DNS Server are used to bind IP address with domain name. In LAB environment where we have limited systems , we can also use hosts file for this purpose.

Open /etc/sysconfig/network

etc-sysconfig-network

Change hostname to Server.example.com and save the file

sysconfig-entry

Reboot the system

reboot

Verify that hostname is changed

ipaddress-hostname-server

Before we update hosts file on server also verify the hostname and ip address of linuxclient

ipaddress-hostname-client

Now on server open /etc/hosts file

etc-hosts

Add entry for server and linuxclient system and save the file

hosts-entry

Verify the network card status

service-network-status

Now restart the httpd service

service-httpd-restart

Default versions of httpd create a generic web server service which is sufficient for most basic operations. Once httpd service is running start web browser and enter a URL http://localhost

apache-test-page-server

Same testing can be done form text based web browser ,If GUI is unavailable.

# elinks 127.0.0.1

elinks-localhost

We got Apache test page which confirm successful Apache configuration.

apache-test-page-command-line

Exit from the ELinks browser. Press Q, and when the Exit ELinks text menu appears, press Y to exit Elinks.

We have successfully installed Apache Web Server. So far its a generic web server service, to make it a regular and a secure web server, we need to configure it.

IPTABLES Firewall rules for web Server



Default installation of Apache web server use port 80 for HTTP traffic and 443 for HTTPS traffic.

You can create custom iptables rule to limit access to one or more networks or systems. For example following rules allows access to every computers on 192.168.1.0 network except one with IP address 192.168.1.25 over port 80.

-A INPUT -m state --state NEW -m tcp -p tcp -s 192.168.1.25 --dport 80 -j REJECT
-A INPUT -m state --state NEW -m tcp -p tcp -s 192.168.1.0/24 --dport 80 -j ACCEPT

We have a well written article for IPTABLES firewall, use that to create custom firewall rules for web server. For this article create rules to allow all traffic on port 80 and 443.

#iptables -A INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT
#iptables -A INPUT -m state --state NEW -m tcp -p tcp --dport 443 -j ACCEPT

iptables-httpd-rules

Save the firewall rules you have just created and restart the iptables service

# service iptables save
# service iptables restart

iptables-save-restart

Until you change the value of DocumentRoot directive in httpd.conf file , Apache looks for web pages in default location /var/www/html directory.

To get your web server up and running, all you need to do is to transfer the web pages or websites in /var/www/html directory.

We will make two websites for testing. We will use most simple html web page for testing.

Make two directories mysite1 and mysite2 in /var/www/html folder

mkdir-mysite

Make a sample html page in both directories

cat-index-htm

Our sample websites are ready for use.

Configure SELinux for web server

Use following command to check all associated SELinux Booleans with httpd

getsebool-httpd

Most of these options are self explained and relate to interactions with other services. for example httpd_enable_ftp_server allow Apache to act as an FTP server, which is out of scope for this article.

getsebool-httpd-list

Default enabled SELinux options



Booleans Descriptions
httpd_builtin_scripting Used to provide permission for php content
httpd_dbus_avahi Supports access from HTTP services
httpd_enable_cgi Allows HTTP services to execute GCI scripts
httpd_tty_comm Enables communication with controlling terminals
httpd_unified Supports read/write/execute access by httpd_t files

httpd_enable_homedirs supports access to files from user home directories, default value is off. We will enable it later in this article.

Default enabled options are sufficient to provide basic web services , you do not need to make any changes. But you need to configure SELinux contexts, user context is system_u and the type is http_sys_content_t.

Check the current context of the files

#ls -Z /var/www
#ls -Z /var/www/html

ls-z

We need to set context of any newly created file or directory for the web server user to be able to access it.

Use the chcon command to change the context

#chcon -R -u system_u /var/www/html
#chcon -R -t httpd_sys_content_t /var/www/html/

Verify that all the context fields have been changed correctly

#ls -Z /var/www/html

chcon

Test these websites form linuxclient system [make sure client system have elinks rpm installed]

elinks 192.168.1.1/mystie1/index.htm

start-elinks

Verify the site

elink-test

Close elinks

eixt-from-elink

On window client open browser and type 192.168.1.1/mysite2/index.htm

internet-explore

We have set up Apache web server with default configuration.

Back up the default httpd.conf file on a safe location.

mkdir-backup

Open the /etc/httpd/conf/httpd.conf

vi-httpd-conf

This is the main configuration file for httpd web service and completely usable right out of the box for generic web service.

This file is grouped in three sections and each section is well commented

  • Global environment directives that control the whole operation of Apache server process.
  • Directives that define the parameters of the main or default server, which responds to requests that are not handled by a virtual host. These directives also provide default values for the settings of all virtual hosts.
  • Settings for virtual hosts, which allow Web requests to be sent to different IP addresses or hostnames and have them handled by the same Apache server process.

To make navigation easier, turn on line number ESC Key + : +set nu + Enter Key

set-nu

Host-Based Security

If server have multiple IP address, you can limit the IP address and port on which the server can listen for incoming connection. By default server listen on port 80, but can be update as well.

default-listen

For example to limit server only to listen on IP address 192.168.1.1 with port 80 Set Listen Directive

Listen 192.168.1.1:80

listen-changed

Now Server will listen only on the 192.168.1.1 IP address on port 80 for incoming requests.

Apache also let you configure the hosts which should be allow to access to web server. <Directory> section allow you to specify the hosts base security.

Value Example Descriptions
Allow from all Default value, allow access from all hosts
Allow from [IP Address] Allow from 192.168.1.10 To allow only a specific IP or host
Allow from [Host name] Allow from linuxclient To allow only specific host
Allow from [Network] Allow from .example.com To allow only example.com network
Allow from [Network] 192.168.1.0/24
192.168.1.0/255.255.255.0
To allow only from 192.168.1.0 network
Deny from all Deny access from all hosts
Deny from [IP Address] Deny from 192.168.1.10 To Deny only a specific IP or host
Deny from [Host name] Deny from linuxclient To deny only specific host
Deny from [Network] Deny from .example.com To deny only example.com network
Deny from [Network] 192.168.1.0/24
192.168.1.0/255.255.255.0
To deny only from 192.168.1.0 network

For exam remember

  • If DNS service is unreliable use IP address.
  • When specify domain name to allow or deny from, make sure you include the leading dot[.]
  • When specify a subnet, there is no ending dot[.] at last octet.
  • Order play the most important role, when set allow or deny access.
  • If you set Order allow, deny Only those host names or IP addresses associated with allow directive are allowed access. All remaining hosts or IP address would be denied.
  • If you set Order deny, allow Only those host names or IP addresses associated with deny directive are denied access. All remaining hosts or IP address would be allowed.

Default value is Allow from all

default-allow-from-entry

In our LAB setup we have two clients linuxclient [192.168.1.10], and windowclient [192.168.1.20]. Lets allow access only to linuxclient system.

allow-from-entry

Save the file and restart the httpd service

httpd-service-restart

Try to access same websites again from both client systems. This time linuxclient system would be able to access web server as usual, but on windowsystem you will be denied

windowclient-error

User-Based Security

User based authentication provides a way to allow only certain users or group to access web server.

We can use following options to configure user based authentication.

Options Descriptions
AuthType Defines the authentication method
AuthName Comment for the users
AuthUserFile File used to define username and password
AuthGroupFile File used to define groups
Require Specifies the users or groups that can log in

Open httpd.conf file again

vi-httpd-conf

In last practice we have restricted all hosts except one

allow-from-entry

Before we do this exercise lets allow all hosts to access the web server.

default-allow-from-entry

In < directory > section add following and save the file

AuthType Basic
AuthName “Password Restricted Area”
AuthUserFile /etc/httpd/userauthfile
Require user rhceuser01

require-user1

Use htpasswd command to create a userauthfile, that will be holds user accounts.

# htpasswd -cm /etc/httpd/userauthfile rhceuser01

useradd-rhceuser01

-c Create new file and populates it with first user and password.

-m Passwords will be encrypted in MD5 before saving

Do not use -c options for creating subsequent users, otherwise it will completely override the file. Use -c option only first time for first user, from second users do not use -c option.

Restart the web server

service-httpd-restart

Try again to access same sites from client, this time it will ask for user name and password

ask-for-pass

If you cancel or use wrong user name and password, access would be denied

auth-require

Use correct user name and password

type-pass

Upon successful authentication access would be granted

sucess-get

Secure web server with .htaccess file

In previous exercise we have secured entire sites. However in real life you want to allow certain parts of site publicly accessible, while other by only authenticated users. For this we will use .htaccess file.

Open /etc/httpd/conf/httpd.conf file again

vi-httpd-conf

Change AllowOverride directive value to authconfig

allow-override-none

In previous example we did user base authentication

Remove that and save the file

allow-override-authconfig

Make a directory and file under mysite1

mkdir /var/www/html/mysite1/salary

mkdir-salary

Suppose that salary folder contains the salary sheet of employees and we want to allow only hr group to access it.

Create a .htaccess file in the salary folder

#vi /var/www/html/mysite1/salary/.htaccess

vi-htaccess

Add followings and save the file

AuthType Basic
AuthName “Password Restricted Area”
AuthGroupFile /etc/httpd/rhcegroupfile
Require group hr

htaccess-entry

Now only users from hr group, defined in /etc/httpd/rhcegroupfile can assess this.

Create few more accounts

useradd-hruser

Create rhcegroupfile, this file will hold entry for groups

vi-rhcegroup

Add user accounts in hr group and save file

rhcegroup-entry

Update the SELinux context of .htaccess file

chcon-htaccess

Restart the web server

httpd-service-restart

Try again to access site for client, access to other parts of site are allowed except salary

mysite-homepage

To access salary folder you need to provide user name and password

htaccess-ask-pass

Upon successful authentication access would be granted

salary-sheet-htm

Configure public_html folder in user home directory

httpd.conf file includes a commented directive UserDir public_html just under the default UserDir disable , when it\’s enabled, it allows users to browse and access the public_html directory within their home folder.

Open /etc/httpd/conf/httpd.conf file

vi-httpd-conf

Comment the default directive

userdir-disable

Uncomment the UserDir public_html directive and save the file

userdir-public-html

Now anyone will have access to web pages that a user puts in his ~/public_html directory. This option can be useful if you want each user to share files over the Web. For this option you need to make users home directory executable for world. You also need to make public_html readable and executable. By default this option is disable because this requires a bit of security compromise. So unless you need to be able to share content out of a users home directory, do not enable this option. If you have to enable it in real world, take all caution in setting up this option.

Create a new normal user

useradd-rh-user1

Make public_html folder under his home folder and create a test file in public_html folder

mkdir-public-html

Change file permission

chmod-public-html

Enable SELinux Boolean associated with home directory

set-bool-http-enable-homedir

Restart the web server

httpd-service-restart

Access it from client system by typing 192.168.1.1/~rh_user1/index.htm

access-home-dir

How to create virtual hosts

Virtual host feature of Apache allows you to define multiple web sites on single IP address. For Virtual hosts configuration following options are required

NameVirtualHost Hostname or IP address of the virtual host
ServerAdmin Email address of the webmaster
DocumentRoot Location of the directory, which holds virtual host files
ServerName URL of the virtual host
ErrorLog Location for the error log
CustomLog Location for a custom log

Suppose that we want to host a new website example.com in virtual host.

Make new directory which will hold our new site

mkdir-webdata

Make a sample file in new site

mkdir-webdata-cat-sample-file

Update SELinux context

chchon-webdata

Open main configuration file again

vi-httpd-conf

By default NameVirtualHost directive is disabled

namehost-commented

Enable it

namehost-uncomment

At the end of file in virtual host section add following lines and save the file

<VirtualHost *:80>
ServerAdmin webmaster@example.com
DocumentRoot /webdata/example.com
ServerName example.com
ErrorLog logs/example.com-error_log
CustomLog logs/example.com-access_log common
</VirtualHost>

virtual-host-entry

If you have DNS server configured update the zone files, otherwise update the hosts files . On server open the /etc/hosts file

etc-hosts

Add entry for new virtual host site and save the file

host-entry-server

Restart the httpd service

httpd-service-restart

On linuxclient system you also need to update the hosts file before testing. Open hosts file

vi-etc-host-linuxclient

Add entry for new virtual host site and save the file

hosts-entry-linuxclient

Now use elinks command to browse new site

elink-example-com

Test page confirms that we have successfully configured virtual host.

virtual-host-testing-client

How to deploy a basic CGI application

In this section we will deploy a basic CGI application. RHCE exam objective \”Deploy a basic CGI application\”, does not test your programming skills, so you need not to worry about programming language. You only need to know the method.

Create a directory to hold your web application:

# mkdir /var/www/webapp

mkdir-webapp

Make a new sample perl file

vi-hello-pl

Add following in file and save the file. [This will make a sample perl script to print hello, world. Based on Apache manual]

#!/usr/bin/perl
print \"Content-type: text/html\\n\\n\";
print \"Hello, World!\";

hello-pl-entry

Update file permission and SELinux context

chmod-chcon-webapp

Open configuration file

vi-httpd-conf

At end of file add following and save the file

ScriptAlias /webapp \"/var/www/webapp\"
<Directory \"/var/www/webapp/\">
Options ExecCGI FollowSymLinks
Order allow,deny
Allow from all
</Directory>

cgi-bin-entry

Restart the web server

httpd-service-restart

On client now you can access this CGI application.

webapp-testing

Configure secure virtual host

In this last section of tutorial we will configure a secure virtual host with self signed certificate. Make a directory to host our secure site

mkdir-secure-host1

Make a sample index.htm file in it

cat-secure-index

Change file permission and Update SELinux context

chcon-secure

Open main configuration file /etc/httpd/conf.d/ssl.conf

vi-ssl-conf

Make sure Listen Directive remain on

listen-443

Add new Directive NameVirtualHost *:443 just above the <VirtualHost _default_:443> and replace _default_ with * in <VirtualHost _default_:443> tag.Uncomment the DocumentRoot and ServerName directives.

namevirtualhost

Change the value of directives and save the file

ssl-uncomment-documentroot

Move in certificate holder directory /etc/pki/tls/certs and use genkey command to generate new certificate and private key for secure site

genkey

Select Next and press enter on Keypair generation window

keypair-next

During the exam always choose minimum available key size. Even smaller key size can take up to several minutes and in exam every minute is precious. Select 512 and move to Next tab and press enter

choose-key-size

Wait while key generates

genrating-key

Select No and press enter on Generate CSR window

genrate-crs

Keep default details and select Next and press Enter

details-for-certificate

We have sucessfully created the certificate ,now we to update the hosts file on server

host1-host-entry

Restart the httpd service

httpd-service-restart

On client updated the hosts file

linuxclient-host1-entry-host-file

To test secure site open the web browser and type https://host1.example.com/index.htm in URL

untursted-connection

You will see Untrusted connection screen Unless you purchase an actual certificate from a certificate authority (CA) such as VeriSign and Thawte. For testing we do not need third party certificate, as we have self signed certificate. Click on I Understand the Risks and Click on Add Exception

add-exception

Click on confirm security exception

confirm-security

Test page confirms that we have successfully configured the secure virtual host

secure-test-page

To test secure sites form elinks test based browser we need to comment two standard directives

open /etc/elinks.conf file

linuxclient-vi-elinks-conf

You need to comment these directives

linuxclient-elinks-conf-uncommented

Comment them and save the file

linuxclient-elinks-conf-commented

Now you can access secure sites form elinks as well

linuxclient-elinks-test-host-index

Test page confirms our secure web hosting

linuxclient-elinks-test-page

When you restarts the httpd service, restart process actually stop the service from running before starting it again. This process hardly take few seconds that is ok for testing purpose but in real life where thousands of people are hitting your site, you can\’t afford any outage even its in seconds. In that situation you can use reload option which allows the main configuration to reread without the actually bringing service down.

#service httpd reload

One more important option which should know for real world is graceful

#service httpd graceful

This option reread the new configuration file without disconnecting any currently connected users. Only drawback of this option is that the currently active connections use the old configuration file until they terminate their connection and reconnect.

One more cool options is configtest, when used , service parses the main config file for any errors and reports back if something is found. It\’s your helping hand during the exam to detect any syntax errors in configuration file.

# service httpd configtest
Syntax OK

If this command detect any syntax related error it return with that, otherwise it return with Syntax ok.

That\’s all for this article.

Full Version EX300 Dumps

Try EX300 Dumps Demo

Categories
RHCE 7 Study Guide

Manage Linux Disk Partition with fdisk Command

This tutorial explains how to manage MBR disk partition (Primary, Extended and Logical) and GPT disk partition in Linux from fdisk command with practical examples. Learn how to create, list, format, mount (temporary and permanent), remove and delete MBR & GPT partitions step by step in detail.

For this tutorial I assume that you have either non-partitioned disk space or have a separate disk for exercise.
If you are using virtual program (such as VMware or Virtual Box) for the practice,
I suggest you to add a new virtual hard disk. To learn how to add new virtual disk in
VMware please see the first part of this tutorial.

This tutorial is the second part of our article “Linux Disk Management Explained in Easy Language with Examples”. You can read other parts of this article here.

Linux Disk Management Tutorial

This is the first part of this article. This part explains basic concepts of Linux disk management such as BIOS, UEFI, MBR, GPT, SWAP, LVM, RAID, primary partition, extended partition and Linux file system type.

Manage Linux Disk Partition with gdisk Command

This is the third part of this article. This part explains how to create GPT (GUID partition table) partitions from gdisk command in Linux step by step with examples.

Linux Disk Management with parted command

This is the fourth part of this article. This part explains how to create primary, extended, logical and GPT partitions from parted command in Linux step by step with examples.

How to create SWAP partition in Linux

This is the fifth part of this article. This part explains how to create swap partition in Linux with examples including basic swap management tasks such as how to increase, mount or clear swap memory.

Learn how to configure LVM in Linux step by step

This is the sixth part of this article. This part explains basic concepts of LVM in detail with examples including how to configure and manage LVM in Linux step by step.

How to configure RAID in Linux Step by Step Guide

This is the last part of this article. This part explains basic concepts of RAID in detail with examples including how to configure and manage software RAID in Linux step by step.

We can list all attached hard disks with fdisk –l command.

fdisk -l command

As above figure shows there are two un-partitioned disks /dev/sdb and /dev/sdc available.
To figure out which disk we added recently check its sequence number. Recently added disk will be the last disk in sequence
(sda, sdb and sdc). In our example it is /dev/sdc. We will use this disk for the practice.

Backup before start



We should always take the backup of associate files before making any system change. Backup copy allows us to revert in original state if anything goes wrong. Run following commands to create a backup copy of files which will change in this practice.

dd command

In first command we created a directory to store the backup files.

In second command we took the backup of first megabyte of raw blocks of /dev/sdc hard disk. Let’s understand this command in detail.

dd :- The dd (disk duplicator) command is used to copy or backup the low level data.

if=/dev/sdc :- This is the first option. This option accepts source location as argument.
In this example I copied from /dev/sdc disk. Change the disk name with the disk name which you want to use for the practice.

of=/root/backup/mbrbackupfile :- This is the second option.
This option accepts destination location as argument. In this example I copied at /root/backup/mbrbackupfile.
The mbrbackupfile is the name of file. You can use any descriptive name here.

bs=1 :- This is the third option. It is used to define the size of block. 1M stands for one megabyte.

count=1 :- This is the last option. It is used to define the number of block which we want to copy.

In third command we took the backup of /etc/fstab file. This file contains partitions information. This information is used to mount the file system while system boots.

Now we are ready to create the MBR partitions in /dev/sdc disk.

Creating MBR Partitions



Let’s initiate fdisk command. This command needs the name of disk where we want to create the partition as its argument.

fdisk dev sdc command

There are two messages listed before the fdisk command prompt.

Changes will remain in memory only, until you decide to write them. Be careful before using the write command.

This massage says whatever change we will make here will not apply until we confirm the change with write command. If you make any mistake in this process, exit from fdisk utility without running write command and nothing will change in hard disk.

Device does not contain a recognized partition table building a new DOS disklabel with disk identifier 0x7a53c114.

This message says currently there is not partition table available in this disk. This is true because we are working with a new hard disk. If hard disk already contains partitions, they will be listed here.

We can also use p command to get the overview of hard disk any time in this utility.

fdisk p command

The p command also provides information about available space in hard disk to create a new partition. If last partition ends before the last sector of hard disk, we have available space to create a new partition. As we can see in above output currently no value is available in partition section which means there is no partition available and entire disk space is available for partition.

Type n and press Enter key to create new partition

fdisk new partition

Type p and press Enter key.

As we know in MBR partition scheme we are allowed to create maximum four primary partitions.
If more partitions are required, we have to use one primary partition as extended partition.
Extended partition allows us to create 15 logical partitions.

To learn more about MBR and GPT partition scheme, see the first part of this tutorial which explains these and other relative topics in detail with examples.

Type the partition number (or keep the default number) and press Enter key.

Type the first available sector for partition (or accept the default sector) and press Enter key.

Type the last available sector for partition. Alternatively we can use KiB, MiB or GiB units to define the size of partition. (To
learn what are the differences between KiB, MiB, GiB and KB, MB, GB, please see the first part of this article
.)

Following figure illustrates above process step by step

fdisk create new partition

We can verify the creation of partition with p command

fdisk print command

Following same process create two more partitions

fdisk partition

We have created three primary partitions from maximum allowed (four) partitions. Now we can create one more primary partition or can create one extended partition which can be used to create further logical partitions.

Let’s create one allowed extended partition. Since extended partition is used to create all allowed logical partitions, we should allocate the maximum disk space in this partition. We will assign 1GiB disk space in this partition.

fdisk extended partition

At this point we have created all allowed primary partitions. If we use n command again, command mode will automatically set
to logical partition (only if one primary partition is created as extended).

fdisk all partition used

We are allowed to create up to 15 logical partitions in extended partition. Since all logical partitions will be created in extended partition, the sum (of size) of all logical partitions cannot go beyond the extended partition. In this example we created an extended partition of 1GiB, so we can create logical partitions up to 1GiB. To understand it more clearly let’s create three logical partitions; first partition of 500MiB, second partition of 500MiB and third partition of remaining size.

fdisk create logical partition

We have used all space of extended partition in three logical partitions. So even we are allowed to create up to 15 logical partitions and free space is available outside the extended partition we cannot create the fourth logical partition. To create fourth logical partition we need free space inside the extended partition not outside the partition. To see it in action let’s try to create fourth logical partition.

no space for logical partition

As above output shows there is no free space available for fourth logical partition. So far we have created all possible partitions including primary, extended and logical partitions. Let’s have a overview of partitions.

fdisk print command

As above output shows there are total 4194304 sectors available in hard disk. From which we used only 2713599 sectors in partitions. 1480705 sectors are still available for partitions but we cannot use them. MBR partition scheme allows us to create only four primary partitions including one extended partition which we have already created.

At first sight this limitation may look alarming, yep it’s an issue but not as much as it looks like. We are allowed to use 2TiB space in each partition. It means 2TiB x 4 = 8TiB hard disk can easily be used with MBR partition scheme.

Each partition uses a special marking known as partition system identifier. This marking is used to identify the purpose of partition. To print all available partition types type l and press Enter key.

linux file system type

As we can see in above output Linux supports several kinds of partitions type. Following table lists some important Linux partition types.

Partition system Identifier Description
82 Linux swap partition
83 Linux Standard partition (Default partition )
85 Linux extended partition
88 Linux plain text partition
8e Linux LVM partition
fd Linux RAID partition

Unless we change the type of any partition, it is marked as Linux Standard partition. But if we want to change it, we can also do the same here. In next part of this tutorial we will learn how to change the partition type, for this part let’s keep the default.

When we started the fdisk utility, we got a message indicating that nothing will be saved on hard disk until we confirm the action.

To accept this partition table type w and press Enter key

save fdisk partition

If you are working with a disk which contains mounted partitions, you may get following warning message.

WARNING: Re-reading the partition table failed with error 16: Device or resource busy.
The kernel still uses the old table. The new table will be used at the next reboot or after you run partprobe(8) or kpartx(8) Syncing disks.

This message indicates that fdisk cannot update the in-memory kernel partition table because disk is busy (mounted). Kernel reads partition table when system boots. So the kernel will be updated about this change at next reboot automatically. Meanwhile if we want to update the kernel immediately, we can use partprobe command which will force the kernel to reread the partition table.

We did not get this warning message because we used a disk which does not contain any mounted partition. Whether we get above message or not we should always run following command.

partprobe command

Replace /dev/sdc with your disk name.

We have successfully created the partitions. To view the partitions use fdisk –l command.

fdisk -l command

These partitions are useless unless we put a file system in them. File system is a logical container which allows us to store files and directories. To learn more about file system see the first part of this tutorial.

How to create file system

To create a file system in partition we have to format it with supported file system. To format a partition following command is used.

#mkfs –t [supported file system type] [partition]

Some common supported file systems are ext3, ext4 and xfs. Let’s format the recently created partitions with these file systems.

File system type ext3 partition /dev/sdc1

mkfs ext3

File system type ext4 partition /dev/sdc2

mkfs ext4

File system type xfs partition /dev/sdc3

mkfs xfs

Since extended partition is only used to store the logical partitions we cannot create file system in it.

extended partition format error

Logical partitions are used to store the data. We have to create the file system in them.

logical partition format

Now partitions have file system, can we use them for data storage now? No, even though partitions are ready to use, we cannot use them until they are connected with primary directory structure (Main Linux file system).

error to access the partition

Linux file system (primary directory structure) starts with root (/) directory and everything goes under it or its subdirectories. We have to mount partitions somewhere under this directory tree. We can mount partitions temporary or permanently.

Mounting partitions temporary

Following command is used to mount the partition temporary.

#mount [what to mount] [where to mount]

Mount command accepts several options and arguments which I will explain separately in another tutorial. For this tutorial this basic syntax is sufficient.

what to mount :- This is the partition.

where to mount :- This is the directory which will be used to access the mounted resource.

Once mounted, whatever action we will perform in mounted directory will be performed in mounted resources. Let’s understand it practically.

  • Create a mount directory in / directory
  • Mount /dev/sdc1 partition
  • List the content
  • Create a test directory and file
  • List the content again
  • Un-mount the /dev/sdc1 partition and list the content again
  • Now mount the /dev/sdc2 partition and list the content
  • Again create a test directory and file. Use different name for file and directory
  • List the content
  • Un-mount the /dev/sdc2 partition and list the content again

Following figure illustrates this exercise step by step

temporary mount exercise

As above figure shows whatever action we performed in mount directory was actually performed in respective partition.

Temporary mount option is good for partitions which we access occasionally. If we access partition on regular basis then this approach will not helpful. Each time we reboot the system all temporary mounted resources are get un-mounted automatically. So if you have a partition which is going to be used regularly, mount it permanently.

Mounting partitions permanently

Each resource in file system has a unique ID called UUID. When mounting a partition permanently we should use UUID instead of its name. From version 7, RHEL also uses UUID instead of device name.

The UUID stands for Universally Unique Identifier. It is a 128-bit number, expressed in hexadecimal (base 16) format.

If you have a static environment, you may use device name. But if you have dynamic environment, you should always use UUID. In dynamic environment device name may change each time when system boot. For example we attached an additional SCSI disk in system; it will be named as /dev/sdb. We mounted this disk permanently with its device name. Now suppose someone else removed this disk and attached new SCSI disk in the same slot. New disk will also be named as /dev/sdb. Since name of old disk and new disk is same, new disk will be mounted at the place of old disk. This way, device name could create a serious problem in dynamic environment. But this issue can solve with UUID. No matter how we attach the resource with system, its UUID will remain always fix.

If you have static environment, you may consider device name to mount the partition.
But if you have dynamic environment, you should always use UUID.

To know the UUID of all partitions we can use blkid command. To know the UUID of a specific partition we have to use its name as argument with this command.

blkid command

Once we know the UUID, we can use it instead of device name. We can also use copy and paste option to type the UUID.

  • Use blkid command with partition name to print the UUID of partition.
  • Copy the UUID of partition.
  • Use mount command to mount the partition. Use paste option instead of typing UUID.

Following figure illustrates above steps

blkid command

When system boots, it looks in /etc/fstab file to find out the partitions which need to be mount automatically. By default this file has entry for those partitions which were created during the installation. To mount any additional partition automatically we have to make an entry for that partition in this file. Each entry in this file has six fields.

default fstab

Number Filed Description
1 What to mount Device which we want to mount. We can use device name, UUID and label in this filed to represent the device.
2 Where to mount The directory in main Linux File System where we want to mount the device.
3 File system File system type of device.
4 Options Just like mount command we can also use supported options here to control the mount process. For this tutorial we will use default options.
5 Dump support To enable the dump on this device use 1. Use 0 to disable the dump.
6 Automatic check Whether this device should be checked while mounting or not. To disable use 0, to enable use 1 (for root partition) or 2 (for all partitions except root partition).

Let’s make some directories to mount the partitions which we have created recently

mkdir command

Now open the fstab file and make entries for partitions and save the file.

fstab partition entry

For demonstration purpose I used both device name and UUID to mount the partitions. After saving always check the entries with mount –a command. This command will mount everything listed in /etc/fstab file. So if we made any mistake while updating this file, we will get an error as the output of this command.

If you get any error as the output of mount –a command, correct that before rebooting the system. If there is no error, reboot the system.

reboot command

The df –h command is used to check the available space in all mounted partitions. We can use this command to verify that all partitions are mounted correctly.

df -h command

Above output confirms that we have successfully mounted all partitions. Now it’s time to clean up the system for next practice.

How to delete partitions

We cannot delete a mounted partition. Un-mount all partitions which we created in this exercise

unmount the partition

Run fdisk /dev/sdc command again

fdisk sdc

The d command is used to delete a partition. If there are multiple partitions, command will ask for partition number which we want to delete. Delete all partitions one by one

delete partition

As we know whatever change we made in this utility will not apply until we save them with w command. Let’s save the change and exit from fdisk.

save change fdisk command

Finally remove the mount directory and copy the original fstab file back.

If you haven’t taken the backup of original fstab file, remove all entries from this file which you made.

restore fstab

Now reboot the system and use df –h command again to verify that all partitions which we created in this exercise are gone.

df -h

That’s all for this part. In next part we will learn how to create and manage GPT partitions.

Full Version EX300 Dumps

Try EX300 Dumps Demo

Categories
RHCE 7 Study Guide

How to Configure DHCP Server in Linux

This tutorial explains how to configure DHCP server in RedHat Linux and DHCP client Windows and Linux step by step with practical example. Learn how to configure DHCP server to assign IP addresses dynamically from IP address pool and configure it to assign fix IP addresses to specific resources based on MAC address.

DHCP, or Dynamic Host Configuration Protocol, allows an administrator to configure network settings for all clients on a central server.

The DHCP clients request an IP address and other network settings from the DHCP server on the network. The DHCP server in turn leases the client an IP address within a given range or leases the client an IP address based on the MAC address of the client\’s network interface card (NIC). The information includes its IP address, along with the network\’s name server, gateway, and proxy addresses,including the netmask.

Nothing has to be configured manually on the local system, except to specify the DHCP server it should get its network configuration from. If an IP address is assigned according to the MAC address of the client\’s NIC, the same IP address can be leased to the client every time the client requests one. DHCP makes network administration easier and less prone to error.

Exam Question Configure the DHCP server by matching the following conditions:

  • Subnet and netmask should be 192.168.0.0 255.255.255.0
  • Gateway Should be 192.168.0.254
  • DNS Sever Should be 192.168.0.254
  • Domain Name should be example.com
  • Range from 192.168.0.10-50

Exam Question You have DHCP server, which assigns the IP, gateway and DNS server ip to Clients. There is one DNS servers having MAC address (00:50:FC:98:8D:00 in your LAN, But it always required fixed IP address (192.168.0.10). Configure the DHCP server to assign the fixed IP address to DNS server.

Configure dhcp server

In this example we will configure a dhcp server and will lease ip address to clients.

For this example we are using three systems one linux server one linux clients and one window clients.

dhcp rpm is required to configure dhcp server. check it if not found then install

rpm

Now check dhcpd service in system service it should be on

#setup
Select  System service
from list [*]dhcpd

To assign IP to dhcp server

DHCP server have a static a ip address. First configure the ip address 192.168.0.254 with netmask of 255.255.255.0 on server.

Run setup command form root user

 #setup 

setup

this will launch a new window select network configuration

network configurations

now a new window will show you all available LAN card select your LAN card ( if you don\’t see any LAN card here mean you don\’t have install driver)

select lan devices in setup

assign IP in this box and click ok

assign ip address

click on ok, quit and again quit to come back on root prompt.

restart the network service so new ip address can take place on LAN card

 #service network restart 

main configuration file of dhcp server is dhcpd.conf. This file located on /etc directory. If this file is not present there or you have corrupted this file, then copy new file first, if ask for overwrite press y

cp dhcpd sample file

now open /etc/dhcpd.conf

vi dhcpd

default entry in this file look like this

dhcpd.conf

make these change in this file to configure dhcp server

remove this line # - - - default gateway
set option routers to 192.168.0.254
set option subnet-mask to 255.255.255.0
option nis domain to example.com
option domain-name to example.com
option domain-name-servers to 192.168.0.254
range dynamic-bootp to 192.168.0.10 192.168.0.50;

After change this file should look like this

dhcpd.conf

how to assign fix ip address to any host

locate this paragraph and change hardware Ethernet to client\’s mac address and fixed -address to ip address which you want to provide that host

dhcpd.conf

after making necessary change save file and exit

now create a blank file use to store the allocated ip address information

touch

Now restart dhcpd service and on it with chkconfig commands

service dhcpd restart

Linux Client configuration

Client configuration is very easy and straightforward. All you need to do is set ip address to dynamic in the properties of lan card. In linux

#setup
select  network configuration from menu list
Select  lan card and enter on ok
Select  USE DHCP and enter on ok
Now click on  quit
and  quit to come back on root prompt

Now restart the network service to obtain ip from dhcp server

service network restart

Window Client configuration

To configure windows system as dhcp clients open lan card properties and select tcp/ip and click on properties and set obtain ip address automatically

lan card porperties

Go on command prompt and check new ip address

ipconfig

Check lease on DHCP server

you can check allocated address on server.

 cat

cat lease

Full Version EX300 Dumps

Try EX300 Dumps Demo

Categories
RHCE 7 Study Guide

Linux Environment Variables List, Set, Create & Remove

This tutorial explains Linux Environment variables in detail. Learn how to set, reset, add, remove, create and delete environment variables locally and globally in Linux with practical examples. Environmental variables are used to customize the Linux for better user experience.

What is a linux environment variable

Linux environment variable is an object that contains value. In simple terms it is a pair of data object and their respective values. If you are familiar with programming language than you can easily understand it. Linux environment variables do same job which variables do in programming language.

If you are not familiar with programming language you can understand linux variable as a container with name which keeps value inside it. This value could be location of all executable files in the filesystem, the default editor that should be used, or the system locale settings.

Example of linux environmental variable

Let take a simple example of ls command to understand linux environmental variables. ls the basic command to list the content of directory. When execute a command in linux, you need to type the full path of that command. Since the ls command is in the /bin directory, users should execute the /bin/ls command to list files in the current directory.

Here comes the magic of linux environmental variables. Linux have a PATH variable. With the help of the PATH variable, full path is not required. The bash shell automatically searches through the directories listed in a user\’s PATH variable for the command that user just typed at the command line. When a matching command found shell run it. In this way environment variable provides a simple way to share configuration settings between multiple applications and processes in Linux.

How to show linux environment variable

printenv or env command can be use to list linux environment variables. The coreutils package contains printenv and env. Use printenv command to show linux environmental variables.

$ printenv

Linux environment variable printenv

The env utility can also be used to show linux environment variables.

$env

Linux environment variable env

printenv to print the names and the values of each. Note that some environment variables are user-specific. Output of env and printenv are too big to fit in screen. We can redirect the output of printenv in a file. To redirect the output of printenv in a file run following command

$printenv > tmp_file

Linux environment variable printenv tmpfile

now we can read the tmp_file with less command.

$less tmp_file

Linux environment variable printenv less

Use up arrow and down arrow key to scroll. Press q to exist from file

Linux environment variable printenv reading

After reading you can simple remove the temporary file

$rm tmp_file

Linux environment variable rm tmp file

How to set linux environment variable

Linux environment can be set in three ways.

  • Temporary also know as Session Specific Variables
  • permanent locally
  • Permanent globally

To set linux environmental variable temporary use export command.

PATH variable contains location of executable files. To check current PATH use following command

$ echo $PATH

Linux environment variable echo path

Now we would add our directory in this path. Make a directory

$makdir custom_script

To add this directory in path run following commands

$export PATH=\"${PATH}:/home/user1/custom_script\"

Verify that we have successfully added our custom_script directory in PATH variable

Linux environment variable echo path with dir

Now move in our custom_script directory and make a sample script

Linux environment variable simple script

make sample_script executable and run script directly from command prompt.

Linux environment variable sample script chomd and run

You can also verify that shell run sample_script from our custom_script directory by which command

Linux environment variable sample script which

Temporary variable only available in current session. To test it log out from current user and login back.

Run sample_script again. This time you will get command not found error.

Linux environment variable simple script error

How to set linux environmental variable permanently

Defining Variables Locally

As you seen temporary variables are available only on that session. We can make those variables permanent. For security reason you should not define an environment variable globally unless you have sound understanding of linux system. For instance, you might want to add /home/user_name/custom_script to the PATH variable for a particular user. In such a case define it locally. As you do not want all other users on your system to have that in their PATH too.

The following files should be used for local environment variables on your system: ~/. profile, ~/.bash_profile, ~/.bash_login and ~/.bash_logout.

Linux environment variable ls a

To add our custom_script directory in to the PATH variable for local usage

open .bash_profile file

 vi ~/.bash_profile

Linux environment vi bash profile

add our directory /home/user1/custom_script in PATH variable

Linux environment variable bash profile edit

To update the variable, re-login required.

Logout

Linux environment variable exit

Login back

Now check that our custom path is available

Linux environment variable sample script check after login

Permanently set linux environmental variable Globally

root privilege requires to set linux environment variable globally. RHEL maintain and manage the environment variables in numerous files. But you do not need to pay attentions on all files that can contain environment variables. Following the RHEL recommendation you should only set environmental variables in some particular files. The following files should be used for defining global environment variables on your system: /etc/profile, /etc/bash.bashrc and /etc/environment.

/etc/profile.d Directory is used to define global script.

Login from root and move to /etc

Linux environment variable cd etc root

move to /etc/profile.d directory

Make a simple test script and make this script executable

Linux environment variable global script

This script print a simple welcome message for all users

To test it logout from root and login back from normal user

Linux environment variable global script test normal user

We have successfully added global script. After testing to remove it login back from root

remove our test script

Linux environment variable rm global

List of Linux environmental variable

Variable name Stored information
DISPLAY used by the X Window system to identify the display server
DOMAIN domain name
EDITOR stores your favorite line editor
HISTSIZE size of the shell history file in number of lines
HOME path to your home directory
HOSTNAME local host name
INPUTRC location of definition file for input devices such as keyboard
LANG preferred language
LD_LIBRARY_PATH paths to search for libraries
LOGNAME login name
MAIL location of your incoming mail folder
MANPATH paths to search for man pages
OS string describing the operating system
OSTYPE more information about version etc.
PAGER used by programs like man which need to know what to do in case output is more than one terminal window.
PATH search paths for commands
PS1 primary prompt
PS2 secondary prompt
PWD present working directory
SHELL current shell
TERM terminal type
UID user ID
USER(NAME) user name
VISUAL your favorite full-screen editor
XENVIRONMENT location of your personal settings for X behavior
XFILESEARCHPATH paths to search for graphical libraries

Full Version EX300 Dumps

Try EX300 Dumps Demo