Skip to main content

CentOS

CentOS text files navigation with less

No doubt you will frequently use programs and tools that use the program less or less-like navigation to view and read file content or display output. At first, the control can seem a bit unintuitive. Here, in this process, we will show you the basics of how to navigate through a file using fewer controls.

To Start With: What Do You Need?

In order to implement this process, you will require a working installation of the CentOS 7 operating system with root privileges.

The Process

  1. To begin, log in as root and type the following command to open a program that uses less for navigation:
    man man
  2. To navigate, press the up and down key to scroll up and down one line at a time, the spacebar to scroll down a page, and the b key to scroll up a page. You can search within the text using the forward slash key, /, followed by the search term, then press Return to search. Press n to jump to the next search result. Press the q key to exit.        

How Does It Work?

Here, in this short process, we have shown you the very basics of less navigation, which is essential for reading man pages and is used by a lot of other programs throughout this book to display text. We only showed you the basic commands and there is much more to learn. Please read the less manual to find out more on man less command.

 

Setting up NRPE on remote client hosts

The Nagios Remote Plugin Executor (NRPE) is a system daemon that uses a special client-server protocol and should be installed on all client hosts that you want to monitor via your Nagios server remotely. It allows the central Nagios server to trigger any Nagios checks on these client hosts securely and with low overhead. Here, we will show you how to set up and configure any CentOS 7 client to use NRPE; if you’ve got more than one computer in your network that you want to monitor, you need to apply this process for every instance.

To Start With: What Do You Need?

To complete this process, you will require a computer other than your Nagios server with an installation of the CentOS 7 operating system and root privileges, which you want to monitor, and which needs a console-based text editor of your choice installed on it, along with a connection to the Internet in order to facilitate the download of additional packages. This computer needs to have access to our Nagios server over the network. In our example, the Nagios server has the IP address 192.168.1.7, and our client system will have the IP address 192.168.1.8.

The Process

  1. Log in as root on your CentOS 7 client system and install all Nagios plugins as well as NRPE on it:
    yum install epel-release;yum install nrpe nagios-plugins-all nagiosplugins-nrpe
  2. Afterwards, open the main NRPE config file (after making a backup first):
    cp /etc/nagios/nrpe.cfg /etc/nagios/nrpe.cfg.BAK && vi /etc/nagios/nrpe.cfg
  3. Find the line that starts with allowed_hosts, and add the IP address of your Nagios server separated by a comma so that we can communicate with it (in our example ,192.168.1.7, so change it accordingly); it should read as follows:
    allowed_hosts=127.0.0.1,192.168.1.7
  4. Save and close the file, then enable NRPE at boot and start it:
    systemctl enable nrpe && systemctl start nrpe
  5. Then enable the NRPE port in firewalld. To do this, create a new firewalld service file for NRPE:
    sed 's/80/5666/g' /usr/lib/firewalld/services/http.xml | sed 's/WWW
    (HTTP)/Nagios NRPE/g' | sed 's/.*\/description>//g' >
    /etc/firewalld/services/nrpe.xml
    firewall-cmd --reload
    firewall-cmd --permanent --add-service=nrpe; firewall-cmd --reload
  6. Finally, test the NRPE connection. To do this, log in as root on your Nagios server (for example, at 192.168.1.7) and execute the following command to check NRPE on our client (192.168.1.8):
    /usr/lib64/nagios/plugins/check_nrpe -H 192.168.1.8 -c check_load
  7. If the output prints out an OK -load average message with some numbers, you have successfully configured NRPE on the client!

How Does It Work?

Here in this process, we have shown you how to install NRPE on your CentOS 7 clients that you want to monitor with your Nagios servers. If you want to monitor other Linux systems running other distributions such as Debian or BSD, you should be able to find appropriate packages using their own package managers or compile NRPE from source. Besides the NRPE package, we also installed all the Nagios plugins on this machine since NRPE is only the daemon for running monitoring commands on client computers, but it does not include them. After installation, NRPE is listening only on localhost (127.0.0.1) connections by default, so we then had to change this to also listen to connections from our Nagios server, which runs with the IP 192.168.1.7, using the allowed_hosts directive in the main NRPE configuration file. The NRPE port 5666 is needed for incoming connections from the Nagios server, so we also had to open it in the firewall. Since no firewalld rule is available for it by default, we created our own new service file and added it to the current firewalld configuration. Afterwards, we could test our NRPE installation from our Nagios server by running a check_nrpe command using the client’s IP address and a random check command (check_load returns the system’s load).

 

Installing Apache and serving web pages in CentOS

In this process, we will learn how to install and configure the Apache web server to enable the serving of static web pages. Apache is one of the world’s most popular open source web servers. It runs as the backend for over half of all the Internet’s web sites and can be used to serve both static and dynamic web pages. Commonly referred to as httpd, it supports an extensive range of features. It is the purpose of this process to show you how easily it can be installed using the YUM package manager so that you can maintain your server with the latest security updates. Apache 2.4 is available on CentOS 7.

To Start With: What Do You Need?

To complete this process, you will require a working installation of the CentOS 7 operating system with root privileges, a console-based text editor of your choice, and a connection to the Internet in order to download additional packages. It is expected that your server will be using a static IP address and a hostname.

The Process

