Linux On The Go
Linux On The Go
Unique amongst business class Linux distributions, CentOS stays true to the open-source
nature that Linux was founded on. This tutorial gives a complete understanding on Linux
Admin and explains how to use it for benefit.
Audience
This tutorial has been prepared for beginners to help them understand the fundamentals
of Linux Admin. It will specifically be useful for Linux administration professionals. After
completing this tutorial, you will find yourself at a moderate level of expertise from where
you can take yourself to the next levels.
Prerequisites
Before you go ahead with this tutorial, we assume that you have a basic knowledge of
Linux and Administration fundamentals.
All the content and graphics published in this e-book are the property of Tutorials Point (I)
Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish
any contents or a part of contents of this e-book in any manner without written consent
of the publisher.
We strive to update the contents of our website and tutorials as timely and as precisely as
possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.
Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our
website or its contents including this tutorial. If you discover any errors on our website or
in this tutorial, please notify us at [email protected]
i
Linux Admin
Table of Contents
About the Tutorial .................................................................................................................................... i
Audience .................................................................................................................................................. i
Prerequisites ............................................................................................................................................ i
wc Command ........................................................................................................................................ 10
sort Command....................................................................................................................................... 11
tee Command........................................................................................................................................ 18
tr Command .......................................................................................................................................... 31
ii
Linux Admin
ps Command ......................................................................................................................................... 68
iii
Linux Admin
17. LINUX ADMIN : INSTALL APACHE WEB SERVER CENTOS 7 ............................................... 115
19. LINUX ADMIN ─ SET UP POSTFIX MTA & IMAP/POP3 ...................................................... 120
iv
Linux Admin
Install Fedora EPEL Repository ─ Extra Packages for Enterprise Linux .................................................. 141
v
Linux Admin
vi
1. Linux Admin ─ CentOS Overview Linux Admin
Unique among business class Linux distributions, CentOS stays true to the open-source
nature that Linux was founded on. The first Linux kernel was developed by a college
student at the University of Helsinki (Linus Torvalds) and combined with the GNU utilities
founded and promoted by Richard Stallman. CentOS has a proven, open-source licensing
that can power today’s business world.
CentOS has quickly become one of the most prolific server platforms in the world. Any
Linux Administrator, when seeking employment, is bound to come across the words:
“CentOS Linux Experience Preferred”. From startups to Fortune 10 tech titans, CentOS has
placed itself amongst the higher echelons of server operating systems worldwide.
What makes CentOS stand out from other Linux distributions is a great combination of:
Before starting the lessons, we assume that the readers have a basic knowledge of Linux
and Administration fundamentals such as:
Cores that compose a computer operating system: file system, drivers, and the kernel
1
2. Linux Admin ─ Basic CentOS Linux Commands
Linux Admin
Before learning the tools of a CentOS Linux Administrator, it is important to note the
philosophy behind the Linux administration command line.
Linux was designed based on the Unix philosophy of “small, precise tools chained together
simplifying larger tasks”. Linux, at its root, does not have large single-purpose applications
for one specific use a lot of the time. Instead, there are hundreds of basic utilities that
when combined offer great power to accomplish big tasks with efficiency.
It is easy to export this list into a text file using the following command.
It is also possible to compare the user list with an export at a later date.
2
Linux Admin
With this approach of small tools chained to accomplish bigger tasks, it is simpler to make
a script performing these commands, than automatically email results at regular time
intervals.
vim
grep
more
less
tail
head
wc
sort
uniq
tee
cat
cut
sed
tr
paste
In the Linux world, Administrators use filtering commands every day to parse logs, filter
command output, and perform actions with interactive shell scripts. As mentioned, the
power of these commands come in their ability to modify one another through a process
called piping.
The following command shows how many words begin with the letter a from the CentOS
main user dictionary.
The biggest difference between vi and vim are advanced ease-of-use features such as
moving the cursor with the arrow keys. Where vim will allow the user to navigate a text
file with the arrow keys, vi is restricted to using the "h", "j", "k", "l" keys, listed as follows.
3
Linux Admin
Key Action
Using vim the same actions can be accomplished with the arrow keys on a standard English
(and other common language) based qwerty, keyboard layout. Similarly, vi will often not
interpret the numeric keypad on as well.
Mostly, these days, vi will be symlinked to vim. If you ever find it frustrating your arrow
keys are doing things unexpected when pressed, try using your package manager to install
vim.
vim uses the concept of modes when manipulating and opening files. The two modes we
will focus on are:
normal: This is the mode vim uses when a file is first opened, and allows for
entering commands.
Let's open a file in vim. We will use the CentOS default dictionary located at
/usr/share/dict:
What you see is the text file opened in normalmode. Now practice navigating the document
using the arrow keys. Also, try using the h,j,k and lkeys to navigate the document.
Vim expects us to send commands for file operations. To enable line number, use the
colon key: shift+:. Your cursor will now appear at the bottom of the document. Type "set
nu" and then hit enter.
:set nu
Now, we will always know where in the file we are. This is also a necessity when
programming in vim. Yes! vim has the best syntax highlighting and can be used for making
Ruby, Perl, Python, Bash, PHP, and other scripts.
Command Action
4
Linux Admin
Please try the following tasks in vim, to become familiar with it.
We will pretend that we made edits on a critical file and want to be sure not to save any
unintended changes. Hit the shift+: and type: q!. This will exit vim, discarding any
changes made.
Now, we want to actually edit a file in vim: at the console type: vim myfile.txt
We are now looking at a blank text buffer in vim. Let's write something: say
- hit "i".
vim is now in insert mode, allowing us to make edits to a file just like in Notepad. Type a
few paragraphs in your buffer, whatever you want. Later, use the following steps to save
the file:
5
Linux Admin
STDOUT
[root@centosLocal centos]# cat output.txt
Hello,
I am coming from Standard output or STDOUT.
[root@centosLocal centos]#
STDIN
[root@centosLocal centos]# cat < stdin.txt
Hello,
I am being read form Standard input, STDIN.
[root@centosLocal centos]#
Above, we passed cat'sstdout to wc for processing the pipe character. wc then processed
the output from cat printing the line count of output.txt to the terminal. Think of the pipe
character as a "pipe" passing output from one command, to be processed by the next
command.
Following are the key concepts to remember when dealing with command redirection.
2 standard error
pipe stdout |
6
Linux Admin
Grep Command
grep is commonly used by administrators to:
Switch Action
Check for possible RDP attacks on an imported Windows Server firewall log.
As seen in the above example, we had 326 Remote Desktop login attempts from IPv4 class
A range in less than 24 hours. The offending IP Address has been hidden for privacy
reasons. These were all from the same IPv4 address. Quick as that, we have tangible
evidence to block some IPv4 ranges in firewalls.
7
Linux Admin
grep can be a fairly complex command. However, a Linux administrator needs to get a
firm grasp on. In an average day, a Linux System Admin can use a dozen variations of
grep.
Typically, less is the preferred choice, as it allows both forward and backward perusal of
paginated text. However, less may not be available on default installations of older Linux
distributions and even some modern Unix operating systems.
Usually less is preferred, because less really offers more than more.
As shown above, when invoked less opens into a new buffer separate from the shell
prompt. When trying less, it sometimes may give an error as follows:
8
Linux Admin
Either use more or install less from the source of the package manager. But less should
be included on all modern Linux Distributions and even ported to Unix platforms. Some
will even symlink more to less.
tail Command
tail will output (stdout) the last part of a text file. Most useful when perusing long text
files and we only need to see the current updates.
Switch Action
A useful switch option for tail is -f. The -f switch is really useful for real-time
troubleshooting of logs. A good example is when a user has issues with remote login. Using
the -f option, piping the output of VPN logs into grep, then the filtering user id is allowed
to watch login attempts from the troubled user. It turned out auth credentials were
garbled.
Upon further inspection, they had changed the encryption protocol of the RAS client.
Something that could have taken a long time to figure out by asking questions and walking
a user through client config. settings step by step.
Using tail with the -f switch to watch wpa supplicant logs as wifi is connected to a new AP.
9
Linux Admin
head Command
head is a basic opposite of tail in relation to what part of the file operations are performed
on. By default, head will read the first 10 lines of a file.
Switch Action
Note: Head offers no -f option, since the files are appended from the bottom.
head is useful for reading descriptions of configuration files. When making such a file, it
is a good idea to use the first 10 lines effectively.
## Host Aliases
[root@centosLocal centos]#
wc Command
wc is useful for counting occurrences in a file. It helps print newline, word, ad byte count
from each file. Most useful is when combined with grep to show matches for a certain
pattern.
Switch Action
-c Bytes
-m Character count
-l Line count
10
Linux Admin
We can see our system has 5 users with a group id of 0. Then upon further inspection only
the root user has shell access.
sort Command
sort has several optimizations for sorting based on datatypes. Theis command writes
sorted concatenation of all files to standard output. However, be weary, complex sort
operations on large files of a few GigaBytes can impede the system performance.
When running a production server with limited CPU and/or memory availability, it is
recommended to offload these larger files to a workstation for sorting operations during
peak business hours.
Switch Action
-M Month sort
-R Random sort
Feel free to copy the tabular text below and follow along with our sort examples. Be sure
each column is separated with a tab character.
11
Linux Admin
12
Linux Admin
13
Linux Admin
Sometimes, we will want to sort files on another column, other than the first column. A
sort can be applied to other columns with the -t and -k switches.
Note: In some examples, we have used cat piped into grep. This was to demonstrate the
concepts of piping commands. Outputting cat into grep can increase the system load
hundreds of times-over with large files, while adding complex sorting. This will make
veteran Linux administrators cringe.
Now that we have a good idea of how the pipe character works, this poor practice will be
avoided in the chapters to follow. The key to keeping the system resources low with
commands like sort, is learning to use them efficiently.
14
Linux Admin
Now we have our list sorted by office number. The astute reader will notice something out
of the ordinary after the -t switch; single quotes separated by what appears to be a few
spaces. This was actually a literal Tab character sent to the shell. A literal Tab can be sent
to the BASH shell using the key combination of: control+Tab+v.
Most shells will interpret the Tab key as a command. For example, auto-completion in
BASH. The shell needs an escape sequence to recognize a literal Tab character. This is one
reason why Tabs are not the best choice for delimiters with Linux. Generally speaking, it
is best to avoid both spaces and tabs, as they can cause issues when scripting a shell.
15
Linux Admin
Sonya:Weaver:403
Donald:Evans:403
Gwendolyn:Chambers:108
Antonia:Lucas:901
Blanche:Hayes:603
Carrie:Todd:201
Terence:Anderson:501
Joan:Parsons:102
Rose:Fisher:304
Malcolm: Matthews:702
[root@centosLocal centos]#
Now, it will be much easier to work with the text file. If someone demands it be returned
to Tab delimited for another application (this is common), we can accomplish that task
easily as:
Common end-user applications will work good with Tabs as a delimiter (An Accountant
does not want to see a colon separating data columns, while working on Spreadsheets.).
So learning to transform characters back and forth is a good practice; it comes up often.
Note: Office uses word-processors and spreadsheets with a Graphical User Interface,
running on Windows. Hence, it is common for Linux Administrators to get good at
completing transformation actions, accommodating end office-users (most times, our boss
will be an end user).
Introduced was a command called sed. sed is a stream editor and can be used as a non-
interactive text editor for manipulating streams of text and files. We will learn more about
sed later. However, keep in mind for now, using sed, we avoided a need to pipe several
filter commands when changing our text file. Thus, making the most efficient use of the
tools at hand.
We also introduced a Bash shell operator: &&. && will run the second command only if the
first command completes with a successful status of "0".
16
Linux Admin
In the above code, note the difference between && and ;? The first will only run the second
command when the first has completed successfully, while ; simply chains the commands.
More on this when we get to scripting shell commands.
uniq Command
Following are the common switches used with uniq. This command reports or omits
repeated lines.
Switch Action
-i Ignore case
We have briefly used uniq in a few examples prior. The uniq command allows us to filter
the lines of files based on matches. For example, say we got a second employee named
Matt Davis in Sales. Three days later, Accounting needs new estimates for Sales
Participation Awards for next quarter. We can check the employee list using the following
command.
We tell them 30 people in Sales for the annual participation awards. There might be a
good chance Accounting will notice a discrepancy: they only needed 29 unique award
plaques produced. Let's try again:
Note: When looking for unique lines, we always want to use sort, piping its output to uniq.
If non-uniq entries are not inline sequence, they will not be seen as duplicate lines.
To quickly generate a report letting us know how many sales people share an office:
17
Linux Admin
tee Command
tee is a simple command, letting an administrator write command output and view a file
at the same time. This simple command can save time over first writing stdout to a file,
then viewing the file contents.
Command Action
18
Linux Admin
Without tee to both view and write files and directories in /etc, where each begins with
the letter "a".
19
Linux Admin
This small task is much more efficient with the tee command.
cat Command
The cat command is used to concatenate files and print to standard output. Formerly, we
have demonstrated both uses and abuses with the cat command. cat servers the following
distinct purposes:
20
Linux Admin
Switch Action
-T Show tabs
As noted previously, when using utilities such as grep, sort, and uniq we want to avoid
piping output from cat if possible. We did this for simple demonstration of piping
commands earlier. However, knowing when to perform an operation with a utility like grep
is what separates Linux Administrators from Linux end-users.
Bad Habit
[root@centosLocal centos]# cat /etc/passwd | sort -t: -k1 | grep ":0"
halt:x:7:0:halt:/sbin:/sbin/halt
operator:x:11:0:operator:/root:/sbin/nologin
root:x:0:0:root:/root:/bin/bash
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
sync:x:5:0:sync:/sbin:/bin/sync
[root@centosLocal centos]#
Good Habit
[root@centosLocal centos]# grep ":0" /etc/passwd | sort -t: -k 1
halt:x:7:0:halt:/sbin:/sbin/halt
operator:x:11:0:operator:/root:/sbin/nologin
root:x:0:0:root:/root:/bin/bash
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
sync:x:5:0:sync:/sbin:/bin/sync
[root@centosLocal centos]#
Note: piping cat to secondary commands like sort or grep should only be done when it is
needed.
One common use of cat is when dealing with Windows formatted line breaks. Both Linux
and Windows by internal design, use a different control code to represent End Of Line
(EOL):
21
Linux Admin
* Macintosh, in all moderne releases of OS X and now macOS, has adopted the
Linux/Unix standard of LF or "\n"
So, let's say we open our file in a GUI text-editor like gedit or are experiencing random
issues while applying filtering commands. Text appears on a single line, or filtering
commands do not operate as expected.
Especially, when the text file was downloaded off the Internet, we want to check line
breaks. Following is a sample output from cat showing EOL characters.
Notice the preceding "$" on each line? Linux is reading the CR "\n", breaking the file. Then
translating a Carriage Return over the first character of each file.
Note: When viewed with the -E switch, all Linux line breaks will end in $.
22
Linux Admin
cat can also be used to combine multiple files into a single file.
23
Linux Admin
Finally, we can use the -n switch to number each output line. This will give us a total of
lines.
cut Command
cut and grep are two of the most useful and common commands for a CentOS
Administrator. cut is extremely useful for dealing with delimited files such as Linux
configuration files, Linux preference files, and CSV files.
Switch Action
Most times, cut will be used to extract specific rows out of text files. Previously, we have
used cut to get a listing of all users from /etc/passwd:
24
Linux Admin
shutdown
Some Linux utilities and applications actually save the output with the functionality of cut
in mind. Following is an example of nmap output.
With cut, we can quickly generate a list of internal systems with port 80 listening for
outside requests.
[root@centosLocal centos]# grep open ./http_scans.txt | cut -d" " -f2 >
open_http_servers.txt
[root@centosLocal centos]# head open_http_servers.txt
10.58.52.17
10.58.52.29
10.58.52.30
10.58.52.36
10.58.52.59
10.58.53.89
10.58.53.100
10.58.54.103
10.58.54.148
10.58.54.152
[root@centosLocal centos]#
25
Linux Admin
10.58.53
10.58.53
10.58.53
10.58.53
10.58.53
10.58.54
10.58.54
10.58.54
10.58.54
10.58.54
10.58.54
10.58.54
10.58.54
10.58.54
10.58.54
10.58.54
10.58.54
10.58.54
10.58.54
10.58.54
10.58.54
[root@centosLocal centos]#
cut is a command that will be used almost daily by a CentOS Administrator. It is a life
saver for parsing text and some binary files.
sed Command
sed is a complex utility to master. This command streams the editor for filtering and
transforming text. Entire books have been written dedicated to using sed proficiently. So
please keep in mind, this tutorial has a purpose of introducing three basic-common-uses
of sed:
character substitution
printing operations
delete operations
26
Linux Admin
Switch Action
-i will apply changes to a file, instead of editing the file's stream as passed to sed.
sed, when used with the -e option extends the command to process multiple operations
on a stream. This can be done instead piping sed recursively.
echo "Windows and IIS run the Internet" | sed -e 's/Windows/Linux/' -e 's/ and
IIS//' -e 's/run/runs/'
Linux runs the Internet
The -n option with sed suppresses default printing to stdout. Using sed's print command,
as we see, each line will be duplicated to stdout.
sed will send content streams to stdout. When the 'p' or print command is added, a
separate stream is sent for each line causing all lines to be duplicated in stdout.
27
Linux Admin
Now, let's change the contents of a file instead of just its output stream sent to sed:
Let's use our names.txt file, the output has been edited for brevity sake:
sed allows the use of "addresses", to more granularly define what is being printed to stdout:
28
Linux Admin
Ted:Daniel:101
Jenny:Colon:608
Dana:Maxwell:602
Marian:Little:903
Bobbie:Chapman:403
Nicolas:Singleton:203
Dale:Barton:901
Aaron:Dennis:305
Santos:Andrews:504
Jacqueline:Neal:102
[root@centosLocal Documents]#
Just like head, we printed the first 10 lines of our names.txt file.
What if we only wanted to print out those with an office on the 9th floor?
Pretty easy. We can also print out everyone, except those with offices on the 9th floor:
29
Linux Admin
Sidney:Mac:100
Heidi:Simmons:204
Matt:Davis:205
Cristina:Torres:206
Sonya:Weaver:403
Donald:Evans:403
In the above code, we negated 'p' printing operation between / and /with !. This performs
similarly to the the "d" or delete command. However, the results can vary with negation
in sed. So as a general rule: p to print and negate what you do not want.
Nothing printed out. With the above command, we asked sed to delete every line from
stdout in the stream. Now, let's only print the first two lines and "delete" the rest of the
stream:
See? Similar to the 'p', or print command. Now let's do something useful with the delete
command. Say we want to remove all blank lines in a file:
It is not uncommon to receive a file like this containing jumbled text, from copying and
pasting an email or formatted with non-standard line breaks. Instead of interactively
editing the file in vim, we can use sed to do the work for us.
30
Linux Admin
The file is now formatted in an easily readable fashion. Note:When making changes to the
important files, use -iswitch. Appending a file backup suffix is greatly advised to reserve
the file contents (sed can make some extreme changes with the slightest typo).
tr Command
Following is the syntax for tr. This command translates or deletes characters.
Following are the commonly used switches and character classes with tr.
Command Action
-d Delete
31
Linux Admin
When thinking should one go with "use sed" or "use tr", it is better to go with keep it
simple philosophy. If an operation is simple in tr; use it. However, once you start thinking
about using tr recursively, it is better to use sed's substitution command.
Typically, tr will replace [SET1] with characters in [SET2] unless the -d switch is used.
Then, the characters from the stream in [SET1] will be deleted.
Using tr on our names.txt file to turn all lower case caracters into uppper case:
32
Linux Admin
paste Command
The paste command is used to merge lines of files. Following are the commonly used
switches.
Switch Action
-d Specify delimiter
33
Linux Admin
Linux
Windows
Solaris
OS X
BSD
line 1
line 2
line 3
line 4
line 5
[root@centosLocal Documents]# past myOS.txt lines.txt
So, if we wanted a ":" colon or Tab separated file by combining two different files, the
paste command makes this fairly simple:
34
Linux Admin
[root@centosLocal Documents]#
With paste it's pretty easy to take a file, and make it into Tab separated columns:
35
3. Linux Admin ─ File / Folder Management
Linux Admin
To introduce permissions as they apply to both directories and files in CentOS Linux, let's
look at the following command output.
Note: The three primary object types you will see are:
We will focus on the three blocks of output for each directory and file:
The second instance, indicates the group to which group permissions are
root
applied
Understanding the difference between owner, group and world is important. Not
understanding this can have big consequences on servers that host services to the
Internet.
Before we give a real-world example, let's first understand the permissions as they apply
to directories and files.
36
Linux Admin
Please take a look at the following table, then continue with the instruction.
Note: When files should be accessible for reading in a directory, it is common to apply
read and execute permissions. Otherwise, the users will have difficulty working with the
files. Leaving write disabled will assure files cannot be: renamed, deleted, copied over, or
have permissions modified.
Symbolic Permissions
Octal Permissions
In essence, each are the same but a different way to referring to, and assigning file
permissions. For a quick guide, please study and refer to the following table:
Octal 4 2 1
Symbolic r w x
When assigning permissions using the octal method, use a 3 byte number such as: 760.
The number 760 translates into: Owner: rwx; Group: rw; Other (or world) no permissions.
Another scenario: 733 would translate to: Owner: rwx; Group: rx; Other: rx.
There is one drawback to permissions using the Octal method. Existing permission sets
cannot be modified. It is only possible to reassign the entire permission set of an object.
Now you might wonder, what is wrong with always re-assigning permissions? Imagine a
large directory structure, for example /var/www/ on a production web-server. We want to
recursively take away the w or write bit on all directories for Other. Thus, forcing it to be
pro-actively added only when needed for security measures. If we re-assign the entire
permission set, we take away all other custom permissions assigned to every sub-
directory.
Hence, it will cause a problem for both the administrator and the user of the system. At
some point, a person (or persons) would need to re-assign all the custom permissions that
were wiped out by re-assigning the entire permission-set for every directory and object.
In this case, we would want to use the Symbolic method to modify permissions:
37
Linux Admin
The above command would not "overwrite permissions" but modify the current permission
sets. So get accustomed to using the best practice:
It is important that a CentOS Administrator be proficient with both Octal and Symbolic
permissions as permissions are important for the integrity of data and the entire operating
system. If permissions are incorrect, the end result will be both sensitive data and the
entire operating system will be compromised.
With that covered, let's look at a few commands for modifying permissions and object
owner/members:
chmod
chown
chgrp
umask
chmod will allow us to change permissions of directories and files using octal or symbolic
permission sets. We will use this to modify our assignment and uploads directories.
chown can modify both owning the user and group of objects. However, unless needing to
modify both at the same time, using chgrp is usually used for groups.
38
Linux Admin
Real-world practice
Let's change all the subdirectory assignments in /var/www/students/ so the owning group
is the students group. Then assign the root of students to the professors group. Later,
make Dr. Terry Thomas the owner of the students directory, since he is tasked as being
in-charge of all Computer Science academia at the school.
As Administrators we never want to give our root credentials out to anyone. But at the
same time, we need to allow users the ability to do their job. So let's allow Dr. Terry
Thomas to take more control of the file structure and limit what students can do.
Now, each directory and subdirectory has an owner of drterryt and the owning group is
professors. Since the assignments directory is for students to turn assigned work in, let's
take away the ability to list and modify files from the students group.
39
Linux Admin
Students can copy assignments to the assignments directory. But they cannot list contents
of the directory, copy over current files, or modify files in the assignments directory. Thus,
it just allows the students to submit completed assignments. The CentOS filesystem will
provide a date-stamp of when assignments turned in.
We can see, the directory owner can list files as well as modify and remove files.
umask Command: Supplies the Default Modes for File and Directory
Permissions As They are Created
umask is an important command that supplies the default modes for File and Directory
Permissions as they are created.
Permission Operation
3 Read only
6 Execute only
7 No permissions
40
Linux Admin
[adama@centosLocal umask_tests]$ ls -l ./
-rw-r--r--. 1 adama students 0 Jan 10 00:27 myDir
-rw-r--r--. 1 adama students 0 Jan 10 00:27 myFile.txt
[adama@centosLocal umask_tests]$ whoami
adama
[adama@centosLocal umask_tests]$ umask
0022
[adama@centosLocal umask_tests]$
Now, let’s change the umask for our current user, and make a new file and directory.
As we can see, newly created files are a little more restrictive than before.
/etc/profile
~/bashrc
Newly supplied umasks will be destroyed when the operating system is restarted, set back
to the default of 0022.
Generally, the default umask in CentOS will be okay. When we run into trouble with a
default of 0022, is usually when different departments belonging to different groups need
to collaborate on projects.
This is where the role of a system administrator comes in, to balance the operations and
design of the CentOS operating system.
41
4. Linux Admin ─ User Management Linux Admin
Users
Groups
Permissions
We have already discussed in-depth permissions as applied to files and folders. In this
chapter, let's discuss about users and groups.
CentOS Users
In CentOS, there are two types accounts:
System accounts are used by daemons to access files and directories. These will
usually be disallowed from interactive login via shell or physical console login.
With this basic understanding of users, let's now create a new user for Bob Jones in the
Accounting Department. A new user is added with the adduser command.
Switch Action
When creating a new user, use the -c, -m, -g, -n switches as follows:
42
Linux Admin
Now we need to enable the new account using the passwd command:
The user account is not enabled allowing the user to log into the system.
Now let’s use the chage command, changing the password expiry date to a previous date.
Also, it may be good to make a note on the account as to why we disabled it.
Manage Groups
Managing groups in Linux makes it convenient for an administrator to combine the users
within containers applying permission-sets applicable to all group members. For example,
all users in Accounting may need access to the same files. Thus, we make an accounting
group, adding Accounting users.
For the most part, anything requiring special permissions should be done in a group. This
approach will usually save time over applying special permissions to just one user.
Example, Sally is in-charge of reports and only Sally needs access to certain files for
43
Linux Admin
reporting. However, what if Sally is sick one day and Bob does reports? Or the need for
reporting grows? When a group is made, an Administrator only needs to do it once. The
add users is applied as needs change or expand.
chgrp
groupadd
groups
usermod
Let's make a directory for people in the accounting group to store files and create
directories for files.
Now, everyone in the accounting group has read and execute permissions to
/home/accounting. They will need write permissions as well.
Since the accounting group may deal with sensitive documents, we need to apply some
restrictive permissions for other or world.
44
Linux Admin
Switch Action
Let's make a new group called secret. We will add a password to the group, allowing the
users to add themselves with a known password.
In practice, passwords for groups are not used often. Secondary groups are adequate and
sharing passwords amongst other users is not a great security practice.
The groups command is used to show which group a user belongs to. We will use this,
after making some changes to our current user.
Switch Action
45
Linux Admin
46
5. Linux Admin ─ Quota ManagementLinux Admin
CentOS disk quotas can be enabled both; alerting the system administrator and denying
further disk-storage-access to a user before disk capacity is exceeded. When a disk is full,
depending on what resides on the disk, an entire system can come to a screeching halt
until recovered.
We now have a copy of our known working /etc/fstab in the current working directory.
#
# /etc/fstab
# Created by anaconda on Sat Dec 17 02:44:51 2016
#
# Accessible filesystems, by reference, are maintained under '/dev/disk'
# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info
#
/dev/mapper/cl-root / xfs defaults 0 0
UUID=4b9a40bc-9480-4 /boot xfs defaults 0 0
/dev/mapper/cl-home /home xfs
defaults,usrquota,grpquota 0 0
/dev/mapper/cl-swap swap swap defaults 0 0
We made the following changes in the options section of /etc/fstab for the volume or Label
to where quotas are to be applied for users and groups.
usrquota
grpquota
As you can see, we are using the xfs filesystem. When using xfs there are extra manual
steps involved. /home is on the same disk as /. Further investigation shows / is set for
47
Linux Admin
noquota, which is a kernel level mounting option. We must re-configure our kernel boot
options.
When the disk/partition we are enabling quotas on, is using the xfs file system
When the kernel is passing noquota parameter to /etc/fstab at boot time
cp /etc/default/grub ~/
GRUB_TIMEOUT=5
GRUB_DISTRIBUTOR="$(sed 's, release .*$,,g' /etc/system-release)"
GRUB_DEFAULT=saved
GRUB_DISABLE_SUBMENU=true
GRUB_TERMINAL_OUTPUT="console"
GRUB_CMDLINE_LINUX="crashkernel=auto rd.lvm.lv=cl/root rd.lvm.lv=cl/swap rhgb
quiet"
GRUB_DISABLE_RECOVERY="true"
to
Note: It is important we copy these changes verbatim. After we reconfigure grub.cfg, our
system will fail to boot if any errors were made in the configuration. Please, try this part
of the tutorial on a non-production system.
cp /boot/grub2/grub.cfg /boot/grub2/grub.cfg.bak
48
Linux Admin
Reboot
[root@localhost rdc]#reboot
If all modifications were precise, we should not have the availability to add quotas to the
xfs file system.
Now, again edit /etc/fstab to include / since /homeon the same physical disk.
/dev/mapper/cl-root / xfs
defaults,usrquota,grpquota 0 0
49
Linux Admin
[rdc@localhost ~]$ df
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/mapper/cl-root 22447404 4081860 18365544 19% /
devtmpfs 903448 0 903448 0% /dev
tmpfs 919308 100 919208 1% /dev/shm
tmpfs 919308 9180 910128 1% /run
tmpfs 919308 0 919308 0% /sys/fs/cgroup
/dev/sda2 1268736 176612 1092124 14% /boot
/dev/mapper/cl-var 4872192 158024 4714168 4% /var
/dev/mapper/cl-home 18475008 37284 18437724 1% /home
tmpfs 183864 8 183856 1% /run/user/1000
[rdc@localhost ~]$
As we can see, LVM volumes are in use. So it's simple to just reboot. This will remount
/home and load the /etc/fstab configuration changes into active configuration.
aquota.user
aquota.group
These are used to store quota information for the quota enabled disks/partitions.
Switch Action
-u Checks for user quotas
-g Checks for group quotas
-c Quotas should be enabled for each file system with enables quotas
50
Linux Admin
hard: Set blocks for a hard limit. Hard limit is total allowable quota
inodes: How many inodes the user is currently using
soft: Soft inode limit
hard : Hard inode limit
Following is an error given to a user when the hard quota limit has exceeded.
As we can see, we are closely within this user's disk quota. Let's set a soft limit warning.
This way, the user will have advance notice before quota limits expire. From experience,
you will get end-user complaints when they come into work and need to spend 45 minutes
clearing files to actually get to work.
51
Linux Admin
As we can see, the user centos has exceeded their hard block quota and can no longer use
any more disk space on /home.
52
6. Linux Admin ─ Systemd Services Start &Linux
Stop Admin
systemd is the new way of running services on Linux. systemd has a superceded sysvinit.
systemd brings faster boot-times to Linux and is now, a standard way to manage Linux
services. While stable, systemd is still evolving.
systemd as an init system, is used to manage both services and daemons that need status
changes after the Linux kernel has been booted. By status change starting, stopping,
reloading, and adjusting service state is applied.
First, let's check the version of systemd currently running on our server.
As of CentOS version 7, fully updated at the time of this writing systemd version 219 is
the current stable version.
We can also analyze the last server boot time with systemd-analyze
When the system boot times are slower, we can use the systemd-analyze blame command.
53
Linux Admin
436ms udisks2.service
398ms sshd.service
360ms boot.mount
336ms polkit.service
321ms accounts-daemon.service
When working with systemd, it is important to understand the concept of units. Units are
the resources systemd knows how to interpret. Units are categorized into 12 types as
follows:
.service
.socket
.device
.mount
.automount
.swap
.target
.path
.timer
.snapshot
.slice
.scope
For the most part, we will be working with .service as unit targets. It is recommended to
do further research on the other types. As only .service units will apply to starting and
stopping systemd services.
Switch Action
-t Comma separated value of unit types such as service or socket
-a Shows all loaded units
--state Shows all units in a defined state, either: load, sub, active, inactive, etc..
Executes operation remotely. Specify Host name or host and user separated
-H
by @.
54
Linux Admin
Stopping a Service
Let's first, stop the bluetooth service.
55
Linux Admin
Start To bring a service up that has been put in the stopped state.
Disable Used primarily when there is a need to stop a service, but it starts on boot.
56
Linux Admin
Show us the current status of the networking service. If we want to see all the services
related to networking, we can use:
For those familiar with the sysinit method of managing services, it is important to make
the transition to systemd. systemd is the new way starting and stopping daemon services
in Linux.
57
7. Linux Admin ─ Resource Mgmt with systemctl
Linux Admin
systemctl is the utility used to control systemd. systemctl provides CentOS administrators
with the ability to perform a multitude of operations on systemd including:
The command syntax for systemctl is pretty basic, but can tangle with switches and
options. We will present the most essential functions of systemctl needed for administering
CentOS Linux.
start
stop
restart
reload
status
is-active
list-units
enable
disable
cat
show
We have already discussed start, stop, reload, restart, enable and disable with systemctl.
So let's go over the remaining commonly used commands.
status
In its most simple form, the status command can be used to see the system status as a
whole:
58
Linux Admin
Failed: 0 units
Since: Thu 2017-01-19 19:14:37 EST; 4h 5min ago
CGroup: /
├─1 /usr/lib/systemd/systemd --switched-root --system --deserialize 21
├─user.slice
│ └─user-1002.slice
│ └─session-1.scope
│ ├─2869 gdm-session-worker [pam/gdm-password]
│ ├─2881 /usr/bin/gnome-keyring-daemon --daemonize --login
│ ├─2888 gnome-session --session gnome-classic
│ ├─2895 dbus-launch --sh-syntax --exit-with-session
The above output has been condensed. In the real-world systemctl status will output about
100 lines of treed process statuses.
As you see, our firewall service is currently active and has been for over 4 hours.
list-units
The list-units command allows us to list all the units of a certain type. Let's check for
sockets managed by systemd:
59
Linux Admin
is-active
The is-active command is an example of systemctl commands designed to return the
status information of a unit.
cat
cat is one of the seldomly used command. Instead of using cat at the shell and typing the
path to a unit file, simply use systemctl cat.
60
Linux Admin
[Unit]
Description=firewalld - dynamic firewall daemon
Before=network.target
Before=libvirtd.service
Before=NetworkManager.service
After=dbus.service
After=polkit.service
Conflicts=iptables.service ip6tables.service ebtables.service ipset.service
Documentation=man:firewalld(1)
[Service]
EnvironmentFile=-/etc/sysconfig/firewalld
ExecStart=/usr/sbin/firewalld --nofork --nopid $FIREWALLD_ARGS
ExecReload=/bin/kill -HUP $MAINPID
# supress to log debug and error output also to /var/log/messages
StandardOutput=null
StandardError=null
Type=dbus
BusName=org.fedoraproject.FirewallD1
[Install]
WantedBy=basic.target
Alias=dbus-org.fedoraproject.FirewallD1.service
[root@localhost]#
Now that we have explored both systemd and systemctl in more detail, let's use them to
manage the resources in cgroups or control groups.
61
8. Linux Admin ─ Resource Mgmt with crgoups
Linux Admin
cgroups or Control Groups are a feature of the Linux kernel that allows an administrator
to allocate or cap the system resources for services and also group.
To list active control groups running, we can use the following ps command:
Resource Management, as of CentOS 6.X, has been redefined with the systemd init
implementation. When thinking Resource Management for services, the main thing to
focus on are cgroups. cgroups have advanced with systemd in both functionality and
simplicity.
The goal of cgroups in resource management is -no one service can take the system, as a
whole, down. Or no single service process (perhaps a poorly written PHP script) will cripple
the server functionality by consuming too many resources.
CPU: Limit cpu intensive tasks that are not critical as other, less intensive tasks
Memory: Limit how much memory a service can consume
Disks: Limit disk i/o
**CPU Time: **
Tasks needing less CPU priority can have custom configured CPU Slices.
62
Linux Admin
[Service]
MemoryLimit=1M
ExecStart=/usr/bin/sha1sum /dev/zero
ExecStop=/bin/kill -WINCH ${MAINPID}
WantedBy=multi-user.target
# /etc/systemd/system/polite.service.d/50-CPUShares.conf
[Service]
CPUShares=1024
[root@localhost]#
[Service]
ExecStart=/usr/bin/md5sum /dev/zero
ExecStop=/bin/kill -WINCH ${MAINPID}
WantedBy=multi-user.target
# /etc/systemd/system/evil.service.d/50-CPUShares.conf
[Service]
CPUShares=1024
[root@localhost]#
63
Linux Admin
/system.slice/polite.service
1 70.5 124.0K - -
/system.slice/evil.service
1 99.5 304.0K - -
As we can see, over a period of normal system idle time, both rogue processes are still
using CPU cycles. However, the one set to have less time-slices is using less CPU time.
With this in mind, we can see how using a lesser time time-slice would allow essential
tasks better access the system resources.
To set services for each resource, the set-property method defines the following
parameters:
Most often services will be limited by CPU use, Memory limits and Read / Write IO.
After changing each, it is necessary to reload systemd and restart the service:
64
Linux Admin
As we can see, by default CentOS 7 has libcgroup installed with the everything installer.
Using a minimal installer will require us to install the libcgroup utilities along with any
dependencies.
65
9. Linux Admin ─ Process ManagementLinux Admin
Following are the common commands used with Process Management–bg, fg, nohup, ps,
pstree, top, kill, killall, free, uptime, nice.
In Linux every running process is given a PID or Process ID Number. This PID is how
CentOS identifies a particular process. As we have discussed, systemd is the first process
started and given a PID of 1 in CentOS.
Let's start using the shell command sleep. sleep will simply do as it is named, sleep for a
defined period of time: sleep.
66
Linux Admin
[root@CentOS ~]$ fg 1
sleep 10
If you are following along, you'll notice the foreground job is stuck in your shell. Now, let's
put the process to sleep, then re-enable it in the background.
Hit control+z
Type: bg 1, sending the first job into the background and starting it.
[root@CentOS ~]$ fg 1
sleep 20
^Z
[1]+ Stopped sleep 20
[root@CentOS ~]$ bg 1
[1]+ sleep 20 &
[root@CentOS ~]$
nohup
When working from a shell or terminal, it is worth noting that by default all the processes
and jobs attached to the shell will terminate when the shell is closed or the user logs out.
When using nohup the process will continue to run if the user logs out or closes the shell
to which the process is attached.
67
Linux Admin
ps Command
The ps command is commonly used by administrators to investigate snapshots of a specific
process. ps is commonly used with grep to filter out a specific process to analyze.
In the above command, we see all the processes using the python interpreter. Also
included with the results were our grep command, looking for the string python.
Following are the most common command line switches used with ps.
Switch Action
a Excludes constraints of only the reporting processes for the current user
x Shows processes not attached to a tty or shell
w Formats wide output display of the output
e Shows environment after the command
68
Linux Admin
See all the processes by user centos and format, displaying the custom output:
pstree Command
pstree is similar to ps but is not often used. It displays the processes in a neater tree
fashion.
69
Linux Admin
The total output from pstree can exceed 100 lines. Usually,ps will give more useful
information.
top Command
top is one of the most often used commands when troubleshooting performance issues in
Linux. It is useful for real-time stats and process monitoring in Linux. Following is the
default output of top when brought up from the command line.
70
Linux Admin
Common hot keys used while running top (hot keys are accessed by pressing the key as
top is running in your shell).
Command Action
b Enables / disables bold highlighting on top menu
z Cycles the color scheme
l Cycles the load average heading
h Help menu
Command Action
Sorting options screen in top, presented using Shift+F. This screen allows customization
of top display and sort options.
Fields Management for window 1:Def, whose current sort field is %MEM
Navigate with Up/Dn, Right selects for move then <Enter> or Left commits,
'd' or <Space> toggles display, 's' sets sort. Use 'q' or <Esc> to end!
71
Linux Admin
top, showing the processes for user rdc and sorted by memory usage:
72
Linux Admin
kill Command
The kill command is used to kill a process from the command shell via its PID. When killing
a process, we need to specify a signal to send. The signal lets the kernel know how we
want to end the process. The most commonly used signals are:
SIGTERM is implied as the kernel lets a process know it should stop soon as it is
safe to do so. SIGTERM gives the process an opportunity to exit gracefully and
perform safe exit operations.
SIGHUP most daemons will restart when sent SIGHUP. This is often used on the
processes when changes have been made to a configuration file.
SIGKILL since SIGTERM is the equivalent to asking a process to shut down. The
kernel needs an option to end a process that will not comply with requests. When
a process is hung, the SIGKILL option is used to shut the process down explicitly.
For a list off all signals that can be sent with kill the -l option can be used:
[root@CentOS]# kill -l
1) SIGHUP 2) SIGINT 3) SIGQUIT
4) SIGILL 5) SIGTRAP 6) SIGABRT 7) SIGBUS 8) SIGFPE 9) SIGKILL 10)
SIGUSR1 11) SIGSEGV 12) SIGUSR2 13) SIGPIPE 14) SIGALRM 15) SIGTERM
16) SIGSTKFLT 17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP 21) SIGTTIN
22) SIGTTOU 23) SIGURG 24) SIGXCPU 25) SIGXFSZ 26) SIGVTALRM 27) SIGPROF 28)
SIGWINCH 29) SIGIO 30) SIGPWR
31) SIGSYS 34) SIGRTMIN 35) SIGRTMIN+1 36) SIGRTMIN+2 37) SIGRTMIN+3 38)
SIGRTMIN+4 39) SIGRTMIN+5 40) SIGRTMIN+6 41) SIGRTMIN+7 42) SIGRTMIN+8 43)
SIGRTMIN+9 44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12 47) SIGRTMIN+13
48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14 51) SIGRTMAX-13 52) SIGRTMAX-12
53) SIGRTMAX-11 54) SIGRTMAX-10 55) SIGRTMAX-9 56) SIGRTMAX-8 57) SIGRTMAX-7
58) SIGRTMAX-6 59) SIGRTMAX-5 60) SIGRTMAX-4 61) SIGRTMAX-3 62) SIGRTMAX-2
63) SIGRTMAX-1 64) SIGRTMAX
[root@CentOS rdc]#
73
Linux Admin
1
464
500
643
15196
15197
15198
[root@CentOS]#
pkill will allow the administrator to send a kill signal by the process name.
killall will kill all the processes. Be careful using killall as root, as it will kill all the processes
for all users.
free Command
free is a pretty simple command often used to quickly check the memory of a system. It
displays the total amount of used physical and swap memory.
[root@CentOS]# free
total used free shared buff/cache available
Mem: 1879668 526284 699796 10304 653588
1141412
Swap: 3145724 0 3145724
[root@CentOS]#
nice Command
nice will allow an administrator to set the scheduling priority of a process in terms of CPU
usages. The niceness is basically how the kernel will schedule CPU time slices for a process
or job. By default, it is assumed the process is given equal access to CPU resources.
First, let's use top to check the niceness of the currently running processes.
74
Linux Admin
We want to focus on the NICE column depicted by NI. The niceness range can be anywhere
between -20 to positive 19. -20 represents the highest given priority.
renice
renice allows us to change the current priority of a process that is already running.
renice 17 -p 30727
The above command will lower the priority of our ping process command.
75
10. Linux Admin ─ Firewall Setup Linux Admin
firewalld is the default front-end controller for iptables on CentOS. The firewalld front-end
has two main advantages over raw iptables:
Rulesets are dynamic, meaning stateful connections are uninterrupted when the
settings are changed and/or modified.
Remember, firewalld is the wrapper for iptables - not a replacement. While custom iptables
commands can be used with firewalld, it is recommended to use firewalld as to not break
the firewall functionality.
We can see, firewalld is both active (to start on boot) and currently running. If inactive or
not started we can use:
Now that we have our firewalld service configured, let's assure it is operational.
Firewalld works on the concept of zones. A zone is applied to network interfaces through
the Network Manager. We will discuss this in configuring networking. But for now, by
default, changing the default zone will change any network adapters left in the default
state of "Default Zone".
76
Linux Admin
Let's take a quick look at each zone that comes out-of-the-box with firewalld.
Zone Description
Low trust level. All incoming connections and packetsare dropped and only
drop
outgoing connections are possible via statefullness
Incoming connections are replied with an icmp message letting the initiator
block
know the request is prohibited
All networks are restricted. However, selected incoming connections can be
public
explicitly allowed
external Configures firewalld for NAT. Internal network remains private but reachable
Only certain incoming connections are allowed. Used for systems in DMZ
dmz
isolation
All machines on the network are trusted. Most incoming connections are
trusted allowed unfettered. This is not meant for interfaces exposed to the
Internet
The most common zones to use are:public, drop, work, and home.
public: It is the most common zone used by an administrator. It will let you apply
the custom settings and abide by RFC specifications for operations on a LAN.
work: You are on a semi-secure corporate LAN. Where all traffic can be assumed
moderately safe. This means it is not WiFi and we possibly have IDS, IPS, and
physical security or 802.1x in place. We also should be familiar with the people
using the LAN.
home: You are on a home LAN. You are personally accountable for every system
and the user on the LAN. You know every machine on the LAN and that none have
been compromised. Often new services are brought up for media sharing amongst
trusted individuals and you don't need to take extra time for the sake of security.
Zones and network interfaces work on a one to many level. One network interface can
only have a single zone applied to it at a time. While, a zone can be applied to many
interfaces simultaneously.
77
Linux Admin
Let's see what zones are available and what are the currently applied zone.
First, let's see what our box looks like, to a portscanner from outside.
Then, set the rule allowing port 80 to the current default zone.
78
Linux Admin
Let's put the default zone to drop and see what happens to port scan.
Now let's scan the host with the network interface in a more secure zone.
79
Linux Admin
As demonstrated below, the host will not even respond to ICMP ping requests when in
drop.
As configured, our port 80 filter rule is only within the context of the running configuration.
This means once the system is rebooted or the firewalld service is restarted, our rule will
be discarded.
80
Linux Admin
We will be configuring an httpd daemon soon, so let's make our changes persistent:
Now our port 80 rule in the public zone is persistent across reboots and service restarts.
Command Action
Lists all zones that can be applied to an
firewall-cmd --get-zones
interface
Returns the currents status of the firewalld
firewall-cmd —status
service
firewall-cmd --set-default-zone=<zone> Sets the default zone into the current context
81
11. Linux Admin ─ Configure PHP in CentOS Linux
Linux Admin
PHP is the one of the most prolific web languages in use today. Installing a LAMP Stack on
CentOS is something every system administrator will need to perform, most likely sooner
than later.
Web Server
Web Development Platform / Language
Database Server
Note: The term LAMP Stack can also include the following technologies: PostgreSQL,
MariaDB, Perl, Python, Ruby, NGINX Webserver.
For this tutorial, we will stick with the traditional LAMP Stack of CentOS GNU Linux: Apache
web server, MySQL Database Server, and PHP.
We will actually be using MariaDB. MySQL configuration files, databases and tables are
transparent to MariaDB. MariaDB is now included in the standard CentOS repository
instead of MySQL. This is due to the limitations of licensing and open-source compliance,
since Oracle has taken over the development of MySQL.
82
Linux Admin
Dependency Installed:
httpd-tools.x86_64 0:2.4.6-45.el7.centos
mailcap.noarch 0:2.1.41-2.el7
Complete!
[root@CentOS]#
As you can see by the nmap service probe, Apache webserver is listening and responding
to requests on the CentOS host.
83
Linux Admin
mariadb-server.x86_64
The main MariaDB Server daemon package.
mariadb-devel.x86_64
Files need to compile from the source with MySQL/MariaDB compatibility.
mariadb.x86_64
MariaDB client utilities for administering MariaDB Server from the command line.
mariadb-libs.x86_64
Common libraries for MariaDB that could be needed for other applications compiled with
MySQL/MariaDB support.
Note: Unlike Apache, we will not enable connections to MariaDB through our host-based
firewall (firewalld). When using a database server, it's considered best security practice to
only allow local socket connections, unless the remote socket access is specifically needed.
As we can see, MariaDB is listening on port 3306 tcp. We will leave our host-based firewall
(firewalld) blocking incoming connections to port 3306.
84
Linux Admin
I'd recommend installing the following php packages for common compatibility:
php-common.x86_64
php-mysql.x86_64
php-mysqlnd.x86_64
php-pdo.x86_64
php-soap.x86_64
php-xml.x86_64
This is our simple php file located in the Apache webroot of /var/www/html/
Let's change the owning group of our page to the system user our http daemon is running
under.
---
85
Linux Admin
PHP and LAMP are very popular web-programming technologies. LAMP installation and
configuration is sure to come up on your list of needs as a CentOS Administrator. Easy to
use CentOS packages have taken a lot of work from compiling Apache, MySQL, and PHP
from the source code.
86
12. Linux Admin ─ Set Up Python with CentOSLinux
Linux
Admin
Python is a widely used interpreted language that has brought professionalism to the world
of coding scripted applications on Linux (and other operating systems). Where Perl was
once the industry standard, Python has surpassed Perl in many respects.
Python can do anything Perl can do, and in a lot of cases in a better manner. Though Perl
still has its place amongst the toolbox of a Linux admin, learning Python is a great choice
as a skill set.
The biggest drawbacks of Python are sometimes related to its strengths. In history, Python
was originally designed to teach programming. At times, its core foundations of "easily
readable" and "doing things the right way" can cause unnecessary complexities when
writing a simple code. Also, its standard libraries have caused problems in transitioning
from versions 2.X to 3.X.
Python scripts are actually used at the core of CentOS for functions vital to the functionality
of the operating system. Because of this, it is important to isolate our development Python
environment from CentOS' core Python environment.
For starters, there are currently two versions of Python: Python 2.X and Python 3.X.
Both stages are still in active production, though version 2.X is quickly closing in on
depreciation (and has been for a few years). The reason for the two active versions of
Python was basically fixing the shortcomings of version 2.X. This required some core
functionality of version 3.X to be redone in ways it could not support some version 2.X
scripts.
Basically, the best way to overcome this transition is: Develop for 3.X and keep up with
the latest 2.X version for legacy scripts. Currently, CentOS 7.X relies on a semi-current
revision of version 2.X.
As of this writing, the most current versions of Python are: 3.4.6 and 2.7.13.
Don't let this confuse or draw any conclusions of Python. Setting up a Python environment
is really pretty simple. With Python frameworks and libraries, this task is actually really
easy to accomplish.
87
Linux Admin
Before setting up our Python environments, we need a sane environment. To start, let's
make sure our CentOS install is fully updated and get some building utilities installed.
Now we need to install current Python 2.X and 3.X from source.
Let's start by creating a build directory for each Python install in /usr/src/
88
Linux Admin
Note: Be sure to use altinstall and not install. This will keep CentOS and development
versions of Python separated. Otherwise, you may break the functionality of CentOS.
You will now see the compilation process begins. Grab a cup of coffee and take a 15-
minute break until completion. Since we installed all the needed dependencies for Python,
the compilation process should complete without error.
Let's make sure we have the latest 2.X version of Python installed.
Note: You will want to prefix the shebang line pointing to our development environment
for Python 2.X.
Just like that, we have separate Python installs for versions 2.X and 3.X. From here, we
can use each and utilities such as pip and virtualenv to further ease the burden of
managing Python environments and package installation.
89
13. Linux Admin ─ Configure Ruby on CentOSLinux
Linux
Admin
Ruby is a great language for both web development and Linux Administration. Ruby
provides many benefits found in all the previous languages discussed: PHP, Python, and
Perl.
To install Ruby, it is best to bootstrap through the rbenv which allows the administrators
to easily install and manage Ruby Environments.
The other method for installing Ruby is the standard CentOS packages for Ruby. It is
advisable to use the rbenv method with all its benefits. CentOS packages will be easier for
the non-Ruby savvy.
git-core
zlib
zlib-devel
gcc-c++
patch
readline
readline-devel
libyaml-devel
libffi-devel
openssl-devel
make
bzzip2
autoconf
automake
libtool
bison
curl
sqlite-devel
90
Linux Admin
Most of these packages may already be installed depending on the chosen options and
roles when installing CentOS. It is good to install everything we are unsure about as this
can lead to less headache when installing packages requiring dependencies.
Let's set our shell for rbenv and assure we have installedthe correct options.
91
Linux Admin
whence Lists all Ruby versions that contain the given executable
We now have a working Ruby environment with an updated and working version of Ruby
2.X branch.
92
14. Linux Admin – Set Up Perl for CentOS Linux
Linux Admin
Perl has been around for a long time. It was originally designed as a reporting language
used for parsing text files. With increased popularity, Perl has added a module support or
CPAN, sockets, threading, and other features needed in a powerful scripting language.
The biggest advantage of Perl over PHP, Python, or Ruby is: it gets things done with
minimal fuss. This philosophy of Perl does not always mean it gets things done the right
way. However, for administration tasks on Linux, Perl is considered as the go-to choice for
a scripting language.
Perl makes writing scripts quick and dirty (usually a Perl script will be several dozen
lines shorter than an equivalent in Python or Ruby)
Typically, there isn't a lot of thought put into standardization and best-practice
when Perl is used.
When deciding whether to use Perl, Python or PHP; the following questions should be
asked:
If the answers to all the above are "no", Perl is a good choice and may speed things up in
terms of end-results.
With this mentioned, let's configure our CentOS server to use the most recent version of
Perl.
Before installing Perl, we need to understand the support for Perl. Officially, Perl is only
supported far back as the last two stable versions. So, we want to be sure to keep our
development environment isolated from the CentOS version.
The reason for isolation is: if someone releases a tool in Perl to the CentOS community,
more than likely it will be modified to work on Perl as shipped with CentOS. However, we
also want to have the latest version installed for development purposes. Like Python,
CentOS ships Perl focused on the reliability and not cutting edge.
93
Linux Admin
[root@CentOS]# perl -v
This is perl 5, version 16, subversion 3 (v5.16.3) built for x86_64-linux-
thread-multi
We are currently running Perl 5.16.3. The most current version as of this writing is: perl-
5.24.0
We definitely want to upgrade our version, being able to use up-to-date Perl modules in
our code. Fortunately, there is a great tool for maintaining Perl environments and keeping
our CentOS version of Perl isolated. It is called perlbrew.
Now that we have Perl Brew installed, let's make an environment for the latest version of
Perl.
First, we will need the currently installed version of Perl to bootstrap the perlbrew install.
Thus, let's get some needed Perl modules from the CentOS repository.
Note: When available we always want to use CentOS Perl modules versus CPAN with our
CentOS Perl installation.
n - No tests
j4 - Execute 4 threads in parallel for the installation routines (we are using a
quadcore CPU)
94
Linux Admin
After our installation has been performed successfully, let's switch to our newest Perl
environment.
[root@CentOS]# perl -v
Perl may be copied only under the terms of either the Artistic License or the
GNU General Public License, which may be found in the Perl 5 source kit.
[root@CentOS]#
Simple perl script printing perl version running within the context of our perlbrew
environment:
Once perl is installed, we can load cpan modules with perl brew's cpanm:
95
Linux Admin
Now let's use the cpanm installer to make the LWP module with our current Perl version
of 5.24.1 in perl brew.
A sub-shell is launched with perl-5.24.1 as the activated perl. Run 'exit' to finish it.
[root@CentOS ~]#
Step 3: Now let's test our Perl environment with the new CPAN module.
There you have it! Perl Brew makes isolating perl environments a snap and can be
considered as a best practice as things get with Perl.
96
15. Linux Admin ─ Install & Configure Open LDAP
Linux Admin
LDAP known as Light Weight Directory Access Protocol is a protocol used for accessing
X.500 service containers within an enterprise known from a directory. Those who are
familiar with Windows Server Administration can think of LDAP as being very similar in
nature to Active Directory. It is even a widely used concept of intertwining Windows
workstations into an OpenLDAP CentOS enterprise. On the other spectrum, a CentOS Linux
workstation can share resources and participate with the basic functionality in a Windows
Domain.
Deploying LDAP on CentOS as a Directory Server Agent, Directory System Agent, or DSA
(these acronyms are all one and the same) is similar to older Novell Netware installations
using the Directory Tree structure with NDS.
While DAP uses the full OSI Model. With the advent of the Internet, TCP/IP and Ethernet
prominence in networks of today, it is rare to come across a Directory Services
implantation using both DAP and native X.500 enterprise directories outside specific legacy
computing models.
The main components used with openldap for CentOS Linux are:
Note: When naming your enterprise, it is a best practice to use the .local TLD. Using a
.net or .com can cause difficulties when segregating an online and internal domain
infrastructure. Imagine the extra work for a company internally using acme.com for both
external and internal operations. Hence, it can be wise to have Internet resources called
acme.com or acme.net. Then, the local networking enterprise resources is depicted as
acme.local. This will entail configuring DNS records, but will pay in simplicity, eloquence
and security.
97
Linux Admin
Dependencies Resolved
===============================================================================
===============================================================================
Package Arch
Version Repository Size
===============================================================================
===============================================================================
Installing:
openldap-clients x86_64
2.4.40-13.el7 base 188 k
openldap-servers x86_64
2.4.40-13.el7 base 2.1 M
Transaction Summary
===============================================================================
===============================================================================
98
Linux Admin
Install 2 Packages
Installed:
openldap-clients.x86_64 0:2.4.40-13.el7
openldap-servers.x86_64 0:2.4.40-13.el7
Complete!
[root@localhost]#
root@localhost]# ls /etc/openldap/
certs check_password.conf ldap.conf schema slapd.d
[root@localhost]#
[root@localhost]# id ldap
uid=55(ldap) gid=55(ldap) groups=55(ldap)
[root@localhost]#
99
Linux Admin
[root@localhost]# slappasswd
New password:
Re-enter new password:
{SSHA}20RSyjVv6S6r43DFPeJgASDLlLoSU8g.a10
[root@localhost]#
First, we want to set up our openLDAP environment. Following is a template to use with
the ldapmodify command.
dn: olcDatabase={2}hdb,cn=config
changetype: modify
replace: olcSuffix
olcSuffix: dc=vmnet,dc=local
dn: olcDatabase={2}hdb,cn=config
changetype: modify
replace: olcRootDN
olcRootDN: cn=ldapadm,dc=vmnet,dc=local
dn: olcDatabase={2}hdb,cn=config
changetype: modify
replace: olcRootPW
olcRootPW: <output from slap
100
Linux Admin
Next, we want to create an self-signed ssl certificate for OpenLDAP. This will secure the
communication between the enterprise server and clients.
We will use openssl to create a self-signed ssl certificate. Go to the next chapter, Create
LDAP SSL Certificate with openssl for instructions to secure communications with
OpenLDAP. Then when ssl certificates are configured, we will have completed our
OpenLDAP enterprise configuration.
101
Linux Admin
dn: cn=config
changetype: modify
replace: olcTLSCertificateFile
olcTLSCertificateFile: /etc/openldap/certs/yourGeneratedCertFile.pem
dn: cn=config
changetype: modify
replace: olcTLSCertificateKeyFile
olcTLSCertificateKeyFile: /etc/openldap/certs/youGeneratedKeyFile.pem
Next, again, use the ldapmodify command to merge the changes into the OpenLDAP
configuration.
[root@centos]# slaptest -u
config file testing succeeded
[root@centos]#
Finally, create the enterprise schema and add it to the current OpenLDAP configuration.
102
Linux Admin
Following is for a domain called vmnet.local with an LDAP Admin called ldapadm.
dn: dc=vmnet,dc=local
dc: vmnet
objectClass: top
objectClass: domain
dn: ou=People,dc=vmnet,dc=local
objectClass: organizationalUnit
ou: People
dn: ou=Group,dc=vmnet,dc=local
objectClass: organizationalUnit
ou: Group
[root@centos]#
Open vim or your favorite text editor and copy the following format. This is setup for a
user named "entacct" on the "vmnet.local" LDAP domain.
dn: uid=entacct,ou=People,dc=vmnet,dc=local
objectClass: top
103
Linux Admin
objectClass: account
objectClass: posixAccount
objectClass: shadowAccount
cn: entacct
uid: entacct
uidNumber: 9999
gidNumber: 100
homeDirectory: /home/enyacct
loginShell: /bin/bash
gecos: Enterprise User Account 001
userPassword: {crypt}x
shadowLastChange: 17058
shadowMin: 0
shadowMax: 99999
shadowWarning: 7
Now import the above files, as saved, into the OpenLdap Schema.
Before the users can access the LDAP Enterprise, we need to assign a password as follows:
Finally, before logging into the Enterprise account, let's check our OpenLDAP entry.
104
Linux Admin
# requesting: ALL
#
# entacct, People, vmnet.local
dn: uid=entacct,ou=People,dc=vmnet,dc=local
objectClass: top
objectClass: account
objectClass: posixAccount
objectClass: shadowAccount
cn: entacct
uid: entacct
uidNumber: 9999
gidNumber: 100
homeDirectory: /home/enyacct
loginShell: /bin/bash
gecos: Enterprise User Account 001
userPassword:: e2NyeXB0fXg=
shadowLastChange: 17058
shadowMin: 0
shadowMax: 99999
shadowWarning: 7
105
Linux Admin
Step 6: Finally, we need to allow access to the slapd service so it can service requests.
106
16. Linux Admin ─ Create SSL CertificatesLinux Admin
SSL goes up to version 3.0. SSL was developed and promoted as an industry standard
under Netscape. After Netscape was purchased by AOL (an ISP popular in the 90's
otherwise known as America Online) AOL never really promoted the change needed for
security improvements to SSL.
At version 3.1, SSL technology moved into the open systems standards and was changed
to TLS. Since copyrights on SSL were still owned by AOL a new term was coined: TLS -
Transport Layer Security. So it is important to acknowledge that TLS is in fact different
from SSL. Especially, as older SSL technologies have known security issues and some are
considered obsolete today.
Note: This tutorial will use the term TLS when speaking of technologies 3.1 and higher.
Then SSL when commenting specific to SSL technologies 3.0 and lower.
TLS SSL
- 3.0
1.0 3.1
1.1 3.2
1.2 3.3
TLS performs two main functions important to the users of the Internet today: One, it
verifies who a party is, known as authentication. Two, it offers end-to-end encryption
at the transport layer for upper level protocols that lack this native feature (ftp, http, email
protocols, and more).
The first, verifies who a party is and is important to security as end-to-end encryption. If
a consumer has an encrypted connection to a website that is not authorized to take
payment, financial data is still at risk. This is what every phishing site will fail to have: a
properly signed TLS certificate verifying website operators are who they claim to
be from a trusted CA.
There are only two methods to get around not having a properly signed certificate: trick
the user into allowing trust of a web-browser for a self-signed certificate or hope the user
107
Linux Admin
is not tech savvy and will not know the importance of a trusted Certificate Authority (or a
CA).
In this tutorial, we will be using what is known as a self-signed certificate. This means,
without explicitly giving this certificate the status of trusted in every web browser visiting
the web-site, an error will be displayed discouraging the users from visiting the site. Then,
it will make the user jump though a few actions before accessing a site with a self-signed
certificate. Remember for the sake of security this is a good thing.
openssl is important, as it provides transport layer security and abstracts the detailed
programming of Authentication and end-to-end encryption for a developer. This is why
openssl is used with almost every single open-source application using TLS. It is also
installed by default on every modern version of Linux.
By default, openssl should be installed on CentOS from at least version 5 onwards. Just to
assure, let's try installing openssl via YUM. Just run install, as YUM is intelligent enough to
let us know if a package is already installed. If we are running an older version of CentOS
for compatibility reasons, doing a yum -y install will ensure openssl is updated against the
semi-recent heart-bleed vulnerability.
When running the installer, it was found there was actually an update to openssl.
===============================================================================
===============================================================================
Package Arch Version
Repository Size
===============================================================================
===============================================================================
Updating:
openssl x86_64
1:1.0.1e-60.el7_3.1 updates
713 k
Updating for dependencies:
108
Linux Admin
[root@centos]# ls /etc/openldap/certs/*.pem
/etc/openldap/certs/vmnetcert.pem /etc/openldap/certs/vmnetkey.pem
[root@centos]#
109
Linux Admin
As you can see, we have both the certificate and key installed in the /etc/openldap/certs/
directories. Finally, we need to change the permissions to each, since they are currently
owned by the root user.
First we need to configure Apache with mod_ssl. Using the YUM package manager this is
pretty simple:
Then reload your Apache daemon to ensure Apache uses the new configuration.
At this point, Apache is configured to support TLS connections on the local host.
Note: Be sure only the root has read/write access to this directory. With world read/write
access, your private key can be used to decrypt sniffed traffic.
[root@centos]# sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout
/etc/ssl/private/self-gen-apache.key -out /etc/ssl/certs/self-sign-apache.crt
Generating a 2048 bit RSA private key
..........+++
....+++
-----
110
Linux Admin
Note: You can use public IP Address of the server if you don't have a registered domain
name.
111
Linux Admin
ff:50:08:dc:c8:f0:67:75:12:ab:cd:8d:3e:7b:59:
e0:83:64:5d:0c:ab:93:e2:1c:78:f0:f4:80:9e:42:
7d:49:57:71:a2:96:c6:b8:44:16:93:6c:62:87:0f:
5c:fe:df:29:89:03:6e:e5:6d:db:0a:65:b2:5e:1d:
c8:07:3d:8a:f0:6c:7f:f3:b9:32:b4:97:f6:71:81:
6b:97:e3:08:bd:d6:f8:19:40:f1:15:7e:f2:fd:a5:
12:24:08:39:fa:b6:cc:69:4e:53:1d:7e:9a:be:4b:
Here is an explanation for each option we used with the openssl command:
Command Action
req -X509 Use X.509 CSR management PKI standard for key management.
Do not secure our certificate with a passphrase. Apache must be able
-nodes
to use the certificate without interruption of a passphrase.
Tells the validity of the certificate to 7 years or 2555 days. Time period
-days 2555
can be adjusted as needed.
-newkey Specified to generate both key and certificate using RSA at 2048 bits
rsa:2048 in length.
Next, we want to create a Diffie-Heliman group for negotiating PFS with clients.
Perfect Forward Secrecy: Used to secure session data in case the private key has been
compromised. This will generate a key used between the client and the server that is
unique for each session.
We will make the following changes to ssl.conf. However, before we do that we should
back the original file up. When making changes to a production server in an advanced text
editor like vi or emcas, it is a best practice to always backup configuration files before
making edits.
[root@centos]# cp /etc/httpd/conf.d/ssl.conf ~/
112
Linux Admin
Now let's continue our edits after copying a known-working copy of ssl.conf to the root of
our home folder.
Locate
Edit both DocumentRoot and ServerName as follows.
\\# General setup for the virtual host, inherited from global configuration
DocumentRoot "/var/www/html"
ServerName centos.vmnet.local:443
DocumentRoot this is the path to your default apache directory. In this folder should be
a default page that will display a HTTP request asking for the default page of your web
server or site.
ServerName is the server name that can be either an ip address or the host name of the
server. For TLS, it is a best practice to create a certificate with a host name. From our
OpenLdap tutorial, we created a hostname of centos on the local enterprise domain:
vmnet.local.
SSLProtocol
Then let Apache know where to find our certificate and private/public key pair.
# Server Certificate:
# Point SSLCertificateFile at a PEM encoded certificate. If
# the certificate is encrypted, then you will be prompted for a
# pass phrase. Note that a kill -HUP will prompt again. A new
# certificate can be generated using the genkey(1) command.
~~~~> SSLCertificateFile /etc/ssl/certs/self-sign-apache.crt
specify path to our private key file
# Server Private Key:
113
Linux Admin
114
17. Linux Admin : Install Apache Web Server CentOS 7
Linux Admin
In this chapter, we will learn a little about the background of how Apache HTTP Server
came into existence and then install the most current stable version on CentOS Linux 7.
Apache started out as a rather small project at the National Center for Supercomputing
Applications also known as NCSA. In the mid-90's "httpd", as it was called, was by far the
most popular web-server platform on the Internet, having about 90% or more of the
market share.
At this time, it was a simple project. Skilled I.T. staff known as webmaster were
responsible for: maintaining web server platforms and web server software as well as both
front-end and back-end site development. At the core of httpd was its ability to use custom
modules known as plugins or extensions. A webmaster was also skilled enough to write
patches to core server software.
Sometime in the late-mid-90's, the senior developer and project manager for httpd left
NCSA to do other things. This left the most popular web-daemon in a state of stagnation.
Since the use of httpd was so widespread a group of seasoned httpd webmasters called
for a summit reqarding the future of httpd. It was decided to coordinate and apply the
best extensions and patches into a current stable release. Then, the current grand-daddy
of http servers was born and christened Apache HTTP Server.
Little Known Historical Fact: Apache was not named after a Native American Tribe of
warriors. It was in fact coined and named with a twist: being made from many fixes (or
patches) from many talented Computer Scientists: a patchy or Apache.
With a default Apache install, the configuration file for Apache is named httpd.conf and is
located in /etc/httpd/. So, let's open it in vim.
#
# This is the main Apache HTTP server configuration file. It contains the
# configuration directives that give the server its instructions.
115
Linux Admin
We will make the following changes to allow our CentOS install to serve http requests from
http port 80.
From here, we change Apache to listen on a certain port or IP Address. For example, if we
want to run httpd services on an alternative port such as 8080. Or if we have our web-
server configured with multiple interfaces with separate IP addresses.
Listen:
Keeps Apache from attaching to every listening daemon onto every IP Address. This is
useful to stop specifying only IPv6 or IPv4 traffic. Or even binding to all network interfaces
on a multi-homed host.
#
# Listen: Allows you to bind Apache to specific IP addresses and/or
# ports, instead of the default. See also the <VirtualHost>
# directive.
#
# Change this to Listen on specific IP addresses as shown below to
# prevent Apache from glomming onto all bound IP addresses.
#
Listen 10.0.0.25:80
#Listen 80
116
Linux Admin
DocumentRoot:
The "document root" is the default directory where Apache will look for an index file to
serve for requests upon visiting your sever: http://www.yoursite.com/ will retrieve and
serve the index file from your document root.
#
# DocumentRoot: The directory out of which you will serve your
# documents. By default, all requests are taken from this directory, but
# symbolic links and aliases may be used to point to other locations.
#
DocumentRoot "/var/www/html"
117
18. Linux Admin ─ MySQL Setup On CentOS 7
Linux Admin
As touched upon briefly when configuring CentOS for use with Maria DB, there is no native
MySQL package in the CentOS 7 yum repository. To account for this, we will need to add
a MySQL hosted repository.
So when deciding whether to use Maria or MySQL one should weigh two options: Will my
current DB Schema work with Maria? What advantage does installing MySQL over Maria
give me?
Maria components are 100% transparent to MySQL structure, with some added efficiency
with better licensing. Unless a compelling reason comes along, it is advised to configure
CentOS to use MariaDB.
Most people will be using MariaDB. When experiencing issues you will get more
assistance with Maria.
CentOS is designed to run with Maria. Hence, Maria will offer better stability.
http://repo.mysql.com/mysql-community-release-el7-5.noarch.rpm
The repository comes conveniently packaged in an rpm package for easy installation. It
can be downloaded with wget:
118
Linux Admin
Note: We will not allow any firewall rules through. It's common to have MySQL configured
to use Unix Domain Sockets. This assures only the web-server of the LAMP stack, locally,
can access the MySQL database, taking out a complete dimension in the attack vector at
the database software.
119
19. Linux Admin ─ Set Up Postfix MTA & IMAP/POP3
Linux Admin
In order to send an email from our CentOS 7 server, we will need the setup to configure
a modern Mail Transfer Agent (MTA). Mail Transfer Agent is the daemon responsible for
sending outbound mail for system users or corporate Internet Domains via SMTP.
It is worth noting, this tutorial only teaches the process of setting up the daemon for local
use. We do not go into detail about advanced configuration for setting up an MTA for
business operations. This is a combination of many skills including but not limited to: DNS,
getting a static routable IP address that is not blacklisted, and configuring advanced
security and service settings. In short, this tutorial is meant to familiarize you with the
basic configuration. Do not use this tutorial for MTA configuration of an Internet facing
host.
With its combined focus on both security and the ease of administration, we have chosen
Postfix as the MTA for this tutorial. The default MTA installed in the older versions of
CentOS is Sendmail. Sendmail is a great MTA. However, of the author's humble opinion,
Postfix hits a sweet spot when addressing the following notes for an MTA. With the most
current version of CentOS, Postfix has superseded Sendmail as the default MTA.
Postfix is a widely used and well documented MTA. It is actively maintained and developed.
It requires minimal configuration in mind (this is just email) and is efficient with system
resources (again, this is just email).
In a simple Postfix configuration, the following must be configured for a specific host: host
name, domain, origin, inet_interfaces, and destination.
Configure the hostname: The hostname is a fully qualified domain name of the Postfix
host. In OpenLDAP chapter, we named the CentOS box: centos on the domain vmnet.local.
Let’s stick with that for this chapter.
120
Linux Admin
Configure the domain: As stated above, the domain we will be using in this tutorial is
vmnet.local
Configure the origin: For a single server and domain set up, we just need to uncomment
the following sections and leave the default Postfix variables.
# SENDING MAIL
#
# The myorigin parameter specifies the domain that locally-posted
# mail appears to come from. The default is to append $myhostname,
# which is fine for small sites. If you run a domain with multiple
# machines, you should (1) change this to $mydomain and (2) set up
# a domain-wide alias database that aliases each user to
# [email protected].
#
# For the sake of consistency between sender and recipient addresses,
# myorigin also specifies the default domain name that is appended
# to recipient addresses that have no @domain part.
#
myorigin = $myhostname
myorigin = $mydomain
Configure the network interfaces: We will leave Postfix listening on our single network
interface and all protocols and IP Addresses associated with that interface. This is done by
simply leaving the default settings enabled for Postfix.
121
Linux Admin
Without SASL Authentication support, Postfix will only allow sending email from local
users. Or it will give a relaying denied error when the users send email away from the
local domain.
smtpd_sasl_auth_enable = yes
smtpd_recipient_restrictions =
permit_mynetworks,permit_sasl_authenticated,reject_unauth_destination
smtpd_sasl_security_options = noanonymous
smtpd_sasl_type = dovecot
smtpd_sasl_path = private/auth
122
Linux Admin
Now let's check to make sure our CentOS host is allowing and responding to the requests
on port 25 (SMTP).
As you can see, SMTP is listening and the daemon is responding to the requests from our
internal LAN.
123
Linux Admin
As noted previously, we will not be configuring MX records for DNS or creating secure rules
allowing our services to handle mail for a domain. Hence, just setting these services up
on an Internet facing host may leave leverage room for security holes w/o SPF Records.
The main configuration file for dovecot is located at: /etc/dovecot.conf. We will first back
up the main configuration file. It is a good practice to always backup configuration files
before making edits. This way id (for example) line breaks get destroyed by a text editor,
and years of changes are lost. Reverting is easy as copying the current backup into
production.
Let's make sure Dovecot is listening locally on the specified ports for: imap, pop3, imap
secured, and pop3 secured.
124
Linux Admin
As seen, dovecot is listening on the specified ports for IPv4 and IPv4.
POP3 110
POP3s 995
IMAP 143
IMAPs 993
Our incoming mail sever is accepting requests for POP3, POP3s, IMAP, and IMAPs to hosts
on the LAN.
125
20. Linux Admin ─ Install Anonymous FTP
Linux Admin
Before delving into installing FTP on CentOS, we need to learn a little about its use and
security. FTP is a really efficient and well-refined protocol for transferring files between
the computer systems. FTP has been used and refined for a few decades now. For
transferring files efficiently over a network with latency or for sheer speed, FTP is a great
choice. More so than either SAMBA or SMB.
However, FTP does possess some security issues. Actually, some serious security issues.
FTP uses a really weak plain-text authentication method. It is for this reason authenticated
sessions should rely on sFTP or FTPS, where TLS is used for end-to-end encryption of the
login and transfer sessions.
With the above caveats, plain old FTP still has its use in the business environment today.
The main use is, anonymous FTP file repositories. This is a situation where no
authentication is warranted to download or upload files. Some examples of anonymous
FTP use are:
Large software companies still use anonymous ftp repositories allowing Internet
users to download shareware and patches.
Hence, as a CentOS Administrator, being able to install and configure FTP is still a designed
skill.
We will be using an FTP daemon called vsFTP, or Very Secure FTP Daemon. vsFTP has
been used in development for a while. It has a reputation for being secure, easy to install
and configure, and is reliable.
126
Linux Admin
In this case, we gave users read/write access to the entire root FTP tree.
Configure /etc/vsftpd/vsftpd.conf"
chown_uploads=YES
chown_username=ftp
127
Linux Admin
Set the custom banner for the user to read before signing in.
listen=YES
listen_ipv6=NO
Now, we need to restart or HUP the vsftp service to apply our changes.
Let's connect to our FTP host and make sure our FTP daemon is responding.
128
21. Linux Admin ─ Remote ManagementLinux Admin
Console Management
GUI Management
The biggest drawbacks to VNC are: VNC does not natively support a multi-user
environment such as remote X-Sessions. Hence, for GUI access to end-users remote X-
Sessions would be the best choice. However, we are mainly concerned with administering
a CentOS server remotely.
We will discuss configuring VNC for multiple administrators versus a few hundred end-
users with remote X-Sessions.
Laying the Foundation for Security with SSH for Remote Console Access
ssh or Secure Shell is now the standard for remotely administering any Linux server.
SSH unlike telnet uses TLS for authenticity and end-to-end encryption of communications.
When properly configured an administrator can be pretty sure both their password and
the server are trusted remotely.
Before configuring SSH, lets talk a little about the basic security and least common access.
When SSH is running on its default port of 22; sooner rather than later, you are going to
get brute force dictionary attacks against common user names and passwords. This just
comes with the territory. No matter how many hosts you add to your deny files, they will
just come in from different IP addresses daily.
129
Linux Admin
With a few common rules, you can simply take some pro-active steps and let the bad guys
waste their time. Following are a few rules of security to follow using SSH for remote
administration on a production server:
Never use a common username or password. Usernames on the system should not
be system default, or associated with the company email address like:
[email protected]
Root access or administration access should not be allowed via SSH. Use a unique
username and su to root or an administration account once authenticated through
SSH.
Disable abandoned or accounts that are unused for extended periods. If a hiring
manager has a voicemail stating they will not be doing interviews for a month; that
can lead to tech-savvy individuals with a lot time on their hands, for example.
Watch your logs daily. As a System Administrator, dedicate at least 30-40 minutes
every morning reviewing system and security logs. If asked, let everyone know you
don't have the time to not be proactive. This practice will help isolate warning signs
before a problem presents itself to end-users and company profits.
130
Linux Admin
Note: We added the new user to the wheel group enabling ability to su into root once SSH
access has been authenticated. We also used a username that cannot be found in common
word lists. This way, our account will not get locked out when SSH is attacked.
LoginGraceTime 60m
PermitRootLogin no
It is good to set the logout grace period to 60 minutes. Some complex administration tasks
can exceed the default of 2 minutes. There is really nothing more frustrating than having
SSH session timeout when configuring or researching changes.
Step 5: We can no longer login remotely via ssh with root credentials. So let's login to our
unprivileged user account and su into the root account.
Step 6: Finally, let's make sure the SSHD service loads on boot and firewalld allows
outside SSH connections.
131
Linux Admin
[root@localhost]#
SSH is now set up and ready for remote administration. Depending on your enterprise
border, the packet filtering border device may need to be configured to allow SSH remote
administration outside the corporate LAN.
To configure screen sharing with Vino under Gnome, we want to go into the CentOS
System Preferences for screen sharing.
Applications->System Tools->Settings->Sharing
132
Linux Admin
Disable New Connections must ask for access - This option will require physical
access to ok every connection. This option will prevent remote administration
unless someone is at the physical desktop.
Enable Require a password - This is separate from the user password. It will control
the access to the virtual desktop and still require the user password to access a
locked desktop (this is good for security).
Forward UP&P Ports: If available leave disabled - Forwarding UP&P ports will send
Universal Plug and Play requests for a layer 3 device to allow VNC connections to
the host automatically. We do not want this.
133
Linux Admin
Finally, as you can see we are able to connect our CentOS Box and administer it with a
VNC client on either Windows or OS X.
It is just as important to obey the same rules for VNC as we set forth for SSH. Just like
SSH, VNC is continually scanned across IP ranges and tested for weak passwords. It is
also worth a note that leaving the default CentOS login enabled with a console timeout
does help with remote VNC security. As an attacker will need the VNC and user password,
134
Linux Admin
make sure your screen sharing password is different and just as hard to guess as the user
password.
After entering the the VNC screen sharing password, we must also enter the user password
to access a locked desktop.
Security Note: By default, VNC is not an encrypted protocol. Hence, the VNC connection
should be tunneled through SSH for encryption.
So from your client that will be initiating the VNC connection, let's set up a remote SSH
tunnel. In this demonstration, we are using OS X. First we need to sudo -s to root.
bash-3.2# sudo -s
password:
Enter the user password and we should now have root shell with a # prompt:
bash-3.2#
135
Linux Admin
-f: ssh should run in the background after the task fully executes
[email protected]: Remote ssh user on the CentOS server hosting VNC services
After successfully entering the remote ssh user's password, our ssh tunnel is created. Now
for the cool part! To connect we point our VNC client at the localhost on the port of our
tunnel, in this case port 2200. Following is the configuration on Mac Laptop's VNC Client:
136
Linux Admin
The cool thing about SSH tunneling is it can be used for almost any protocol. SSH tunnels
are commonly used to bypass egress and ingress port filtering by an ISP, as well as trick
application layer IDS/IPS while evading other session layer monitoring.
Your ISP may filter port 5900 for non-business accounts but allow SSH on port 22
(or one could run SSH on any port if port 22 is filtered).
Application level IPS and IDS look at payload. For example, a common buffer
overflow or SQL Injection. End-to-end SSH encryption will encrypt application
layer data.
SSH Tunneling is great tool in a Linux Administrator's toolbox for getting things done.
However, as an Administrator we want to explore locking down the availability of lesser
privileged users having access to SSH tunneling.
This is an advanced topic stretching outside the realm of an intermediate level primer.
Research on this topic is advised for those who wish to reach the upper echelons of CentOS
Linux Administration.
137
Linux Admin
X-Windows (often called just "X"), provides the mechanism to display application windows
originating from one Linux box to the display portion of X on another Linux box. So through
SSH we can request an X-Windows application be forwarded to the display of another
Linux box across the world!
To run an X Application remotely via an ssh tunnel, we just need to run a single command:
The syntax is: ssh -X [user]@[host], and the host must be running ssh with a valid user.
138
Linux Admin
It is pretty simple to run applications remotely from another Linux server or workstation.
It is also possible to start an entire X-Session and have the entire desktop environment
remotely through a few methods.
XDMCP
This method is most commonly used for headless servers with no physical display and
really exceeds the scope of an intermediate level primer. However, it is good to know of
the options available.
139
22. Linux Admin ─ Traffic Monitoring in CentOS
Linux Admin
There are several third party tools that can add enhanced capabilities for CentOS traffic
monitoring. In this tutorial, we will focus on those that are packaged in the main CentOS
distribution repositories and the Fedora EPEL repository. There will always be situations
where an Administrator (for one reason or another) is left with only tools in the main
CentOS repositories.
Most utilities discussed are designed to be used by an Administrator with the shell of
physical access. When traffic monitoring with an accessible web-gui, using third party
utilities such as ntop-ng or Nagios is the best choice (versus re-creating such facilities
from scratch).
For further research on both configurable web-gui solutions, following are a few links to
get started on research.
For a summarized history of Nagious, here is the official Nagios History page:
https://www.nagios.org/about/history/
ntopng
Another great tool allowing bandwidth and traffic monitoring via a web-gui is called ntopng.
ntopng is similar to the Unix utility ntop, and can collect data for an entire LAN or WAN.
Providing a web-gui for administration, configuration, and charting makes it easy to use
for the entire IT Departments.
Like Nagious, ntopng has both open-source and paid enterprise versions available. For
more information about ntopng, please visit the website:
http://www.ntop.org/
140
Linux Admin
Caution:
Remember, the EPEL Repository is not official for CentOS and may break compatibility and
functionality on production servers with common dependencies. With that in mind, it is
advised to always test on a non-production server running the same services as production
before deploying on a system critical box.
Really, the biggest advantage of using the EHEL Repository over any other third party
repository with CentOS is that we can be sure the binaries are not tainted. It is considered
a best practice to not use the repositories from an untrusted source.
With all that said, the official EPEL Repository is so common with CentOS that it can be
easily installed via YUM.
141
Linux Admin
At this point, our EPEL repository should be configured and ready to use. Let's start by
installing nload for interface bandwidth monitoring.
nload
ntop
ifstst
iftop
vnstat
net hogs
Wireshark
TCP Dump
Traceroute
These are all standard for monitoring traffic in Linux Enterprises. The usage of each range
from simple to advanced, so we will only briefly discuss tools such as Wireshark and TCP
Dump.
Like most other basic installs nload is installed via the YUM package manager.
142
Linux Admin
Dependencies Resolved
===============================================================================
===============================================================================
Package Arch
Version Repository
Size
===============================================================================
===============================================================================
Installing:
nload x86_64
0.7.4-4.el7 epel
70 k
Transaction Summary
===============================================================================
===
============================================================================
Install 1 Package
Total download size: 70 k
Installed size: 176 k
Downloading packages:
nload will monitor the specified interface. In this case, enp0s5 an Ethernet interface, in
real-time from the terminal for network traffic loads and total bandwidth usage.
143
Linux Admin
As seen, nload will chart both incoming and outgoing data from the specified interface,
along with providing a physical representation of the data flow with hash marks "#".
The depicted screenshot is of a simple webpage being loaded with some background
daemon traffic.
Command Action
-a Time period
-t Time update interval in milliseconds, the default is 500
-u Sets display of traffic measurement h
-U Sets total in/out traffic measurement units same options as -u
If no interface is specified, nload will automatically grab the first Ethernet interface. Let's
try measuring the total data in/out in Megabytes and current data-transfer speeds in
Megabits.
144
Linux Admin
Data coming in/out the current interface is measured in megabits per second and each
"Ttl" row, representing total data in/out is displayed in Megabytes.
nload is useful for an administrator to see how much data has passed through an interface
and how much data is currently coming in/out a specified interface.
To see other interfaces without closing nload, simply use the left/right arrow keys. This
will cycle through all available interfaces on the system.
145
23. Linux Admin ─ Log Management Linux Admin
systemd has changed the way system logging is managed for CentOS Linux. Instead of
every daemon on the system placing logs into individual locations than using tools such
as tail or grep as the primary way of sorting and filtering log entries, journald has brought
a single point of administration to analyzing system logs.
The main components behind systemd logging are: journal, jounralctl, and journald.conf
journald is the main logging daemon and is configured by editing journald.conf while
journalctl is used to analyze events logged by journald.
Events logged by journald include: kernel events, user processes, and daemon services.
Currently, the system is correct to the local time zone. If your system is not, let's set the
correct time zone. After changing the settings, CentOS will automatically calculate the
time zone offset from the current time zone, adjusting the system clock right away.
146
Linux Admin
That is the contended output from timedatectl list-timezones. To find a specific local time-
zone, the grep command can be used:
The label used by CentOS is usually Country/Region with an underscore instead of space
(New_York versus "New York").
Switch Action
-k Lists only kernel messages
-u Lists by specific unit (httpd, sshd, etc...)
-b Boots the label offset
-o Logs the output format
-p Filters by log type (either name or number)
-F Fieldname or fieldnamevalue
147
Linux Admin
To check boot logs per reboot instance, we can issue the following command:
148
Linux Admin
Above is the condensed output from our last boot. We could also refer back to a boot log
from hours, days, weeks, months, and even years. However, by default CentOS doesn't
store persistent boot logs. To enable persistently storing boot logs, we need to make a
few configuration changes:
Now, let's give the directory proper permissions journald daemon access:
Finally, let's tell journald it should store persistent boot logs. In vim or your favorite text
editor, open /etc/systemd/jounrald.conf".
[Journal]=
Storage=peristent
149
Linux Admin
The line we are concerned with is, Storage=. First remove the comment #, then change
to Storage=persistent as depicted above. Save and reboot your CentOS system and
take care that there should be multiple entries when running journalctl list-boots.
Note: A constantly changing machine-id like that from a VPS provider can cause journald
to fail at storing persistent boot logs. There are many workarounds for such a scenario. It
is best to peruse the current fixes posted to CentOS Admin forums, than follow the trusted
advice from those who have found plausible VPS workarounds.
To examine a specific boot log, we simply need to get each offset using journald --list-
boots the offset with the -b switch. So to check the second boot log we'd use:
journalctl -b -2
The default for -b with no boot log offset specified will always be the current boot log after
the last reboot.
Hence, if we want to see all warnings the following command can be issued via journalctl:
150
Linux Admin
The above shows all warnings for the past 4 days on the system.
The new way of viewing and perusing logs with systemd does take little practice and
research to become familiar with. However, with different output formats and particular
notice to making all packaged daemon logs universal, it is worth embracing. journald offers
great flexibility and efficiency over traditional log analysis methods.
151
24. Linux Admin ─ Backup & RecoveryLinux Admin
Before exploring methods particular to CentOS for deploying a standard backup plan, let's
first discuss typical considerations for a standard level backup policy. The first thing we
want to get accustomed to is the 3-2-1 backup rule.
System Recovery
A bare metal restore plan is simply a plan laid out by a CentOS administrator to get vital
systems online with all data intact. Assuming 100% systems failure and loss of all past
system hardware, an administrator must have a plan to achieve uptime with intact user-
data costing minimal downtime. The monolithic kernel used in Linux actually makes bare
metal restores using system images much easier than Windows. Where Windows uses a
micro-kernel architecture.
A full data restore and bare metal recovery are usually accomplished through a
combination of methods including working, configured production disk-images of key
operational servers, redundant backups of user data abiding by the 3-2-1 rule. Even some
sensitive files that may be stored in a secure, fireproof safe with limited access to the
trusted company personnel.
A multiphase bare metal restore and data recovery plan using native CentOS tools may
consist of:
tar & gzip to store encrypted backups of files with passwords and notes from
administrators. Commonly, this can be put on a USB drive, encrypted and locked
in a safe that a Senior Manager access. Also, this ensures someone else will know
vital security credentials if the current administrator wins the lottery and disappears
to a sunny island somewhere.
If a system crashes due to a hardware failure or disaster, following will be the different
phases of restoring operations:
152
Linux Admin
rsync is named for its purpose: Remote Sync and is both powerful and flexible in use.
The following sync sent nearly 2.3GB of data across our LAN. The beauty of rsync is it
works incrementally at the block level on a file-by-file basis. This means, if we change just
two characters in a 1MB text file, only one or two blocks will be transferred across the lan
on the next sync!
Furthermore, the incremental function can be disabled in favor of more network bandwidth
used for less CPU utilization. This might prove advisable if constantly copying several 10MB
153
Linux Admin
database files every 10 minutes on a 1Gb dedicated Backup-Lan. The reasoning is: these
will always be changing and will be transmitting incrementally every 10 minutes and may
tax load of the remote CPU. Since the total transfer load will not exceed 5 minutes, we
may just wish to sync the database files in their entirety.
rsync syntax:
rsync [options] [local path] [[remote host:remote path] or [target path]]
Switch Action
-a Archive mode and assumes -r, -p, -t, -g, -l
-d Sync only directory tree, no files
-r Recursive into directory
-p Preserve permissions
-g Preserve group
-v Verbose output
-A Preserve ACLs
-t Preserve timestamps
My personal preference for rsync is when backing up files from a source host to a target
host. For example, all the home directories for data recovery or even offsite and into the
cloud for disaster recovery.
Let's make a manual incremental backup of /etc/ in our root user's directory.
154
Linux Admin
First, we need to create a directory off ~/root for the synced backup:
[root@localhost rdc]# df -h
Filesystem Size Used Avail Use% Mounted on
/dev/mapper/cl-root 43G 15G 28G 35% /
[root@localhost etc_baks]# ls -l ./
total 1436
drwxr-xr-x. 3 root root 101 Feb 1 19:40 abrt
-rw-r--r--. 1 root root 16 Feb 1 19:51 adjtime
-rw-r--r--. 1 root root 1518 Jun 7 2013 aliases
-rw-r--r--. 1 root root 12288 Feb 27 19:06 aliases.db
drwxr-xr-x. 2 root root 51 Feb 1 19:41 alsa
drwxr-xr-x. 2 root root 4096 Feb 27 17:11 alternatives
-rw-------. 1 root root 541 Mar 31 2016 anacrontab
-rw-r--r--. 1 root root 55 Nov 4 12:29 asound.conf
-rw-r--r--. 1 root root 1 Nov 5 14:16 at.deny
drwxr-xr-x. 2 root root 32 Feb 1 19:40 at-spi2
--{ condensed output }--
test_incremental.txt
0 100% 0.00kB/s 0:00:00 (xfer#1, to-check=1145/1282)
155
Linux Admin
We have now backed up a folder from a workstation onto a server running a RAID6 volume
with rotated disaster recovery media stored offsite. Using rsync has given us standard 3-
156
Linux Admin
2-1 backup with only one server having an expensive redundant disk array and rotated
differential backups.
Now let's do another backup of the same folder using rsync after a single new file named
test_file.txt has been added.
As you can see, only the new file was delivered to the server via rsync. The differential
comparison was made on a file-by-file basis.
A few things to note are: This only copies the new file: test_file.txt, since it was the only
file with changes. rsync uses ssh. We did not ever need to use our root account on either
machine.
Simple, powerful and effective, rsync is great for backing up entire folders and directory
structures. However, rsync by itself doesn't automate the process. This is where we need
to dig into our toolbox and find the best, small, and simple tool for the job.
To automate rsync backups with cronjobs, it is essential that SSH users be set up using
SSH keys for authentication. This combined with cronjobs enables rsync to be done
automatically at timed intervals.
dd in simplest terms copies an image of a selected disk area. Then provides the ability to
copy selected blocks of a physical disk. So unless you have backups, once dd writes over
a disk, all blocks are replaced. Loss of previous data exceeds the recovery capabilities for
even highly priced professional-level data-recovery.
The entire process for making a bootable system image with dd is as follows:
157
Linux Admin
In this tutorial, for the sake of time and simplicity, we will be creating an ISO image of the
master-boot record from a CentOS virtual machine. We will then store this image offsite.
In case our MBR becomes corrupted and needs to be restored, the same process can be
applied to an entire bootable disk or partition. However, the time and disk space needed
really goes a little overboard for this tutorial.
Note: When using dd make sure to NOT confuse source and target volumes. You can
destroy data and bootable servers by copying your backup location to a boot drive. Or
possibly worse destroy data forever by copying over data at a very low level with DD.
Following are the common command line switches and parameters for dd:
Switch Action
if= In file or source to be copied
of= Out file or the copy of the in file
Note on block size: The default block size for dd is 512 bytes. This was the standard
block size of lower density hard disk drives. Today's higher density HDDs have increased
to 4096 byte (4kB) block sizes to allow for disks ranging from 1TB and larger. Thus, we
will want to check disk block size before using dd with newer, higher capacity hard disks.
For this tutorial, instead of working on a production server with dd, we will be using a
CentOS installation running in VMWare. We will also configure VMWare to boot a bootable
Linux ISO image instead of working with a bootable USB Stick.
First, we will need to download the CentOS image entitled: CentOS Gnome ISO. This is
almost 3GB and it is advised to always keep a copy for creating bootable USB thumb-
drives and booting into virtual server installations for trouble-shooting and bare metal
images.
Other bootable Linux distros will work just as well. Linux Mint can be used for bootable
ISOs as it has great hardware support and polished GUI disk tools for maintenance.
158
Linux Admin
Let's configure our VMWare Workstation installation to boot from our Linux bootable
image. The steps are for VMWare on OS X. However, they are similar across VMWare
Workstation on Linux, Windows, and even Virtual Box.
Note: Using a virtual desktop solution like Virtual Box or VMWare Workstation is a great
way to set up lab scenarios for learning CentOS Administration tasks. It provides the ability
to install several CentOS installations, practically no hardware configuration letting the
person focus on administration, and even save the server state before making changes.
First let's configure a virtual cd-rom and attach our ISO image to boot instead of the virtual
CentOS server installation:
Now when booted, our virtual machine will boot from the CentOS bootable ISO image and
allow access to files on the Virtual CentOS server that was previously configured.
Let’s check our disks to see where we want to copy the MBR from (condensed output is as
follows).
MiNt ~ # fdisk -l
159
Linux Admin
We have located both our physical disks: sda and sdb. Each has a block size of 512 bytes.
So, we will now run the dd command to copy the first 512 bytes for our MBR on SDA1.
Just like that, we have full image of out master boot record. If we have enough room to
image the boot drive, we could just as easily make a full system boot image:
The conv=sync is used when bytes must be aligned for a physical medium. In this case,
dd may get an error if exact 4K alignments are not read (say... a file that is only 3K but
needs to take minimum of a single 4K block on disk. Or, there is simply an error reading
and the file cannot be read by dd.). Thus, dd with conv=sync,noerror will pad the 3K with
trivial, but useful data to physical medium in 4K block alignments. While not presenting
an error that may end a large operation.
When working with data from disks we always want to include: conv=sync,noerror
parameter.
This is simply because the disks are not streams like TCP data. They are made up of blocks
aligned to a certain size. For example, if we have 512 byte blocks, a file of only 300 bytes
still needs a full 512 bytes of disk-space (possibly 2 blocks for inode information like
permissions and other filesystem information).
tar has been the standard for storing archived files on Unix and Linux for many years.
Hence, using tar along with gzip or bzip is considered as a best practice for archives on
each system.
160
Linux Admin
Following is a list of common command line switches and options used with tar:
Switch Action
-c Creates a new .tar archive
-C Extracts to a different directory
-j Uses bzip2 compression
-z Uses gzip compression
-v Verbose show archiving progress
-t Lists archive contents
-f File name of the archive
-x Extracts tar archive
Note on Compression mechanisms with tar: It is advised to stick with one of two
common compression schemes when using tar: gzip and bzip2. gzip files consume less
CPU resources but are usually larger in size. While bzip2 will take longer to compress, they
utilize more CPU resources; but will result in a smaller end filesize.
When using file compression, we will always want to use standard file extensions letting
everyone including ourselves know (versus guess by trial and error) what compression
scheme is needed to extract archives.
bzip2 .tbz
bzip2 .tar.tbz
bzip2 .tb2
gzip .tar.gz
gzip .tgz
When needing to possibly extract archives on a Windows box or for use on Windows, it is
advised to use the .tar.tbz or .tar.gz as most the three character single extensions will
confuse Windows and Windows only Administrators (however, that is sometimes the
desired outcome).
Let's create a gzipped tar archive from our remote backups copied from the Mac
Workstation:
161
Linux Admin
./RemoteStuff/DDWRT/factory-to-ddwrt.bin
./RemoteStuff/open_ldap_config_notes/
./RemoteStuff/open_ldap_config_notes/ldap_directory_a.png
./RemoteStuff/open_ldap_config_notes/open_ldap_notes.txt
./RemoteStuff/perl_scripts/
./RemoteStuff/perl_scripts/mysnmp.pl
./RemoteStuff/php_scripts/
./RemoteStuff/php_scripts/chunked.php
./RemoteStuff/php_scripts/gettingURL.php
./RemoteStuff/A Guide to the WordPress REST API | Toptal.pdf
./RemoteStuff/Rick Cardon Tech LLC.webloc
./RemoteStuff/VeeamDiagram.png
./RemoteStuff/backbox-4.5.1-i386.iso
./RemoteStuff/dhcp_admin_script_update.py
./RemoteStuff/test_file.txt
[rdc@mint Documents]$ ls -ld RemoteStuff.tgz
-rw-rw-r--. 1 rdc rdc 2317140451 Mar 12 06:10 RemoteStuff.tgz
Note: Instead of adding all the files directly to the archive, we archived the entire folder
RemoteStuff. This is the easiest method. Simply because when extracted, the entire
directory RemoteStuff is extracted with all the files inside the current working directory as
./currentWorkingDirectory/RemoteStuff/
Now let's extract the archive inside the /root/ home directory.
./RemoteStuff/DDWRT/
./RemoteStuff/DDWRT/.DS_Store
./RemoteStuff/DDWRT/ddwrt-linksys-wrt1200acv2-webflash.bin
./RemoteStuff/DDWRT/ddwrt_mod_notes.docx
./RemoteStuff/DDWRT/factory-to-ddwrt.bin
./RemoteStuff/open_ldap_config_notes/
./RemoteStuff/open_ldap_config_notes/ldap_directory_a.png
./RemoteStuff/open_ldap_config_notes/open_ldap_notes.txt
./RemoteStuff/perl_scripts/
./RemoteStuff/perl_scripts/mysnmp.pl
./RemoteStuff/php_scripts/
162
Linux Admin
./RemoteStuff/php_scripts/chunked.php
./RemoteStuff/php_scripts/gettingURL.php
./RemoteStuff/A Guide to the WordPress REST API | Toptal.pdf
./RemoteStuff/Rick Cardon Tech LLC.webloc
./RemoteStuff/VeeamDiagram.png
./RemoteStuff/backbox-4.5.1-i386.iso
./RemoteStuff/dhcp_admin_script_update.py
./RemoteStuff/test_file.txt
[root@mint ~]# ping www.google.com
As seen above, all the files were simply extracted into the containing directory within our
current working directory.
[root@centos ~]# ls -l
total 2262872
-rw-------. 1 root root 1752 Feb 1 19:52 anaconda-ks.cfg
drwxr-xr-x. 137 root root 8192 Mar 9 04:42 etc_baks
-rw-r--r--. 1 root root 1800 Feb 2 03:14 initial-setup-ks.cfg
drwxr-xr-x. 6 rdc rdc 4096 Mar 10 22:20 RemoteStuff
-rw-r--r--. 1 root root 2317140451 Mar 12 07:12 RemoteStuff.tgz
-rw-r--r--. 1 root root 9446 Feb 25 05:09 ssl.conf
[root@centos ~]#
When using gzip, the default action is to remove the original files, replacing each with a
compressed version adding the .gz extension.
Switch Action
-c Keeps files after placing into the archive
-l Get statistics for the compressed archive
-r Recursively compresses files in the directories
gzip more or less works on a file-by-file basis and not on an archive basis like some
Windows O/S zip utilities. The main reason for this is that tar already provides advanced
archiving features. gzip is designed to provide only a compression mechanism.
163
Linux Admin
Hence, when thinking of gzip, think of a single file. When thinking of multiple files, think
of tar archives. Let's now explore this with our previous tar archive.
Note: Seasoned Linux professionals will often refer to a tarred archive as a tarball.
For demonstration purposes, let's gzip the newly created tarball, and tell gzip to keep the
old file. By default, without the -c option, gzip will replace the entire tar archive with a .gz
file.
To demonstrate how gzip differs from Windows Zip Utilities, let's run gzip on a folder of
text files.
Now let's use the -r option to recursively compress all the text files in the directory.
See? Not what some may have anticipated. All the original text files were removed and
each was compressed individually. Because of this behavior, it is best to think of gzip alone
when needing to work in single files.
164
Linux Admin
Working with tarballs, let's extract our rsynced tarball into a new directory.
As seen above, we extracted and decompressed our tarball into the /tmp directory.
Openssl like GnuPG can do what we want and ships with CentOS. But again, is not
specifically designed to do what we want and encryption has been questioned in the
security community.
Our choice is a utility called 7zip. 7zip is a compression utility like gzip but with many
more features. Like Gnu Gzip, 7zip and its standards are in the open-source community.
We just need to install 7zip from our EHEL Repository (the next chapter will cover installing
the Extended Enterprise Repositories in detail).
165
Linux Admin
Simple as that, 7zip is installed and ready be used with 256-bit AES encryption for our tar-
ball archives.
Now let's use 7z to encrypt our gzipped archive with a password. The syntax for doing so
is pretty simple:
Where, a: add to archive, and -p: encrypt and prompt for passphrase
166
Linux Admin
Items to compress: 1
Everything is Ok
[root@centos Documents]# ls
RemoteStuff RemoteStuff.tar RemoteStuff.tar.gz RemoteStuff.tgz.7z slapD
text_files
[root@centos Documents]#
Now, we have our .7z archive that encrypts the gzipped tarball with 256-bit AES.
Note: 7zip uses AES 256-bit encryption with an SHA-256 hash of the password and
counter, repeated up to 512K times for key derivation. This should be secure enough if a
complex key is used.
The process of encrypting and recompressing the archive further can take some time with
larger archives.
7zip is an advanced offering with more features than gzip or bzip2. However, it is not as
standard with CentOS or amongst the Linux world. Thus, the other utilities should be used
often as possible.
167
25. Linux Admin ─ System Updates Linux Admin
Manually
Automatically
Update manually for major security issues and configure automatic updates
It is plausible a simple security update can cause recursive issues with common application
that requires upgrading and reconfiguration by an Administrator. So, be weary of
scheduling automatic updates in production before testing in development servers and
desktops first.
In order to use yum for updates, your CentOS server will need to be connected to the
Internet. Most configurations will install a base system, then use yum to query the main
CentOS repository for additional functionality in packages and apply system updates.
We have already made use of yum to install a few packages. When using yum you will
always need to do so as the root user. Or a user with root access. So let's search for and
install an easy to use text-editor called nano.
168
Linux Admin
Name and summary matches only, use "search all" for everything.
[root@centos rdc]#
Dependencies
Resolved=======================================================================
===============================================================================
=========
Package Arch Version
Repository Size
Installing:
nano x86_64
2.3.1-10.el7
base 440 k
Transaction Summary
Install 1 Package
Total download size: 440 k
Installed size: 1.6 M
Is this ok [y/d/N]: y
Downloading packages:
169
Linux Admin
nano-2.3.1-10.el7.x86_64.rpm
| 440 kB 00:00:00
Complete!
[root@centos rdc]#
We have installed the nano text editor. This method, IMO, is a lot easier than searching
for utilities on websites and manually running the installers. Also, repositories use digital
signatures to validate packages assuring they are coming from a trusted source with yum.
It is up to the administrator to validate authenticity when trusting new repositories. This
is why it is considered a best practice to be weary of third party repositories.
Dependencies Resolved
170
Linux Admin
* updates: repos.forethought.net
Updated Packages
NetworkManager.x86_64
1:1.4.0-17.el7_3 updates
NetworkManager-adsl.x86_64
1:1.4.0-17.el7_3 updates
NetworkManager-glib.x86_64
1:1.4.0-17.el7_3 updates
NetworkManager-libnm.x86_64
1:1.4.0-17.el7_3 updates
NetworkManager-team.x86_64
1:1.4.0-17.el7_3 updates
NetworkManager-tui.x86_64
1:1.4.0-17.el7_3 updates
NetworkManager-wifi.x86_64
1:1.4.0-17.el7_3 updates
audit.x86_64
2.6.5-3.el7_3.1 updates
audit-libs.x86_64
2.6.5-3.el7_3.1 updates
audit-libs-python.x86_64
As depicted, we have a few dozen updates pending to install. Actually, there are about
100 total updates since we have not yet configured automatic updates. Thus, let's install
all pending updates.
171
Linux Admin
Transaction Summary
===============================================================================
Install 2 Packages
Upgrade 68 Packages
Total size: 196 M
Total download size: 83 M
Is this ok [y/d/N]:
After hitting the "y" key, updating of CentOS 7 will commence. The general process that
yum goes through when updating is:
172
Linux Admin
[root@centos rdc]#
Installed:
yum-cron.noarch 0:3.4.3-150.el7.centos
Complete!
[root@centos rdc]#
By default, yum-cron will only download updates and not install them. Whether to install
updates automatically is on the Administrator. The biggest caveat is: some updates will
require a system reboot. Also, some updates may require a configuration change before
services are again operational.
Updating dependencies can possibly create a recursive problem in the following situation:
173
Linux Admin
Yum may go ahead and automatically upgrade Apache and PHP without notice unless
configured not to.
If all 5 scenarios play out, it can result in anything from a big headache in the morning to
a possible security compromise exposing the user data. While the aforementioned example
is a perfect storm of sorts, we never want such a scenario to play out.
It is up to the Administrator for accessing possible scenarios of potential revenue loss from
time needed to restore services due to possible downtime from update reboots and
reconfigurations. This practice may not be conservative enough for, say, a multi-million
dollar per day ecommerce site with millions of customers.
Again, whether to use automatic updates and install updates on demand can be a double
edged sword and needs to be considered by an administrator for each unique situation.
174
26. Linux Admin ─ Shell Scripting Linux Admin
Everyone has a favorite shell and each has its strengths and difficulties. But for the most
part, Bash is going to be the default shell across all Linux distributions and most commonly
available. With experience, everyone will want to explore and use a shell that is best for
them. However at the same time, everyone will also want to master Bash shell.
Other Linux shells include: Tcsh, Csh, Ksh, Zsh, and Fish.
Developing skills to use any Linux shell at an expert level is extremely important to a
CentOS administrator. As we mentioned previously, unlike Windows, Linux at its heart is
a command line operating system. A shell is simply a user interface that allows an
administrator (or user) to issue commands to the operating system. If a Linux system
administrator were an airlines pilot, using the shell would be similar to taking the plane
off auto-pilot and grabbing the manual controls for more maneuverable flight.
A Linux shell, like Bash, is known in Computer Science terms as a Command Line
Interpreter. Microsoft Windows also has two command line interpreters called DOS (not
to be confused with the original DOS operating system) and PowerShell.
Most modern shells like Bash provide constructs allowing more complex shell scripts to
automate both common and complex tasks.
Constructs include:
There is no set rule here. There are only typical differences between shells versus scripting
languages.
175
Linux Admin
Shell
Shell allows the use of Linux commands such as sed, grep, tee, cat and all other
command-line based utilities on the Linux operating system. In fact, pretty much any
command line Linux utility can be scripted in your shell.
A great example of using a shell would be a quick script to check a list of hosts for DNS
resolution.
#!/bin/bash
for name in $(cat $1); do
host $name.$2 | grep "has address"
done
exit
dns
www
test
dev
mail
rdp
remote
176
Linux Admin
Leveraging simple Linux commands in our shell, we were able to make a simple 5-line
script to audit DNS names from a word list. This would have taken some considerable time
in Perl, Python, or Ruby even when using a nicely implemented DNS Library.
Scripting Language
A scripting language will give more control outside the shell. The above Bash script used
a wrapper around the Linux host command. What if we wanted to do more and make our
own application like host to interact outside the shell? This is where we would use a
scripting language.
Also, with a highly maintained scripting language we know our actions will work across
different systems for the most part. Python 3.5, for example, will work on any other system
running Python 3.5 with the same libraries installed. Not so, if we want to run our BASH
script on both Linux and HP-UX.
Sometimes the lines between a scripting language and a powerful shell can be blurred. It
is possible to automate CentOS Linux administration tasks with Python, Perl or Ruby. Doing
so is really quite commonplace. Also, affluent shell-script developers have made a simple,
but otherwise functional, web-server daemon in Bash.
Also, it is ok to use both a scripting language and shell script for different parts of a project.
An example could be a Perl script to scrape a website. Then, use a shell script to parse
and format with sed, awk, and egrep. Finally, use a PHP script for inserting formatted data
into MySQL database using a web GUI.
With some theory behind shells, let's get started with the basic building blocks to automate
tasks from a Bash shell in CentOS.
Above, we have passed cat'sstoud to wc for processing with the pipe character. wc then
processed the output from cat, printing the line count of output.txt to the terminal. Think
of the pipe character as a "pipe" passing output from one command, to be processed by
the next command.
177
Linux Admin
Following are the key concepts to remember when dealing with command redirection:
2 standard error
We introduced this in chapter one without really talking much about redirection or
assigning redirection. When opening a terminal in Linux, your shell is seen as the default
target for:
/dev/pts/0 is our pseudo terminal. CentOS Linux looks at this and thinks of our open
terminal application like a real terminal with the keyboard and display plugged in through
a serial interface. However, like a hypervisor abstracts hardware to an operating system
/dev/pts abstracts our terminal to applications.
From the above lsof command, we can see under the FD column that all three file-
descriptors are set to our virtual terminal (0,1,2). We can now send commands, see
command output, as well as any errors associated with the command.
178
Linux Admin
STDOUT
[root@centosLocal centos]# echo "I am coming from Standard output or STDOUT." >
output.txt && cat output.txt
I am coming from Standard output or STDOUT.
[root@centosLocal centos]#
When searching the entire file system, two errors were encountered. Each were sent to a
separate file for later perusal, while the results returned were placed into a separate text
file.
Sending stderr to a text file can be useful when doing things that output a lot of data to
the terminal like compiling applications. This will allow for perusal of errors that could get
lost from terminal scrollback history.
One note when passing STDOUT to a text file are the differences between >> and >. The
double ">>" will append to a file, while the singular form will clobber the file and write
new contents (so all previous data will be lost).
STDIN
In the above command, the text file stdin.txt was redirected to the cat command which
echoed its content to STDOUT.
The pipe character will take the output from the first command, passing it as an input into
the next command, allowing the secondary command to perform operations on the output.
179
Linux Admin
Above, wc performs calculations on output from cat which was passed from the pipe. The
pipe command is particularly useful when filtering the output from grep or egrep:
In the above command, we passed every 4 digit number to wc from a text file containing
all numbers from 65535 passed through an egrep filter.
Output can be redirected using the & character. If we want to direct the output both
STDOUT and STDERR, into the same file, it can be accomplished as follows:
Redirecting using the & character works like this: first, the output is redirected into out.txt.
Second, STDERR or the file descriptor 2 is reassigned to the same location as STDOUT, in
this case out.txt.
Redirection is extremely useful and comes in handy while solving problems that surgace
when manipulating large text-files, compiling source code, redirecting the output in shell
scripts, and issuing complex Linux commands.
While powerful, redirection can get complicated for newer CentOS Administrators. Practice,
research, and occasional question to a Linux forum (such as Stack Overflow Linux) will
help solve advanced solutions.
Variables
Loops
Conditionals
Loop control
180
Linux Admin
Variables
Variables in Bash are used like any other scripting language. The syntax may vary from
languages such as Perl, Python and Ruby.
The first thing we will want to note is BASH variables comes in two basic varieties: Global
or Environment Variables and Script or Local Variables.
Global or Environment Variables are set across all shells and scripts.
Environment Variables can be displayed with either the env or printenv commands:
bash-3.2# printenv
SHELL=/bin/bash
TERM=xterm-256color
USER=root
SUDO_USER="rick cardon"
SUDO_UID=501
USERNAME=root
MAIL=/var/mail/root
PATH=/usr/local/pear/bin:/Library/Frameworks/Python.framework/Versions/3.5/bin:
/opt/local/bin:/opt/local/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/
PWD=/home/rdc/Desktop
LANG=en_US.UTF-8
Common syntax is to use uppercase for Environment variables and lowercase script for
local variables. These are the variables used within your script, assuming the script will
not be setting or changing the shell Environment Variables.
#!/bin/bash
num=0
while [ $num -lt 100 ]
do
num=$[$num+1]
echo $num
if [ $((num % 10)) = 0 ];
then
sleep 5s
fi
done
181
Linux Admin
echo $PATH
The small script above simply increments to 20, pauses for five seconds every 5th
iteration, then echoes an environmental variable: the current user's path:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/usr/local/pear/bin:/Library/Frameworks/Python.framework/Versions/3.5/bin:/opt/
local/bin:/opt/local/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
If you'd like a variable to be seen outside your shell, the following export command must
be used.
#!/bin/bash
export MY_NEW_GLOBAL="I am Global"
Loops
Like all other programming languages BASH makes use of common looping structures:
for, while, and until.
182
Linux Admin
for loop
The for loop is used to execute other shell instructions repeatedly. The for loop is classified
as an iteration statement in BASH.
#!/bin/bash
myFile="myLines.txt"
for i in `cat $myFile`
do
echo $i
done
The above for loop iterates through the contents of *myLines.txt" and echoes each line to
the terminal.
Note: When a command is enclosed in backticks (shift+tilde) the command's output will
be assigned to a variable.
while loop
This loop will execute until a condition is satisfied. We saw this used previously with the
shell routine that repeatedly echoed and incremented.
#!/bin/bash
myFile="myLines.txt"
Again, this small script displays the contents of our text file.
Note: The first line of your script should always contain the shebang line. This is simply
the path to your BASH shell interpreter. Usually, located in /bin/bash on CentOS.
until loop
The until loop is similar in syntax to the while loop. The difference is, the until loop will
execute until a command executes successfully.
With that in mind, we'd just need to negate our while script to execute with until
#!/bin/bash
myFile="myLines.txt"
until ! read -a FILELINE;
183
Linux Admin
do
echo $FILELINE
done < $myFile
Conditionals
While loops are the main control structures for operational flow, logical operations need to
be performed as well.
Logical operations can be controlled with the following constructs in BASH: if, then, else,
and elif.
If
This is pretty simple and will make a conditional operation based on how a logic test
evaluates.
#!/bin/bash
result=1
if [ $result -eq 1 ];
then
echo "Result was true!"
else
echo "Result was false!"
fi
Note: Bash uses a few different equality operators. In this case, we used "-eq", performing
equality on an integer. For a string, we'd use "==".
#!/bin/bash
ourColor="red"
if [ $ourColor == "black" ];
then
echo "Too dark"
elif [ $ourColor == "white" ];
then
echo "Too plain!"
elif [ $ourColor != "gray" ];
then
echo "Too colorful"
184
Linux Admin
else
echo "Let's make it" $ourColor
fi
Our somewhat biased script will not be satisfied until we decide on gray.
Loop Control
Sometimes (a lot times actually) we will either want to skip loop iteration operation or
break out of a loop prior to completion. These operations are performed with the following
verbs: continue and break.
continue
#!/bin/bash
myFile="myLines.txt"
while read -a FILENAME;
do
if [ `echo $FILENAME | grep 004` ];
then
continue
fi
echo $FILENAME
done < $myFile
The snippet above will skip the 4th line of the text file, then continue script execution.
line001
line002
line003
line005
line006
line007
line008
line009
break
Break will stop the loop in its entirety rather than skip a single iteration when a condition
is met.
185
Linux Admin
#!/bin/bash
myFile="myLines.txt"
while read -a FILENAME;
do
if [ `echo $FILENAME | grep 004` ];
then
break
fi
echo $FILENAME
done < $myFile
line001
line002
line003
#!/bin/bash
myFile="myLines.txt"
while read -a FILENAME;
do
if [ `echo $FILENAME | grep 004` ];
then
echo "line was $FILENAME" >> LineFile.txt
break
fi
echo $FILENAME
done < $myFile
Instead of echoing to the terminal, our conditional branch now echoes to a file named
LineFile.txt.
Reading from files has been presented in two ways, cat and read. read is usually always
considered a best practice. While cat just passes the streams of text from a file. read
implies to the script reading an actual file and takes accountability for a file being read.
The following script reads the text file again, puts each line into an array, then prints the
array to the terminal.
186
Linux Admin
#!/bin/bash
myFile="myLines.txt"
line=()
0 -> line001
1 -> line002
2 -> line003
3 -> line004
4 -> line005
5 -> line006
6 -> line007
7 -> line008
8 -> line009
9 -> line010
+ Addition
- Subtraction
* Multiplication
/ division
% Modulus
++ Increment
-- Decrement
When performing math operations, it is necessary to use the format of $((math formula))
187
Linux Admin
Note: When using $() BASH, it will execute a command. echo $(ls) will print the output
of ls to the terminal. Adding an additional nest () will let BASH know the math operations
to be performed.
#!/bin/bash
1
2
3
4
5
6
7
8
9
10
11
#!/bin/bash
echo $((2+1))
echo $((2-1))
echo $((2*1))
echo $((2/1))
echo $((2%1))
3
1
2
2
188
Linux Admin
Performing math operations on integers is pretty simple in BASH. The developer just needs
to remember integer operations are always performed in $(()), telling BASH it is math.
#!/bin/bash
echo 1.1+2.3 | bc
3.4
bc can get pretty complex but at the same time is a very powerful command-line
calculator.
Just remember, using bc is best with floating point operations and the shell can handle
integer math. You will need to pass your operands to bc. Finally, the scale parameter
specifies the precision of the solution.
#!/bin/bash
echo 'scale=3; 1.19*2.3' | bc -q
2.737
189
Linux Admin
A quick search of Google or signing up at an expert Linux forum to ask a question will lead
to a quick resolution. There is a very likely chance someone has come across the exact
issue and it has already been solved.
BASH scripting is a great method of quickly creating powerful scripts for everything from
automating administration tasks to creating useful tools. Becoming an expert level BASH
script developer takes time and practice. Hence, use BASH scripts whenever possible, it is
a great tool to have in your CentOS Administration toolbox.
190
27. Linux Admin ─ Package Management
Linux Admin
Package management in CentOS can be performed in two ways: from the terminal and
from the Graphical User Interface.
More often than not a majority of a CentOS administrator's time will be using the terminal.
Updating and installing packages for CentOS is no different. With this in mind, we will first
explore package management in the terminal, then touch on using the graphical package
management tool provided by CentOS.
YUM has brought software installation and management in Linux a long way. YUM
"automagically” checks for out-of-date dependencies, in addition to out-of-date packages.
This has really taken a load off the CentOS administrator compared to the old days of
compiling every application from source-code.
yum check-update
Checks for packages that can update candidates. For this tutorial, we will assume this a
production system that will be facing the Internet with no production applications that
needs to be tested by DevOps before upgrading the packages. Let us now install the
updated candidates onto the system.
NetworkManager.x86_64 1:1.4.0-19.el7_3
updates
NetworkManager-adsl.x86_64 1:1.4.0-19.el7_3
updates
NetworkManager-glib.x86_64 1:1.4.0-19.el7_3
updates
NetworkManager-libnm.x86_64 1:1.4.0-19.el7_3
updates
NetworkManager-team.x86_64 1:1.4.0-19.el7_3
updates
191
Linux Admin
NetworkManager-tui.x86_64 1:1.4.0-19.el7_3
updates
NetworkManager-wifi.x86_64 1:1.4.0-19.el7_3
updates
audit.x86_64 2.6.5-3.el7_3.1
updates
vim-common.x86_64 2:7.4.160-1.el7_3.1
updates
vim-enhanced.x86_64 2:7.4.160-1.el7_3.1
updates
vim-filesystem.x86_64 2:7.4.160-1.el7_3.1
updates
vim-minimal.x86_64 2:7.4.160-1.el7_3.1
updates
wpa_supplicant.x86_64 1:2.0-21.el7_3
updates
xfsprogs.x86_64 4.5.0-9.el7_3
updates
[root@localhost rdc]#
yum update
This will install all updated candidates making your CentOS installation current. With a
new installation, this can take a little time depending on your installation and your internet
connection speed.
Transaction Summary
===============================================================================
===
Install 2 Packages
Upgrade 156 Packages
192
Linux Admin
Is this ok [y/d/N]:
Before installing some software utilities, let's look at few YUM commands. For daily work,
90% of a CentOS Admin's usage of YUM will be with about 7 commands. We will go over
each in the hope of becoming familiar with operating YUM at a proficient level for daily
use. However, like most Linux utilities, YUM offers a wealth of advanced features that are
always great to explore via the man page. Use man yum will always be the first step to
performing unfamiliar operations with any Linux utility.
Command Action
193
Linux Admin
* extras: mirror.scalabledns.com
* updates: mirror.clarkson.edu
================================================================= N/S matched:
web, browser ==================================================================
icedtea-web.x86_64 : Additional Java components for OpenJDK - Java browser
plug-in and Web Start implementation
elinks.x86_64 : A text-mode Web browser
firefox.i686 : Mozilla Firefox Web browser
firefox.x86_64 : Mozilla Firefox Web browser
lynx.x86_64 : A text-based Web browser
Full name and summary matches only, use "search all" for everything.
[root@localhost rdc]#
We see, CentOS does offer the Lynx web browser in the repository. Let's see some more
information about the package.
194
Linux Admin
[root@localhost rdc]#
Dependencies Resolved
===============================================================================
===============================================================================
Package Arch Version
Repository Size
===============================================================================
===============================================================================
Installing:
lynx x86_64 2.8.8-
0.3.dev15.el7 base
1.4 M
Transaction Summary
===============================================================================
===============================================================================
Install 1 Package
195
Linux Admin
lynx-2.8.8-0.3.dev15.el7.x86_64.rpm
| 1.4 MB 00:00:10
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
Installing : lynx-2.8.8-0.3.dev15.el7.x86_64
1/1
Verifying : lynx-2.8.8-0.3.dev15.el7.x86_64
1/1
Installed:
lynx.x86_64 0:2.8.8-0.3.dev15.el7
Complete!
[root@localhost rdc]#
Great! Let's use Lynx to and see what the web looks like without "likes" and pretty pictures.
196
Linux Admin
Great, now we have a web browser for our production server that can be used without
much worry into remote exploits launched over the web. This a good thing for production
servers.
We are almost completed, however first we need to set this server for developers to test
applications. Thus, let's make sure they have all the tools needed for their job. We could
install everything individually, but CentOS and YUM have made this a lot faster. Let's install
the Development Group Package.
Available Groups:
Compatibility Libraries
Console Internet Tools
Development Tools
Graphical Administration Tools
197
Linux Admin
This is a smaller list of Package Groups provided by CentOS. Let's see what is included
with the "Development Group".
The first screen of output is as seen above. This entire list is rather comprehensive.
However, this group will usually be needed to be installed in its entirety as time goes by.
Let's install the entire Development Group.
This will be a larger install. When completed, your server will have most development
libraries and compilers for Perl, Python, C, and C++.
198
Linux Admin
The Software Package Management Tool is divided into groups allowing the administrator
to select packages for installation. While this tool is great for ease-of-use and simplicity
for end-users, YUM is a lot more powerful and will probably be used more by
administrators.
Following is a screenshot of the Software Package Management Tool, not really designed
for System Administrators.
199
28. Linux Admin ─ Volume ManagementLinux Admin
Note: Using Logical Volumes actually increases disk I/O when configured correctly. This
works in a similar fashion to RAID 0 striping data across separate disks.
When learning about volume management with LVM, it is easier if we know what each
component in LVM is. Please study the following table to get a firm grasp of each
component. If you need to, use Google to study. Understanding each piece of a logical
volume is important to manage them.
A physical volume will be seen as /dev/sda, /dev/sdb; a physical disk that is detected
by Linux.
A physical partition will be a section of the disk partitioned by a disk utility such as fdisk.
Keep in mind, physical partition is not recommended in most common LVM setups.
Example: disk /dev/sda is partitioned to include two physical partitions: /dev/sda1 and
/dev/sda1
If we have two physical disks of 1TB each, we can create a volume group of almost 2TB
amongst the two.
From the volume group, we can create three logical volumes each of any-size not
exceeding the total volume group size.
Now, assuming we have added another disk or two to our system, we need to enumerate
disks detected by Linux. I'd always advise enumerating disks every time before performing
operations considered as destructive. lsblk is a great tool for getting disk information.
Let's see what disks CentOS detects.
200
Linux Admin
As you can see, we have three disks on this system: sda, sdb, and sdc.
Disk sda contains our working CentOS installation, so we do not want to toy around with
sda. Both sdb and sdc were added to the system for this tutorial. Let's make these disks
usable to CentOS.
We now have one disk labeled. Simply run the parted command in the same manner on
sdc.
Yes/No? NO
201
Linux Admin
As you can see from lsblk output, we now have two partitions, each on sdb and sdc.
202
Linux Admin
Each is now using the XFS file system. Let's mount them, check the mount, and copy a
file to each.
/mnt/sdc:
myFile
We have two usable disks at this point. However, they will only be usable when we mount
them manually. To mount each on boot, we must edit the fstab file. Also, permissions
must be set for groups needing access to the new disks.
203
Linux Admin
We will go through the process of creating a simple volume pool and logical volumes in
CentOS. The first step is installing the System Storage Manager.
What we want to do is make a Volume Group using two disks (sdb and sdc). Then make
three 3GB Logical Volumes available to the system.
204
Linux Admin
By default, ssm will create a single logical volume extending the entire 10GB of the pool.
We don't want this, so let's remove this.
We now have three separate logical volumes spanned across two physical disk partitions.
Logical volumes are a powerful feature now built into CentOS Linux. We have touched the
surface on managing these. Mastering pools and logical volumes come with practice and
extended learning from Tutorials Point. For now, you have learned the basics of LVM
management in CentOS and possess the ability to create basic striped Logical Volumes on
a single host.
205