Apache is not installed by default and for this reason, we will begin by installing the necessary packages using the YUM package manager.

  1. To begin, log in as root and type the following command:
    yum install httpd
  2. Create a home page by typing:
    vi /var/www/html/index.html
  3. Now add the required HTML. You can use the following code as a starting point but it is expected that you will want to modify it to suit your own needs:


    Welcome to my new web server

    Welcome to my new web server

    Lorem ipsum dolor sit amet, adipiscing elit.


  4. You can now remove the Apache 2 test page with the following command:
    rm -f /etc/httpd/conf.d/welcome.conf
  5. Having completed these steps, we will now consider the need to configure the httpd service for basic usage. To do this, open the httpd configuration file in your favorite text editor by typing (after you have made a backup of the file):
    cp /etc/httpd/conf/httpd.conf /etc/httpd/conf/httpd.conf.BAK vi /etc/httpd/conf/httpd.conf
  6. Now scroll down to find the line ServerAdmin root@localhost. The traditional approach to setting this value is based on the use of the webmaster identity, so simply modify the e-mail address to reflect something more relevant to your own needs. For example, if your server’s domain name was www.centos7.home then your entry will look similar to this:
    ServerAdmin webmaster@centos7.home
  7. Now scroll down a few more lines to find the ServerName directive as follows: #ServerName www.example.com:80. Uncomment this line (which means remove the leading # sign at its beginning) and replace the value www.example.com with something more appropriate to your own needs. For example, if your server’s domain name was www.centos7.home then your entry will look as follows:
    ServerName www.centos7.home:80
  8.  Next, we will expand the DirectoryIndex directive a bit more. Find the line DirectoryIndex index.html, which is part of the block, then change it to:
    DirectoryIndex index.html index.htm
  9. Save and close the file, and then type the following command to test the config file:
    apachectl configtest
  10. Next, let’s configure our web server’s firewall by allowing incoming http connections (this defaults to port 80) to the server:
    firewall-cmd --permanent --add-service http && firewall-cmd --reload
  11. Now proceed to set the httpd service to start at boot and start the service:
    systemctl enable httpd && systemctl start httpd
  12. You can now test httpd from any computer in the same network as your web server (both systems should be able to see and ping each other), pointing your browser at the following URL by replacing XXX.XXX.XXX.XXX with the IP address of your server in order to see our own custom Apache test page we created:
    http://XXX.XXX.XXX.XXX.
  13. Alternatively, if you don’t have a web browser, you can check if Apache is up and running using curl by fetching our test page on any computer in your network:
    curl http://XXX.XXX.XXX

How Does It Work?

Apache is a software package that enables you to publish and serve web pages, and is more commonly known as httpd, Apache2 or simply Apache. It was the purpose of this process to show you how easily CentOS enables you to get started with your very first website.

So what did we learn from this experience?

We began the process by installing Apache via the YUM package manager and the package named httpd. Having done this, we learned that on CentOS 7 the default location to serve static HTML is /var/www/html so our first task was to create a suitable home page, which we put in /var/www/html/index.html. Here we used a basic HTML template to get you started and it is expected that you would like to customize the look and feel of this page yourself. Following this, we then removed the default Apache 2 welcome page found in /etc/httpd/conf.d/welcome.conf. Following this, the next stage was to open the httpd.conf configuration file in our favorite text editor after making a backup of it so we could revert our changes if any problems occurred. First we defined the server’s e-mail address and the server name, which often appear in the error messages on the server-generated web pages; for this reason it should reflect your domain name. Next, we adjusted the DirectoryIndex directive, which defines which files will be sent first to the browser if a directory is requested. Often people request not a specific web page but a directory instead. For example, if you browse to www.example.com, you request a directory, while www.example.com/welcome.html is a specific web page. By default Apache sends the index.html in the requested directory but we expanded this since a lot of websites use the .htm extension instead. Finally, we saved and closed the httpd configuration file in the usual way before proceeding to check if the Apache configuration file contained any errors by using the apachectl configtest command. This should print out a Syntax OK message so we could enable the httpd service to start at boot time. We had to open the standard HTTP port 80 in our firewalld to allow incoming HTTP requests to the server, and finally we then started the httpd service. Remember, you can also always reload Apache’s configuration file if it has been changed without fully restarting the service, by using: systemctl reload httpd. Having completed these steps, it was simply a matter of opening your browser from another computer in the same network and electing a method of viewing our new Apache start page. You can use your server’s IP address (for example, http://192.168.1.100), while those with hostname support can type the hostname (for example, http://www.centos7.home) instead. Apache’s access and error log files can be found in /var/log/httpd. To get a live view of who is currently accessing your web server, open /var/log/httpd/access_log; to see all the errors, type /var/log/httpd/error_log.

Apache is a big subject and we cannot cover every nuance, but over the coming processes, we will continue to expose additional functionalities that will enable you to build a web server of choice.

 

Troubleshooting CentOS users and file transfers

Analyzing log files is the most important technique for troubleshooting all kinds of problems or improving services on Linux. In this process, you will learn how to configure and enable vsftpd’s extensive logging features in order to help system administrators when problems arise, or simply to monitor usage with this service.

To Start With: What Do You Need?

To complete this process, you will require a working installation of the CentOS 7 operating system with root privileges and a console-based text editor of your choice. It is expected that your server will be using a static IP address and that vsftpd is already installed with a chroot jail and is currently running.

The Process

  1. To do this, log in as root and type the following command to open the main configuration file in your favorite text editor:
    vi /etc/vsftpd/vsftpd.conf
  2. Now, add the following lines to the end of the configuration file to enable verbose logging features:
    dual_log_enable=YES log_ftp_protocol=YES
  3. Finally, restart the vsftpd daemon to apply the changes:
    systemctl restart vsftpd

How Does It Work?

In this process, we have shown how to enable two separate logging mechanism: first, the xferlog log file that will log detailed information about user uploads and downloads, then the vsftpd log file that contains every FTP protocol transaction between the client and the server outputting the most detailed logging information possible for vsftpd.

So what did we learn from this experience?

In this process, we opened the main vsftpd configuration file and added two directives to the end of the file. First, dual_log_enable will make sure both the xferlog and vsftpd log files will be used for logging. Afterwards, we increased the verbosity of the vsftpd log file by enabling log_ftp_protocol.

After restarting the service, the two log files, /var/log/xferlog and /var/log/vsftdp.log, will be created and filled with useful FTP activity information. Now, before we open the files, let’s create some FTP user activity. Log in with any FTP user on the server using the ftp command-line tool and issue the following FTP command at the ftp> prompt to upload a random file from the client to the server:
put ~/.bash_profile bash_profile_test

Now, back on the server, inspect the /var/log/xferlog file to see detailed information about the uploaded file and open /var/log/vsftpd.log for all other user activities (such as login time or other FTP commands that users issued).

Please note that both the log files only keep track of user and FTP activity and are not meant to debug problems with the vsftpd service such as configuration file errors. Use the systemctl status vsftpd -l or journalctl -xn, to debug general problems with the service.

 

Extending the capacity of the CentOS filesystem

CentOS 7 uses the Logical Volume Manager (LVM) to organize the structure and available capacity of your partitions. It is a very dynamic and flexible system that can be extended or rearranged over time, and which is essential in today’s most demanding and ever-changing environments. At the moment, buzzwords such as big data or cloud computing can be heard everywhere. Since massive amounts of data get produced all the time, storage requirements and disk space have to grow at the same steady pace. In this process, you will learn how to work with the LVM system and how to extend your physical drives, and also how to shrink and extend the capacity of your filesystems.

To Start With: What Do You Need?

To complete this process, you will require a working installation of the CentOS 7 operating system with root privileges. We will use virtual block devices instead of real disk devices to show you from scratch how to set up a LVM first, and afterward how to work with it. Please read the Creating a virtual block device process and create three 1 gigabyte virtual block devices with the GPT partition table, which will be labeled as /dev/loop0, /dev/loop1, and /dev/loop2 in this example.

Again, feel free to use real disk devices if you feel ready for it.

The Process

First, we will start by creating an LVM test environment similar to the standard CentOS 7 LVM structure, which is set up during the installation of every server system:

  1. First, let’s log in as root and show information about our virtual block devices:
    lsblk -io NAME,SIZE
  2. Next, create new partitions spanning the whole disk on each of the three virtual block devices (without a filesystem label):
    parted -a optimal /dev/loop0 mkpart primary 2048KiB 100%
    parted -a optimal /dev/loop1 mkpart primary 2048KiB 100%
    parted -a optimal /dev/loop2 mkpart primary 2048KiB 100%
  3. Now, let’s create LVM physical volumes on each of the loop devices (type yes to remove the gpt label):
    pvcreate /dev/loop0p1 pvcreate /dev/loop1p1 pvcreate /dev/loop2p1
  4. Next, show information about our physical volumes:
    pvdisplay
  5. Next, we will create a new LVM volume group on our first physical volume:
    vgcreate myVG1 /dev/loop0p1
  6. Now, show information about the created group:
    vgdisplay myVG1
  7. Afterward, let’s create some logical volumes on our first volume group, which will be treated as virtual partitions in our Linux system:
    lvcreate -L 10m -n swap myVG1
    lvcreate -L 100m -n home myVG1
    lvcreate -L 400m -n root myVG1
  8. Next, show information about the logical volumes:
    lvdisplay myVG1
  9. Now, display how much free space our underlying volume group has left, which becomes important if you want to expand some logical volumes (see the section Free PE / Size in the output):
    vgdisplay myVG1
  10. Afterward, let’s create the filesystems on those new logical volumes:
    mkswap /dev/myVG1/swap
    mkfs.xfs /dev/myVG1/home
    mkfs.xfs /dev/myVG1/root
  11. Now, after we have created our test LVM system (which is very similar to the real CentOS LVM standard layout, but with smaller sizes), let’s start working with it.
  12. First, let’s shrink the root partition, which is currently 400 megabytes (M) in size, by 200 megabytes, and afterward, let’s increase the home partition by 500 megabytes (confirm the possible data loss):
    lvresize -L -200m /dev/myVG1/root
    lvresize -L +500m /dev/myVG1/homE
  13. Use vgdisplay myVG1 again to see how the volume group’s free space changes by running the previous commands (see Free PE / Size).
  14. Now, let’s expand the XFS filesystem on the grown logical volume:
    mkdir /media/home-test;mount /dev/myVG1/home /media/home-test xfs_growfs /dev/myVG1/home
    Note
    It is very important not to use resize2fs for growing XFS filesystems, because it’s incompatible and can corrupt them.
  15. Now, let’s say that after some time your data has grown again, and you need the home partition to be 1.5 gigabytes (G), but you only have 184.00 MiB left on the underlying volume group. First, we need to add our two prepared physical volumes from the beginning of this process to our volume group:
    vgextend myVG1 /dev/loop1p1 /dev/loop2p1 vgdisplay myVG1
  16. Afterward, we have enough free space in our volume group (see Free PE / Size) to expand our home logical volume (the volume must stay mounted):
    lvresize -L +1500m /dev/myVG1/home xfs_growfs /dev/myVG1/home

How Does It Work?

Here, in this process, we have shown you how to work with the LVM for XFS partitions. It has been developed with the purpose of managing disk space on several hard disks dynamically. You can easily merge many physical hard disks together to make them appear as a single virtual hard disk to the system. This makes it a flexible and very scalable system in comparison to working with plain old static partitions. Traditional partitions are bound to, and cannot grow over, the total disk capacity they reside on, and their static partition layout cannot be changed easily. Also, we have introduced some important LVM technical terms that provide different abstraction layers to a hard disk, and which will be explained in this section so as to understand the concepts behind it: physical volume (pv), volume group (vg), and logical volume (lv).

So, what did we learn from this experience?

We started this process by creating three virtual block devices of 1 gigabyte (G) each and then one partition spanning the whole device on each of them. Afterwards, we defined these single-partition devices as physical volumes (pv) using the pvcreate command. A pv is an LVM term that defines a storage unit in the LVM world. It must be defined on a partition, full drive, or loop device. A pv is just an abstraction of all the space available in the surrounding partition so that we can work with it on an LVM basis. Next, we created a volume group (vg) with the vgcreate command, where we also had to define a volume group name of our choice and put the first pv in it as a basic storage volume. As you can see, a vg is a container for at least one pv (we add more pv’s later). Adding or removing pv’s to or from a vg is the heart of the whole scalability concept of the LVM system. The pv’s don’t have to be all the same size, and it is possible to grow your vg over time by adding dozens of new physical drives all defined as pv. You can have more than one vg on your system, and you can identify them by the unique names you are giving to them. So, in summary, to extend the space of your vg, you have to create pv’s out of physical drives, which you can then add to.

Finally, we created logical volumes (lv) on our vg, which can be seen and used like real physical partitions within a vg. Here, we created three lv’s using the lvcreate command, by which we need to define the name of the vg (remember, there can be more than one vg on your system) that we want to put our target lv on, along with the size of the volume, as well as a name for it as the last parameter. You can add multiple lvs into a vg and you don’t need to use the whole allocated space from the underlying free space of the vg. You can be very flexible with it. The best part is that your decision about your volumes’ size and layout doesn’t have to be fixed for all time; you can change them anytime later. It is a very dynamic system that can be extended and shrunk, deleted and created, without having to unmount the volume beforehand. But you have to remember that all lvs are bound to a vg, and it is not possible to create them without it or outside its spacial boundaries. If you need to extend an lv’s space over the borders of the underlying vg, you have to extend the vg, as show in this process.

Note
As you may have seen, for every LVM term, there is a “display” and “create” command, so it’s easy to remember: pvdisplay, vgdisplay, lvdisplay, pvcreate, vgcreate, lvcreate.

After you have successfully created your lv’s, you can work with them as you would with every other block device partition on your system. The only difference is that they reside in special device folders: /dev// or /dev/mapper//. For example, the home volume created in this example has the name /dev/myVG1/home. Finally, in order to use them as normal mount points, we created some test filesystems on them.

In the second part of this , we showed you how to extend our vg and how to shrink and expand our lv’s test system.

We started by using the vgdisplay myVG1 command to show the currently available space on the vg. In the command output, we saw that our current volume group has a total of 996M (VG Size), the allocated size from our lv’s (swap, home, root) is 512M (Alloc PE / Size), and the free size is 484M (Free PE /Size). Next, we used the lvresize command to shrink and expand the logical volume’s root and home. The -L parameter sets the new size of the volume, and with the + or -sign, the value is added to or subtracted from the actual size of the logical volume. Without it, the value is taken as an absolute one. Remember that we could only increase the home partition because the current volume layout does not occupy the complete vg’s total space. After resizing, if we use the vgdisplay command again, we see that we now occupy more space in the vg; its free size has been decreased to 184M. Since we expanded the home volume from 100M to 500M in total, we need to remember to expand its XFS filesystem too, since expanding a volume does not automatically expand its filesystem. Therefore, 400M of the current volume are unallocated without any filesystem information. We used the command, xfs_growfs, which will, without defining a limit parameter, use the complete unallocated area for the XFS filesystem. If you want to resize any other filesystem type, such as ext4, you would use the resize2fs command instead.

Finally, we wanted to grow the home volume by 1.5G, but we only have 184M left on our vg to expand. This is where LVM really shines because we can just add some more physical volumes to it (in the real world, you would just install new hard disks in your server and use them as pvs). We showed you how to extend the capacity of your vg by adding two 1G-sized pvs to it using the vgextend command. Afterward, we used vgdisplay to see that our vg has now grown to 3G in total size, so finally, we could extend our home lv as it would now fit into it. As a last step, we expanded the XFS file system once again to fill up the whole 2G home volume size.

Please remember, all the time, that if you use vg’s with several physical hard disks, your data will be distributed among these. An LVM is not a RAID system and has no redundancy, so if one hard disk fails, your complete vg will fail too and your data will be lost! In order to deal with this problem, a proposed solution could be to use a physical RAID system for your hard disks and create an LVM on top of that.

 

Synchronizing files in CentOS and doing more with rsync

rsync is a program that can be used to synchronize files and directories across a variety of local and remote locations. It can interact with multiple operating systems, work over SSH, provide incremental backups, execute commands on a remote machine, and replace the need for the cp and scp commands. The rsync program is an invaluable asset for any system administrator who intends to run a server or manage a network of computers, as it not only simplifies the process of making backups in general, but it can be used to action a complete backup solution. For this reason, it is the purpose of this process to offer a suitable starting point for a small utility that will quickly become your trusted friend.

To Start With: What Do You Need?

In a bid to complete this process, you will require a working installation of the CentOS 7 operating system with root privileges, a console-based text editor of your choice, and a connection to the Internet in order to facilitate the download of additional packages.

The Process

During the course of this process, it will be assumed that you know the location of the source files and directories that you wish to synchronize and that a suitable destination is available:

  1. To begin this process, log in as root and install rsync by typing:
    yum install rsync
  2. Now, create a target directory for our synchronization (change the folder name appropriately):
    mkdir ~/sync-target
  3. To begin the synchronization process, simply repeat the following command by modifying the value used for /path/to/source/files/ with something more applicable to your needs:
    rsync -avz --delete /path/to/source/files/ ~/sync-target
  4. Having used the Return key to confirm the preceding instruction, your system will now respond with a live report of what is being copied. When this process has finished, you can then compare both directories to see that the contents are exactly the same. To do this, use the diff command (if both are the same, no output will be written):
    diff -r /path/to/source/files/ ~/sync-target

How it works…

In this process, we considered the use of rsync through the command line. Of course, this is only one of the many ways that this tool can be used, but by using this approach we were able to explore a handful of the features provided by this very valuable utility.

So, what did we learn from this experience?

Rsync is not intended to be complicated. It is a fast and efficient file synchronization tool that is designed to be versatile by giving you complete access to an array of features on the command line. It can be used to maintain an exact copy (or mirror) of the source directory on the same machine or on a completely different system, and it does this by copying all the files once and then only updating the files that have changed the next time you run it. This can save tremendous bandwidth and should be your primary tool when copying data over the network. The use of the phrase, --delete, is important, as it instructs rsync to delete files on the target that do not exist in the source, while the chosen flags imply that rsync should use -an archive mode in order to recursively copy files and directories while keeping all permissions and time-based information; –v)verbosity mode so you can see what is happening; and –z to compress the data during the file transfer in order to save bandwidth and reduce the amount of time required to complete the entire process.

As you can see, rsync is very flexible and has many options that go beyond the purpose of this process, but if you want to exclude certain files you could always extend the original instruction by invoking the --exclude flag. By doing this, you tell rsync to back up an entire directory but ensure that it does not include a predefined pattern of files and folders. For example, if you are copying files from your server to a USB device and you do not want to include large files (such as a .iso image) or ZIP files, then your command may look similar to this:
rsync --delete -avz --exclude="*.zip" --exclude="*.iso" /path/to/source/ /path/to/external/disk/

On a final note, there is the subject of verbosity. Verbosity is very useful, but a tendency to use bytes as its primary unit of measurement can be a source of confusion. So, in order to change this, you can invoke rsync with the –h (or human readable) option, as shown next:
rsync -avzh --exclude="home/path/to/file.txt" /home/ /path/to/external/disk/

 

 

 

Updating the CentOS installation and enhancing the minimal install

This process will rightly explain you the way to enhance the minimal install along with additional tools. This will provide you with various administrative and developmental options that might stand extremely vital for your server to work in its lifetime. 

However, this minimal install is said to the most efficient and the most friendly way for installing a server, but implementing this minimal server does definitely require some extra features so, in order to make it much compelling. We know the importance of administrative and developmental tools for the smooth running of your server and this process how to install these extra packages

To Start With: What Do You Need?

  1. A minimal installation of CentOS 6 operating system added with its root privileges. 
  2. A high-speed Internet connection for smooth downloading of additional packages.

The Process:

  1. The primary task is to update the system.
    So login as root and type,
    yum -y update
  2. Now, CentOS will look for relevant updates and if updates are available, they will get installed. Further, after completion of the update, you should reboot your computer
    You should type,
    reboot
  3. After the server reboots and finally returns to the login screen, we will complete by enhancing the current installation along with a series of package groups. So, login as root and type,
    yum –y groupinstall "Base" "Development Libraries" "DevelopmentTools"
  4. After the installation is complete, you are required to reboot the server by typing, 
    reboot

How Does It Work?

This process works to increase the minimal installation of the CentOS operating system. You also got introduced to Yum Package Manager. 

We initiated by updating the system so that we make sure that the system is up to date. Further, during this time, it is best to reboot the server and this is solely because to take advantage of a new kernel or rather any other revised security updates. We also came to know about how to add a new series of package groups that would stand highly essential for use in the future. 

 

 

Installing and configuring Nagios Core in CentOS

In this process, we will learn how to install Nagios Core version 4, an open-source network monitoring system that checks whether hosts and services are working and notifies users when problems occur or services become unavailable. Nagios provides solutions to monitor your complete IT infrastructure and is designed with an architecture that is highly extendable and customizable and goes far beyond simple bash scripts to monitor your services. (Refer to the Monitoring important server infrastructure process.)

To Start With: What Do You Need?

To complete this process, you will require a working installation of the CentOS 7 operating system with root privileges, a console-based text editor of your choice, and a connection to the Internet in order to facilitate the download of additional packages. Nagios Core 4 is not available in the official sources but from the EPEL repository; make sure to have installed it before (refer to the Using a third-party repository process in, Managing Packages with YUM). For the Nagios web frontend, you need a running Apache2 web server as well as PHP (refer to the processes from, Providing Web Services) installed on your Nagios server. In our example, the Nagios server has the IP address 192.168.1.7, and it will be able to monitor all IT infrastructure in the complete 192.168.1.0/24 subnet.

The Process

Nagios Core 4 is not available by default, so let’s begin by installing all the required packages:

  1. To do so, log in as root and type the following command:
    yum install nagios nagios-plugins-all nagios-plugins-nrpe nrpe
  2. First, create a new user account called nagiosadmin, which is needed for authentication to the web frontend (enter a secure password when prompted), then reload the Apache configuration:
    htpasswd /etc/nagios/passwd nagiosadmin && systemctl reload httpd
  3. Now, add an e-mail address for the nagiosadmin web user to the Nagios configuration, open the following file, and search and replace the string, nagios@localhost, with an appropriate e-mail address you want to use here (it can be a domain-wide or external e-mail address):
    vi /etc/nagios/objects/contacts.cfg
  4. Now, we need to adjust the main configuration file to activate /etc/nagios/servers as our server’s definition configuration directory, where we will put all our server config files later, but first, make a backup:
    cp /etc/nagios/nagios.cfg /etc/nagios/nagios.cfg.BAK
    sed -i -r 's/^#cfg_dir=(.+)servers$/cfg_dir=\1servers/g'
    /etc/nagios/nagios.cfg
  5. We will have to create the server’s config directory that we just defined in the last step:
    mkdir /etc/nagios/servers
    chown nagios: /etc/nagios/servers;chmod 750 /etc/nagios/servers
  6. Afterwards, to check the correctness of the nagios.cfg syntax, run the following:
    nagios -v /etc/nagios/nagios.cfg
  7. Finally, enable the Nagios daemon on boot and start the service:
    systemctl enable nagios && systemctl start nagios

How Does It Work?

Here in this process, we have shown you how to install the Nagios Core v4 server (Core is the open-source version of the Nagios project) on CentOS 7. Besides the main Nagios package, we also required the NRPE package and all the Nagios plugins on our Nagios server. After installing, we created a user account, which is able to log in to the web frontend, and we set the e-mail address for this user in the main Nagios configuration file. Next, we activated the /etc/nagios/servers directory using sed, where all our server definition files will be put in a later process, here. Then, we created the directory and changed permissions to the Nagios user. To test the Nagios server installation, open a web browser on a computer in the same subnet 192.168.1.0/24 as your Nagios server, open the following URL (in our example, the Nagios server has the IP 192.168.1.7, so change accordingly), and then log in with your newly created nagiosadmin user account to http://192.168.1.7/nagios.

 

Using Fetchmail in CentOS

So far in this segment, we have shown you two different forms of MTA. First, we introduced you to the Postfix MTA, which is a transport agent used for routing e-mails from a mail client to or between mail servers and delivering them to the local mailboxes on the mail server using the SMTP protocol. Then we showed you another type of MTA which sometimes called an access agent and which the Dovecot program can be used for. This delivers mails from the local Postfix mailboxes to any remote mail client programs using the POP3 or IMAP protocol. Now we will introduce you to a third type of MTA, which can be termed a retrieval agent, and explain what we will use the program Fetchmail for. Nowadays, almost everybody has more than one e-mail account, from one or more different mail providers, which can be hard to maintain if you need to login to all those different webmail sites or use different accounts in your mail program. This is where Fetchmail comes into play. It is a program, running on the same server as your domain-wide Postfix mail server and which can retrieve all your different e-mails from all your different mail providers and pass them into the local user mailboxes of your Postfix MTA. Once they are stored in their appropriate place, users can access all these mails in the usual way provided by the access agent Dovecot over POP3 or IMAP. Here in this process we will show you how to install and integrate Fetchmail into your server running the Postfix MTA.

To Start With: What Do You Need?

To complete this process, you will require a working installation of the CentOS 7 operating system with root privileges, a console-based text editor of your choice, and a connection to the Internet in order to download additional packages. It is assumed that you are working through this chapter division process by process in the order that they appear and for this reason, it is expected that Postfix has been configured as a domain-wide MTA and Dovecot has been installed to provide a POP3/IMAP mail access service. In order to test Fetchmail in this process, we also need to have registered some external e-mail addresses: you need the name of the external e-mail server address and the port of your e-mail provider, as well as your user login credentials at hand. Often you can find this information from your mail provider’s Frequently Asked Questions (FAQ) section on their webpage. Also, for some e-mail addresses, you need to first enable POP3 or IMAP in your e-mail settings before you can use Fetchmail.

The Process

Fetchmail is not installed by default and for this reason we must begin by installing the necessary packages. Perform the following steps:

  1. To begin, log in your mail server running your Postfix server and type:
    yum install fetchmail
  2. Once installed, we will log into a system’s user account for which we want to enable Fetchmail to download external mail from an external mail provider into his local mailbox, in our example it will be the system user john: su -john. Now let’s configure Fetchmail with an external e-mail address. If your e-mail provider is called mailhost.com and it runs a POP3 server at pop.mailhost.com and IMAP on imap.mailhost.com with the username , here (please substitute your own values) is an example command line to test connecting and fetching mails from this provider:
    fetchmail pop.mailhost.com -p pop3 -u -k -v
  3. If you want to use IMAP with the same provider instead:
    fetchmail imap.mailhost.com -p IMAP -u -v
  4. If the Fetchmail command was successful, all new messages will be downloaded from the server into your local mailbox in your user account.

How Does It Work?

Here in this process, we showed you how to install and test Fetchmail, which provides automated mail retrieval capabilities for any user account having a local mailbox on our Postfix server. As a result, for a client connecting to the mail server using POP3 or IMAP, the mails fetched this way look like normal incoming e-mails. Fetchmail is often used to combine and bundle all your different mail accounts into one single account, but you can also use it if your mail provider does not have a good virus or spam filter. Here you download the mails from your host’s e-mail server, then process the mails using tools such as SpamAssassin or ClamAV before sending mails to your clients.

So what did we learn from this experience?

We began this process by installing the YUM package for Fetchmail. As we wanted to set up Fetchmail for a system user’s mailbox called john, next we logged in as this user. Afterwards, we tested the Fetchmail program by running a simple command line to fetch mail from a single mail provider. As said before, for a successful login to your external mail provider, you need to know the exact login information (server address, port, username, and password, as well as the type of protocol) of the server before you can use Fetchmail.

Remember that, while some e-mail providers let the user decide if he wants to connect securely using SSL or not, some hosters such as gmail.com only allow secure connections. This means that the example command shown here in this process is likely to fail on every major e-mail provider if they don’t support POP3/IMAP access without SSL connections. Proceed to the next section in order to learn how to use Fetchmail with SSL POP3/IMAP encryption.

You should always prefer SSL encryption if your mail provider offers both. Also, some providers such as gmail.com only let the user use their services via webmail and disable POP3/IMAP service features by default; you need to enable them in your account’s settings on your provider’s website (see later).

We specified with the -p parameter which mail protocol to use with the fetchmail command. With the -u parameter, we specified the user identification to be used when logging in to the mailserver, which is completely dependent on our e-mail provider. For POP3, we applied the -k flag to ensure that the e-mails only get fetched from the server but never deleted (which is the default when using the POP3 protocol). Finally, we used -v to make the output more verbose and give us more information for our simple test. If your e-mail provider supports SSL, you also need to add a -ssl flag to the Fetchmail command as well as the root certificate of the mail server (see the next section for more information). If you run the previous command, Fetchmail will immediately start asking the mail server for any mail in the inbox on the server and download anything to your user’s local mailbox.

There's more…

In this section, we will show you how to configure Fetchmail to download all your e-mails from some real-life mail providers using POP3S, IMAPS, and the POP3 and IMAP protocols to your local mailbox on the Postfix server using a configuration file. Finally, we will show you how to automate the Fetchmail process.

Configuring Fetchmail with gmail.com and outlook.com e-mail accounts

Here we will configure the different external mail accounts which Fetchmail will download from: the popular gmail.com and outlook.com e-mail providers and a hypothetical one at my-email-server.com.

As we learned in the main process that Fetchmail processes configuration options on the command line by default, this should not be your preferred way of using Fetchmail to download your mail from different mail accounts automatically. Normally Fetchmail should be running as a service in daemon mode in the background at boot time or with a cron job and polls a list of mail servers defined in a special configuration file at specific time intervals. With this, you can conveniently configure multiple mail servers and a long list of other options.

Note
At the time of writing this book, for gmail.com to work with Fetchmail you need to login to the gmail.com website with your user account and first enable IMAP by going to your accounts settings in Forwarding and POP/IMAP. Also, enable Allow less secure apps under Sign-in & security in My account. For outlook.com, login to your mail account on the webpage, then click on options, again click on options, then click on Connect devices and apps with POP, and then click on enable POP.

Both outlook.com and gmail.com use secure POP3S and IMAPS protocols, so you need to download and install the root certificates they are signing their SSL certificates with on your Fetchmail server first in order to be able to use their services. Here we can install the Mozilla CA certification bundle, which has been compiled by the Mozilla foundation and includes the most commonly used root server certificates used by all major websites and services, such as those used by our mail providers. For gmail.com we need the Equifax Secure Certificate Authority root certificate and for outlook.com we need the root server certificate from Globalsign. Fetchmail needs these root certificates to verify the validity of any other SSL certificate downloaded from the e-mail server. Login as root on your Postfix server and install the following package:
yum install ca-certificates

Afterwards, login as a Linux system user, for example, john, who we will create a new Fetchmail configuration file for, and who already has a local Postfix mailbox directory on our server located in his home directory under ~/Maildir. Now before configuring any account in the Fetchmail configuration file, you should always first test if the connection and authentication to the specific account are working with the Fetchmail command line, as shown in the previous process. For testing our different mail providers’ accounts, we need three different command line calls. For testing if your provider is using SSL encryption, you need the –ssl flag; a typical output for a mail provider who is not allowing non-SSL connections could be:
Fetchmail: SSL connection failed.
Fetchmail: socket error while fetching from @
Fetchmail: Query status=2 (SOCKET)

If your google and outlook username is johndoe at both mail providers for testing google with the IMAPS protocol try (enter your e-mail user’s password when prompted):
fetchmail imap.gmail.com -p IMAP --ssl -u johndoe@gmail.com -k -v

If the login was successful, the output should be similar to (truncated):
Fetchmail: IMAP A0002 OK johndoe@gmail.com authenticated (Success)
9 messages (2 seen) for johndoe at imap.gmail.com.
Fetchmail: IMAP> A0005 FETCH 1:9 RFC822.SIZE

For testing outlook.com with POP3S, use:
fetchmail pop-mail.outlook.com -p POP3 --ssl -u johndoe@outlook.com -k -v

On success, the output should be similar to (it has been truncated):
Fetchmail: POP3> USER johndoe@outlook.com
Fetchmail: POP3 +OK password required
Fetchmail: POP3 +OK mailbox has 1 messages

For our third hypothetical e-mail account at my-email-server.com, we will use POP3 or IMAP without SSL so test it using our account:
fetchmail pop3.my-email-server.com -p POP3 -u johndoe -k -v
fetchmail imap.my-email-server.com -p IMAP -u johndoe -v

You should also check if all the fetched mails from your external providers have been downloaded correctly. View your system user’s local mailbox using the mailx command (mailx -f ~/Maildir). After we successfully verify that Fetchmail is able to connect to the servers and fetch some mails, we now can proceed to create a local Fetchmail configuration file in our system user’s home directory in order to automate this process and configure multiple mail addresses. Start by opening a new empty file using vi ~/.fetchmailrc. Remember that all the commands which can be put on the command line can also be used with slightly different names in the configuration file (and much more). Now put in the following content (replace john with your actual Linux system user, johndoe with your e-mail user account name, and secretpass with your actual mail password for this account):
set postmaster "john"
set logfile fetchmail.log
poll imap.gmail.com with proto IMAP
user 'johndoe@gmail.com' there with password 'secretpass' is john here
ssl
fetchall
poll pop-mail.outlook.com with proto POP3
user 'johndoe@outlook.com' there with password 'secretpass' is john here
ssl
fetchall
poll pop3.my-email-server.com with proto POP3
user 'johndoe@my-email-server.com' there with password 'secretpass' is john
here
fetchall

Save and close this file. In this file, we used the following important commands:

  • postmaster: Defines the local Linux user which will receive all the warning or error mails if Fetchmail runs into problems.
  • logfile: Defines a filename for a log file, which can be very helpful for us to supervise and debug Fetchmail output when it’s running continuously over a long period of time in the background.
  • poll section: Specifies downloading mails from a specific mail provider. For every mail account, you will define one such poll section. As you can see here, the syntax is very similar to the one used on the command line when we tested the single connections. With proto we define the mail protocol, user is the login user for the mail account, password is the login password of your account, and with the is here parameter you specify which local system user account this mail account is tied to. For SSL connections you need the ssl flag, and we specified the fetchall parameter to make sure we also download all the e-mail messages flagged as read by the e-mail provider as otherwise Fetchmail would not download e-mails that have already been read.

Next change the permissions of the .fetchmailrc file because it contains passwords and should therefore not be read by anyone other than our own user:
chmod 600 ~/.fetchmailrc

Finally, we execute Fetchmail with the settings given in our configuration file. For testing, we will use a very verbose parameter here: fetchmail -vvvv. All the new mails from all your different e-mail providers should now be fetched, so afterwards you should go through the output and see if every server was ready and could be polled just as the single tests we did on the command line tests earlier. All the new mails should have been downloaded to the local mailbox, so in order to read your local mails you can use the mailx command as usual, like: mail -f ~/Maildir.

Automating Fetchmail

As just said, we can now manually start the polling process every time we want by just typing in fetchmail on the command line. This will poll and fetch all new mails from the mail servers specified in our new configuration file and then after processing each entry once it will exit the program. Now what’s still missing is a mechanism to continuously query our mail servers at a specific interval updating our mailbox whenever new mails can be fetched. Here you can use two approaches. Either run the fetchmail command as a cron job or as an alternative you can start Fetchmail in daemon mode (use the parameter set daemon in your .fetchmailrc config file to activate it.) and put it in the background.

This way Fetchmail will run constantly and wake up at a given time point and start the polling until everything finishes processing and then go back to sleep until the next interval has been reached.

As both methods are basically the same, here we will show you how to run Fetchmail as a cron job, which is much easier to set up because we don’t have to create some custom systemd service files (currently in CentOS 7 there is no fetchmail systemd service available out-of-the box). For every system user (for example, john) who has a fetchmail configuration file, to start the e-mail server polling process every 10 minutes type in the following command once to register the cron job:
crontab -l | { cat; echo "*/10 * * * * /usr/bin/fetchmail &> /dev/null "; } | crontab

Note

Do not set the Fetchmail polling cycle shorter than every 5 minutes; otherwise, some mail providers may block or ban you, as it just overloads their systems.

 

Customizing the FTP service on CentOS

In this process, you will learn how to customize your vsftpd installation. vsftpd has a lot of configuration parameters, and here we will show how to create a custom welcome banner, change the server’s default-time out, limit user connections, and ban users from the service.

To Start With: What Do You Need?

To complete this process, you will require a working installation of the CentOS 7 operating system with root privileges and a console-based text editor of your choice. It is expected that your server will be using a static IP address and that vsftpd is already installed with a chroot jail and is currently running.

The Process

  1. To begin with, log in as root and open the main vsftpd configuration file:
    vi /etc/vsftpd/vsftpd.conf
  2. First, provide an alternative welcome message, uncomment the following line, and alter the message as required. For example, you could use this:
    ftpd_banner=Welcome to my new FTP server
  3. To change the default FTP time-outs, uncomment these lines and substitute the numeric values as required:
    idle_session_timeout=600
    data_connection_timeout=120
  4. Now, we will limit the connections: the data transfer rate in bytes per second, the number of clients, and the maximum parallel connections per IP address. Add the following lines to the end of the file:
    local_max_rate=1000000
    max_clients=50
    max_per_ip=2
  5. Next, save and close the file. To ban a specific user, you can use the following commands while replacing the username with an appropriate system user value that fits your needs:
    echo "username" >> /etc/vsftpd/user_list
  6. Now to apply the changes, restart the FTP service:
    systemctl restart vsftpd

How Does It Work?

In this process, we have shown some of the most important vsftpd settings. Covering all the configuration parameters here is outside the scope of this process. To learn more about it, read through the entire main vsftpd configuration file at /etc/vsftpd/vsftpd.conf, as it contains a lot of useful comments; alternatively, you can read the man vsftpd.conf manual.

So what did we learn from this experience?

We began by opening the main vsftpd configuration file and then activated and customized the welcome banner using the ftpd_banner directive. On the next successful login, your users should see your new message. Next, when dealing with a large number of users, you may want to consider changing the values for a default timeout and limit the connections in order to improve the efficiency of your FTP service.

First, we changed our server’s timeout numbers. An idle_session_timeout of 600 seconds will logout the user if he is inactive (not executing FTP commands) for 10 minutes, while a data_connection_timeout of 120 seconds will kill the connections when a client data transfer is stalled (not progressing) for 20 minutes. Then we changed the connection limits. A local_max_rate of 1000000 bytes per second will limit the data transfer rate of a single user to roughly one megabyte per second. A max_clients value of 50 will tell the FTP server to only allow 50 parallel users to the system, while a max_per_ip of 2 allows only two connections per IP address.

Then we saved and closed the file. Finally, we showed how to ban users from using our FTP service. If you wanted to ban a specific user from using the FTP service as a whole, the user’s name should be added to the /etc/vsftpd/user_list file. If you ever need to re-enable the user at any time, simply reverse the previous process by removing the user concerned from /etc/vsftpd/user_list.