PCPlanet – Tech Blogs | Information
  • Home
  • Tools
    • CHMOD Calculator
    • Subnet Calculator
  • Linux Guides & Tutorials
    • Beginner Guides
    • Linux Installation Tutorials
    • Command Line Tutorials
    • Server Administration Guides
    • Security Tutorials
    • Database Tutorials
    • Open-Source Software
      • Nextcloud Guides
      • Apache
    • Operating Systems
      • Ubuntu
      • RHEL/Rocky/Alma
  • Ransomware News
  • Cybersecurity Laws and Regulations
Top Posts
How to install Emby Server on Ubuntu
Best Linux distribution (distros) in 2022
15,000 WordPress Sites hacked with Malicious Redirects
How to Install Python 3.9 on Ubuntu 18.04
How to Install Python 3.9 on Ubuntu 16.04
How to Install MongoDB on Ubuntu 16.04 to...
How to enable HSTS on Apache
How to install Python on CentOS 8
How to install PHP 8.1 on RHEL based...
Comment activer HSTS pour Apache
Navigating CVE-2023-49103: Proactive Defense for ownCloud
Thursday, May 15, 2025
PCPlanet – Tech Blogs | Information
  • Home
  • Tools
    • CHMOD Calculator
    • Subnet Calculator
  • Linux Guides & Tutorials
    • Beginner Guides
    • Linux Installation Tutorials
    • Command Line Tutorials
    • Server Administration Guides
    • Security Tutorials
    • Database Tutorials
    • Open-Source Software
      • Nextcloud Guides
      • Apache
    • Operating Systems
      • Ubuntu
      • RHEL/Rocky/Alma
  • Ransomware News
  • Cybersecurity Laws and Regulations
PCPlanet – Tech Blogs | Information
PCPlanet – Tech Blogs | Information
  • Home
  • Tools
    • CHMOD Calculator
    • Subnet Calculator
  • Linux Guides & Tutorials
    • Beginner Guides
    • Linux Installation Tutorials
    • Command Line Tutorials
    • Server Administration Guides
    • Security Tutorials
    • Database Tutorials
    • Open-Source Software
      • Nextcloud Guides
      • Apache
    • Operating Systems
      • Ubuntu
      • RHEL/Rocky/Alma
  • Ransomware News
  • Cybersecurity Laws and Regulations
Copyright 2021 - All Right Reserved
Linux

Install and Configure Fail2Ban Ubuntu & RHEL

by pcplanet June 29, 2023
written by pcplanet 29 minutes read

Introduction

As cyber threats continue to evolve and become increasingly sophisticated, safeguarding your servers is more important than ever. One effective way to fortify your systems against unwarranted intrusion is by employing an intrusion prevention software tool like Fail2Ban.

Fail2Ban is an open-source software that protects your system against brute-force attacks. By scanning log files for any malicious activity, it identifies and bans IP addresses displaying suspicious behavior. It does this by dynamically altering the firewall rules to reject incoming connections from these addresses. This vital tool not only enhances your system’s security but also conserves resources that would otherwise be expended handling invalid requests.

In this comprehensive guide, we delve into the nuts and bolts of Fail2Ban – how to install it, configure it, and make it an effective component of your security strategy. Primarily, our focus will be on the installation and configuration of Fail2Ban on two popular Linux distributions – Ubuntu 20.04 and Red Hat Enterprise Linux (RHEL) 8.

Whether you’re a system administrator looking to enhance your server security or a tech enthusiast eager to broaden your knowledge about open-source security software, this guide is tailored to meet your needs. We’ll cover everything from basic installation procedures to advanced configurations, providing practical examples to illustrate each point clearly. Moreover, we’ll address common issues that might arise during the process and offer potential solutions.

  • Creating Custom Nginx Rules for Different Subdomains in DirectAdminOctober 27, 2024
  • Nginx Reverse Proxy for Nextcloud: A GuideJune 20, 2024
  • How to Reverse Proxy in DirectAdmin with Nginx_ApacheMay 13, 2024

Understanding Fail2Ban

To maximize the benefits Fail2Ban offers, we must first understand its workings, features, and components. This knowledge lays the foundation for proficiently installing and configuring this essential security tool.

Fail2Ban is a powerful open-source software that serves as an intrusion prevention system. It operates by continually monitoring your system’s log files for any signs of malicious activity such as repeated failed login attempts – often a telltale sign of a brute-force attack. When it detects such activity, Fail2Ban swings into action, blocking the offending IP address from making further connections.

At the heart of Fail2Ban’s operation are three main components: filters, actions, and jails.

Filters are a set of definitions or rules that Fail2Ban uses to parse the log files. These rules help Fail2Ban identify patterns of suspicious behavior.

Actions define what Fail2Ban should do once it identifies a potential threat. Typically, an action involves altering the firewall rules to block the offending IP address. However, actions can also include sending email notifications about the event.

The bridge between filters and actions is the jail. A jail in Fail2Ban binds a specific filter with an action. Essentially, a jail specifies that if certain suspicious activity is detected (as defined by the filter), a particular action should be taken.

Moreover, Fail2Ban is highly configurable, allowing you to define custom rules and actions that best suit your security needs. You can modify the ban duration, specify certain IP addresses to ignore, adjust the threshold for banning an IP, and much more.

Sure! Here’s the reformatted text with the command lines presented as code in the Gutenberg editor for WordPress:

Before we start, it’s important to remember that we will be making significant changes to the system. Ensure you have backed up any crucial data and proceed with caution.

1. Installing Fail2Ban on Ubuntu 20.04

Fail2Ban is available in the standard Ubuntu 20.04 repositories, which makes its installation straightforward. Here is a step-by-step guide on how to do it:

Step 1: Update your System

Before installing any new package, it’s always a good idea to update your system. Open a terminal and run the following command:

sudo apt update && sudo apt upgrade -y

This command will fetch the list of available updates and install them on your system.

Step 2: Install Fail2Ban

With your system updated, you can now install Fail2Ban using the following command:

sudo apt install fail2ban -y

Wait for the installation process to complete.

Step 3: Verify the Installation

Once the installation is complete, verify if Fail2Ban is installed correctly and running with this command:

sudo systemctl status fail2ban

You should see a message indicating that Fail2Ban is active and running.

Step 4: Enable Fail2Ban to Start on Boot

To ensure that Fail2Ban starts automatically every time your system boots, use the following command:

sudo systemctl enable fail2ban

Congratulations! You have successfully installed Fail2Ban on your Ubuntu 20.04 system. In the following sections, we will discuss how to configure Fail2Ban and customize it to meet your specific needs. But before we proceed, let’s understand how to install Fail2Ban on a RHEL 8 system.

Certainly! Here’s the reformatted text with the headings and command lines presented as code in the Gutenberg editor for WordPress:

2. Installing Fail2Ban on RHEL 8

Just like in Ubuntu, Fail2Ban is readily available from the standard repositories in RHEL 8, simplifying the installation process. Let’s walk through this process step-by-step:

Step 1: Update Your System

Before installing new packages, it is recommended to update your system. Open your terminal and type:

sudo dnf update -y

This command will fetch the list of available updates and install them.

Step 2: Install the EPEL Repository

The Fail2Ban package is part of the Extra Packages for Enterprise Linux (EPEL) repository, which is not enabled by default. To install it, use the following command:

sudo dnf install epel-release -y

Step 3: Install Fail2Ban

With the EPEL repository enabled, you can now install Fail2Ban. Type the following command in the terminal:

sudo dnf install fail2ban -y

Wait for the process to finish before moving to the next step.

Step 4: Check the Installation

Once the installation is complete, you can check if Fail2Ban is installed and running by using this command:

sudo systemctl status fail2ban

If Fail2Ban is running successfully, you should see a message indicating that the service is active.

Step 5: Enable Fail2Ban to Start on Boot

Lastly, ensure Fail2Ban starts automatically at boot with the following command:

sudo systemctl enable fail2ban

And there you have it – Fail2Ban is now installed on your RHEL 8 system. In the upcoming sections, we’ll explore how to configure and customize Fail2Ban for optimal server security. Now that we have covered the installation process for both Ubuntu 20.04 and RHEL 8, we are ready to dive deeper into the world of Fail2Ban configurations.

Configuring Fail2ban

Understanding Fail2Ban Configuration Files

To effectively harness the power of Fail2Ban, it’s essential to understand its configuration files. The primary ones are jail.conf and jail.local, and they play a pivotal role in customizing Fail2Ban’s behavior to suit your unique needs.

1. The jail.conf File

The jail.conf file is the default configuration file that comes with the installation of Fail2Ban. It contains a series of “jails,” each of which associates a log file with one or more actions and filters. The jail.conf file contains numerous preset jails for various services like SSH, Apache, and more. Each jail specifies the rules that Fail2Ban follows when monitoring the log files for these services.

While you can directly modify jail.conf, it’s not recommended because this file may be overwritten when Fail2Ban is updated. Instead, it’s better to create and modify a jail.local file, as explained below.

2. The jail.local File

The jail.local file is where you should make your custom configuration changes. If this file is present, Fail2Ban will prioritize it over jail.conf. If it’s not present, you can create it by copying the jail.conf file. You can then modify this copy according to your needs. Any changes you make in jail.local will override the corresponding settings in jail.conf.

To create a jail.local file, use the following command:

sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

Then, open jail.local with a text editor of your choice (like nano or vim) and make your desired changes.

Creating and Modifying Filters

A filter in Fail2Ban defines the patterns to look for in a log file. Filters are stored in individual files within the /etc/fail2ban/filter.d/ directory. These files contain regular expressions (regex) that match patterns indicative of unauthorized or malicious activity.

Fail2Ban comes with many predefined filters, but you can also create your own. To do this, create a new file in the /etc/fail2ban/filter.d/ directory with a .conf extension, then add your regular expressions to this file.

For example, to create a new filter file called myfilter.conf, you would run:

sudo nano /etc/fail2ban/filter.d/myfilter.conf

Then, inside this file, you might add something like:

[Definition]
failregex = Failed login from <HOST>
ignoreregex =

The failregex line defines the pattern that Fail2Ban will look for in the log files. <HOST> is a placeholder that matches any IP address.

Understanding how to work with these configuration files and filters is key to customizing Fail2Ban to suit your specific needs. In the next section, we will look at how to configure Fail2Ban on both Ubuntu 20.04 and RHEL 8, using the principles we’ve just discussed.

Customizing Fail2Ban Configurations for Ubuntu 20.04 and RHEL 8

Given the similarities between Ubuntu and RHEL regarding Fail2Ban configurations, the same steps can generally be applied to both. Let’s explore how to customize Fail2Ban to enhance the security of your server on both these platforms.

Step 1: Duplicating the jail.conf File

As a standard practice, refrain from modifying the original jail.conf file. Instead, create a duplicate named jail.local. Execute the command below to achieve this:

sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

Step 2: Accessing the jail.local File

Use a text editor to open and modify the jail.local file. We’ll use nano in this example:

sudo nano /etc/fail2ban/jail.local

Step 3: Tailoring Fail2Ban Settings

Inside jail.local, there are two key areas to focus on: the [DEFAULT] section and the specific jail sections.

  • Refining the [DEFAULT] Section

The [DEFAULT] segment contains settings applicable to all jails unless they are overridden in the individual jail sections. Significant parameters that you might want to customize include:

  • ignoreip: Specifies IP addresses that Fail2Ban will never ban. By default, it only includes 127.0.0.1 (localhost).
  • bantime: Sets the ban duration (in seconds). The default is 600 seconds (10 minutes). If you desire to ban for an hour, for instance, set this to 3600.
  • findtime: Determines the period (in seconds) within which Fail2Ban counts failed attempts. The default is also 600 seconds.
  • maxretry: Specifies the number of failures (within the findtime) that triggers a ban. The default is 5.
  • Adjusting Individual Jails

Post the [DEFAULT] section, you’ll find several individual jail sections for various services like [sshd], [apache], and more. Enable or disable these jails by setting enabled = true or enabled = false, respectively. Moreover, you can override any default settings within these jail sections.

Suppose you intend to activate the sshd jail and ban offending IPs for a day after three failed attempts within 15 minutes. In that case, you might modify the [sshd] section as follows:

[sshd]
enabled = true
bantime = 86400
findtime = 900
maxretry = 3

Step 4: Saving and Exiting the File

Once you have made the desired changes, save and close the file. In nano, you can do this by pressing Ctrl+X, then Y, then Enter.

Step 5: Relaunching Fail2Ban

Apply your new configuration by restarting Fail2Ban with the following command:

sudo systemctl restart fail2ban

You can now verify the status of Fail2Ban using sudo fail2ban-client status. The output should reflect the jails you’ve enabled.

Remember, this is just a primer to configuring Fail2Ban. The software is incredibly versatile, with a plethora of settings and options for you to fine-tune according to your security needs. For an in-depth understanding, consider exploring the official Fail2Ban documentation.

Implementing Advanced Fail2Ban Configurations

I. Banning Persistent Offenders

In the realm of server security, the persistent offenders – those that continuously attempt to breach your system – pose a significant threat. By exploiting different vulnerabilities or brute-forcing their way into the system, these relentless attackers can severely impact your server’s security and overall performance. Hence, it becomes crucial to have mechanisms in place to handle such persistent threats. One such mechanism involves leveraging Fail2Ban’s “recidive” jail. In this section, we will understand what “recidive” jail is and how to configure it to ban persistent offenders.

Understanding the ‘recidive’ Jail

Fail2Ban’s ‘recidive’ jail provides an extra layer of security to your server by handling repeat offenders who keep hitting the server even after being banned multiple times. The ‘recidive’ jail monitors Fail2Ban’s own log file and bans IPs that have been banned more than a certain number of times within a given period. These bans are usually much longer, helping to keep persistent attackers at bay.

Configuring the ‘recidive’ Jail

To configure the ‘recidive’ jail, open the jail.local file:

sudo nano /etc/fail2ban/jail.local

Find the section labeled [recidive] and edit it as per your requirements. If it doesn’t exist, you can create one. Here is an example of a typical ‘recidive’ jail configuration:

[recidive]
enabled = true
filter = fail2ban
logpath = /var/log/fail2ban.log
banaction = iptables-allports
bantime = 86400   ; 1 day
findtime = 604800 ; 1 week
maxretry = 5

In the above configuration:

  • filter = fail2ban tells Fail2Ban to use the default Fail2Ban filter which matches lines in the log file indicating a ban.
  • logpath = /var/log/fail2ban.log sets the log file to be monitored by this jail.
  • banaction = iptables-allports sets the action to be taken when a ban occurs, which in this case is to ban the IP from all ports using iptables.
  • bantime = 86400 sets the ban duration to 1 day.
  • findtime = 604800 specifies that Fail2Ban should consider only the bans that have occurred within the last week.
  • maxretry = 5 means that an IP will be banned if it gets banned 5 times within one week.

Remember to replace the values as per your requirements.

Creating Custom Filters and Actions for Repeat Offenders

While the default ‘recidive’ jail configuration may be sufficient for many users, some may wish to create custom filters or actions for handling persistent offenders.

For example, suppose you wish to create a custom action that not only bans the IP but also sends an email alert whenever a persistent offender is banned. In that case, you can define a custom action file under the /etc/fail2ban/action.d/ directory, and then specify that action in your ‘recidive’ jail configuration.

Remember to always test your custom filters and actions to ensure that they work as expected before applying them to your live server.

Banning persistent offenders is an essential part of securing your server. By understanding how to configure the ‘recidive’ jail in Fail2Ban, you can effectively protect your server from repeated attacks.

II. Configuring Email Alerts

Alerts serve as critical components in any security system, promptly notifying administrators of any potential security issues. In the context of Fail2Ban, email alerts provide quick information about banned IPs and other security events, enabling administrators to take timely action. This section will detail the significance of email alerts and demonstrate how to configure email notifications in Fail2Ban.

The Importance of Email Alerts

Fast response to security incidents can mitigate potential damage and reduce the overall impact of an attack. Email alerts play a crucial role in this process by instantly informing system administrators about vital security events, such as an IP getting banned due to multiple failed login attempts. Furthermore, detailed email alerts can offer valuable insights into the nature of the attack, the offender’s IP, the service targeted, and the time of the event. All these details can contribute to a better understanding of the threat landscape and guide future security enhancements.

Email Notifications in Fail2Ban

Fail2Ban provides a built-in feature to send email notifications when an IP is banned. It uses the sendmail command by default to send emails. However, the exact mail command can be configured in the jail.local file. Besides the command, you can also specify the email address that should receive the alerts, the sender’s email address, and the format of the email.

Setting Up Email Alerts

Below are the step-by-step instructions on how to set up email alerts for banned IP addresses in Fail2Ban.

Step 1: Install Sendmail (if not already installed)

In Ubuntu 20.04 or RHEL 8, use the following command to install Sendmail:

sudo apt-get install sendmail    # For Ubuntu
sudo dnf install sendmail        # For RHEL
Step 2: Open the jail.local file

To configure email alerts, open the jail.local file in a text editor:

sudo nano /etc/fail2ban/jail.local
Step 3: Configure the email settings

In the [DEFAULT] section of the jail.local file, set the following parameters:

  • destemail: The email address that should receive the alerts.
  • sender: The sender’s email address (optional).
  • mta: The mail transfer agent (default is sendmail).
  • action: The action to be taken when an IP is banned. To send an email alert, use the action_mw or action_mwl action. The action_mw action sends an email with the whois report of the banned IP, while the action_mwl action sends an email with the whois report and relevant log lines.

Here is an example of how to configure these parameters:

[DEFAULT]
destemail = your-email@example.com
sender = fail2ban@example.com
mta = sendmail
action = %(action_mwl)s
Step 4: Save and close the file

After making the changes, save and close the file. If you’re using nano, press Ctrl+X, then Y, then Enter.

Step 5: Restart Fail2Ban

Finally, restart Fail2Ban to apply the new settings:

sudo systemctl restart fail2ban

Now, whenever an IP gets banned, Fail2Ban will send an email alert to the specified email address.

In conclusion, setting up email alerts in Fail2Ban is a straightforward yet powerful way to enhance your server’s security. It ensures that you stay informed about critical security events and can take immediate action when needed.

III. Creating Custom Filters and Actions

Fail2Ban provides a powerful feature to create custom filters and actions. Custom filters allow you to define specific log patterns that Fail2Ban should consider as failed attempts, while custom actions define what Fail2Ban should do when it finds a match to these patterns. In this section, we will discuss the process of creating custom filters and actions, their use cases, and demonstrate how to set them up.

Understanding Custom Filters

A filter in Fail2Ban is a set of rules that define what log entries should be considered as failed attempts. Each filter is defined in a file located in the /etc/fail2ban/filter.d/ directory and uses regular expressions to match log entries.

Custom filters can be very useful in situations where the default filters don’t cover specific attack patterns. For instance, you might have services like FTP, SFTP, SMB, or SMTP running on your server, and you want Fail2Ban to ban IPs that make repeated failed login attempts to these services. In such cases, you can create custom filters to match the log entries generated by these services.

Creating Custom Filters

Here is an example of how you can create a custom filter for an FTP service:

  1. Create a new filter file: Open a new file in the /etc/fail2ban/filter.d/ directory, let’s name it custom-ftp.conf: sudo nano /etc/fail2ban/filter.d/custom-ftp.conf
  2. Define the filter rules: In the custom-ftp.conf file, define the failregex that matches the failed login attempts in the FTP server’s log. For instance: [Definition] failregex = ^.*authentication failure;.* rhost=<HOST>$ Replace the failregex line with the actual log pattern of the failed login attempts.
  3. Save and close the file: Press Ctrl+X, then Y, then Enter to save and close the file.

Defining Custom Actions

Custom actions in Fail2Ban define what should be done when a filter matches a log entry. For instance, you might want to run a specific script or command, send an email, or even sound an alarm when an IP gets banned. Custom actions can be defined in files located in the /etc/fail2ban/action.d/ directory.

Here is how you can create a custom action that sends an email with a custom message:

  1. Create a new action file: Open a new file in the /etc/fail2ban/action.d/ directory, let’s name it custom-email.conf: sudo nano /etc/fail2ban/action.d/custom-email.conf
  2. Define the action rules: In the custom-email.conf file, define what should be done in the actionstart, actionstop, actioncheck, actionban, and actionunban sections. For instance, you can use the mail command in the actionban section to send an email when an IP is banned: [Definition] actionstart = actionstop = actioncheck = actionban = mail -s "Fail2Ban Alert: IP <ip> has been banned" your-email@example.com <<< "IP <ip> has been banned by Fail2Ban due to multiple failed login attempts to the FTP service." actionunban =
  3. Save and close the file: Press Ctrl+X, then Y, then Enter to save and close the file.

Finally, don’t forget to restart Fail2Ban after creating or modifying filters and actions:

sudo systemctl restart fail2ban

By understanding how to create custom filters and actions in Fail2Ban, you can enhance your server’s security and tailor it to your specific needs. Always ensure to test your custom filters and actions thoroughly to verify their functionality and impact on your server’s performance.

IV. Utilizing Fail2Ban APIs and External Scripts

The versatility of Fail2Ban extends beyond its in-built features. The software’s functionality can be further enhanced through the use of its APIs and the implementation of external scripts. These allow for a programmatic interaction with Fail2Ban, enabling you to create custom solutions tailored to your specific needs. In this section, we will explore how to leverage APIs and external scripts to extend the functionality of Fail2Ban and integrate it with other tools.

Interacting with Fail2Ban APIs

Fail2Ban, as of my knowledge cut-off in September 2021, doesn’t directly offer a REST API or similar interface for programmatic interaction. However, it does provide a Python-based API that allows you to interact with the Fail2Ban server programmatically.

By using this API, you can create, delete, and manage jails, fetch information about banned IPs, set the ban time, and perform many other actions. This can be particularly useful when you want to extend the functionality of Fail2Ban, or integrate it with other tools or systems.

Leveraging APIs for Extending Functionality

You can leverage Fail2Ban APIs to create custom solutions that extend its functionality. For example, you could write a Python script that automatically fetches the list of currently banned IPs and posts it to a Slack channel. Or you could create a web interface that displays real-time Fail2Ban statistics. The possibilities are virtually endless.

Implementing External Scripts for Custom Actions

Another way to enhance Fail2Ban’s functionality is by using external scripts. These scripts can be written in any language and can be triggered by Fail2Ban when certain events occur.

For instance, you might want to run a specific script when an IP gets banned or unbanned. You can do this by creating a custom action (as we discussed in the previous section) that calls your script.

Here is an example of a custom action that calls an external script:

  1. Create a new action file: Open a new file in the /etc/fail2ban/action.d/ directory, let’s name it custom-script.conf: sudo nano /etc/fail2ban/action.d/custom-script.conf
  2. Define the action rules: In the custom-script.conf file, you can call your script in the actionban or actionunban sections: [Definition] actionstart = actionstop = actioncheck = actionban = /path/to/your/script.sh <ip> actionunban = /path/to/your/other/script.sh <ip>
  3. Save and close the file: Press Ctrl+X, then Y, then Enter to save and close the file.

V. Implementing Whitelists and Exemptions

While Fail2Ban is an essential tool for securing your server, there might be certain situations where you want to exempt specific IP addresses or services from being monitored by Fail2Ban. This is where the concept of whitelisting and exemptions comes into play. In this section, we’ll delve into the significance of implementing whitelists and exemptions, explain how to configure them in Fail2Ban, and present some common scenarios where they might be required.

The Importance of Whitelisting and Exemptions

In some circumstances, it might be necessary to whitelist certain trusted IP addresses, effectively excluding them from the scrutiny of Fail2Ban. This could be applicable, for instance, when you have specific IP addresses that need to continuously connect to your server, and you want to prevent them from being accidentally banned due to some unforeseen circumstances like a faulty login script.

Similarly, exemptions allow you to exclude certain services from Fail2Ban protection. For example, you might have an internal service that doesn’t require protection from Fail2Ban, and you want to avoid unnecessary load on your server by excluding this service from Fail2Ban’s monitoring.

Configuring Whitelists and Exemptions in Fail2Ban

To whitelist an IP address in Fail2Ban, you need to modify the ignoreip parameter in the jail.local file. Here’s how to do it:

  1. Open the jail.local file: sudo nano /etc/fail2ban/jail.local
  2. Add the IP address to the ignoreip parameter: In the [DEFAULT] section of the file, add the IP address you want to whitelist to the ignoreip parameter. You can specify multiple IP addresses separated by space: [DEFAULT] ignoreip = 127.0.0.1/8 ::1 192.168.0.100

To exempt a service from Fail2Ban, simply do not create a jail for that service in the jail.local file.

Scenarios for Whitelisting and Exemptions

Let’s consider some scenarios where you might want to implement whitelisting or exemptions.

  • Trusted IP addresses: You might have certain IP addresses that belong to trusted users or administrators. These addresses can be whitelisted to prevent accidental bans.
  • Fault-tolerant services: There might be some services in your server that have built-in security measures and don’t require additional protection from Fail2Ban. Such services can be exempted to reduce the load on the server.
  • Internal services: Services that are only accessible internally and are not exposed to the internet can be exempted from Fail2Ban protection, as they pose a low risk of being attacked.

VI. Log Analysis and Visualization

Monitoring the behavior of your server is a critical aspect of maintaining its security. Fail2Ban logs provide valuable insights into security events and can help identify attack patterns and potential vulnerabilities. This section will discuss the importance of analyzing Fail2Ban logs, introduce tools and techniques for this purpose, and explain how to visualize Fail2Ban data for better understanding and interpretation.

The Importance of Log Analysis

Fail2Ban logs contain detailed information about its operations, including which IP addresses were banned, when they were banned, and which service triggered the ban. By analyzing these logs, you can identify patterns and trends, such as repeated attacks from the same IP address or a sudden surge in failed login attempts, indicating a possible brute-force attack.

Additionally, log analysis can also aid in troubleshooting and fine-tuning Fail2Ban’s configuration. For example, if a trusted IP address is being banned repeatedly, it may indicate that you need to adjust the fail2ban sensitivity or whitelist that IP.

Tools and Techniques for Log Analysis

There are several tools available for analyzing Fail2Ban logs. fail2ban-client, the command-line interface provided with Fail2Ban, offers several commands for viewing the current status of Fail2Ban, such as fail2ban-client status, which shows the status of all active jails.

For more advanced log analysis, you can use log management tools such as Logwatch, Logcheck, or GoAccess. These tools can parse the logs, identify important events, and provide reports.

You can also write custom scripts to analyze the logs. For instance, a simple Bash or Python script can parse the Fail2Ban log file and identify the most frequently banned IP addresses.

Visualizing Fail2Ban Data

Visual representation of data is a powerful way to understand complex patterns and trends. Tools such as Grafana or Kibana allow you to create dashboards for visualizing Fail2Ban logs. These dashboards can include graphs, charts, and tables that show the number of banned IPs over time, the most targeted services, the most frequently banned IPs, and more.

To visualize Fail2Ban data, you need to export the logs to a format that your visualization tool can understand. This can be done using a log shipper like Filebeat or Fluentd.

VII. Testing and Monitoring

Implementing advanced configurations in Fail2Ban, such as custom filters and actions, can significantly enhance your server’s security. However, it’s equally important to thoroughly test and monitor these configurations to ensure they’re working as expected and aren’t causing any unintended side effects. This section discusses the significance of testing and monitoring in Fail2Ban and provides guidelines on how to effectively test your custom configurations.

The Importance of Testing and Monitoring

While creating custom configurations in Fail2Ban provides a level of flexibility, it also brings in complexity. Even a minor mistake in a filter or action can lead to serious issues such as banning legitimate users or failing to ban malicious users. Hence, it’s crucial to thoroughly test your configurations to make sure they work correctly.

Furthermore, monitoring the performance and effectiveness of your Fail2Ban configurations can help you fine-tune them and adapt to changing circumstances. For example, if a particular filter is banning too many IP addresses, you might need to adjust its sensitivity. Similarly, if an action is not working as expected, monitoring can help you identify and fix the problem.

Testing Custom Filters, Actions, and Configurations

Fail2Ban provides a utility called fail2ban-regex that allows you to test your custom filters against your log files. This utility is a powerful tool to validate your filters before deploying them in a live environment. Here’s how to use it:

fail2ban-regex /path/to/your/logfile.log /etc/fail2ban/filter.d/your-filter.conf

This command will test the filter defined in your-filter.conf against the log file logfile.log and show you the matched lines. This way, you can verify that your filter is catching the right log entries and adjust it if necessary.

For testing actions, unfortunately, there’s no built-in tool in Fail2Ban. The best way to test an action is to apply it to a temporary jail and trigger it manually. You can do this by setting the maxretry and findtime parameters to low values, which will cause the action to trigger quickly.

In conclusion, effective testing and monitoring are key to maintaining a secure and efficient Fail2Ban setup. They enable you to validate your custom configurations, detect issues early, and ensure your server remains secure against potential threats.

Troubleshooting Common Fail2Ban Issues

Like any robust software, encountering issues while installing or configuring Fail2Ban is not uncommon. These issues can vary, ranging from installation hurdles to difficulties during the configuration of filters or actions. This section aims to address some frequently occurring Fail2Ban challenges, providing pragmatic solutions and tips to troubleshoot these obstacles.

Installation Problems

A fairly common issue users may encounter relates to difficulties arising during the installation process. If you find yourself struggling to install Fail2Ban, it could be due to several factors:

Ensuring System Updates

First and foremost, make sure your system is up-to-date. You can accomplish this by running sudo apt update && sudo apt upgrade on Ubuntu or sudo yum update on RHEL.

Checking Repositories

If the package manager can’t find the Fail2Ban package, it may indicate that the required repositories aren’t enabled or your package list isn’t up-to-date.

Verifying Dependencies

When installing from source and encountering issues, ensure all the necessary dependencies are installed.

Filters Not Catching Log Entries

If your filters aren’t catching the log entries they should, several potential issues can be checked:

Log Path Mismatch

Ensure the log path in your jail configuration aligns with the actual location of your log files.

Using fail2ban-regex

The fail2ban-regex tool is quite handy for testing your filters against your log files. This tool can help pinpoint any mismatches or issues with your filter patterns.

Checking failregex

Make sure the failregex in your filter configuration is correctly formatted and captures the log entries you intend to ban.

Actions Failing to Trigger

If actions are not being triggered when they should be, consider the following troubleshooting steps:

Checking Jail Configuration

Make sure the action is correctly defined in your jail configuration.

Verifying Parameters

Check that the maxretry and bantime parameters are set appropriately.

Consulting Fail2Ban Logs

Consult your Fail2Ban logs (/var/log/fail2ban.log) for any error messages or warnings related to your actions.

Difficulties with Whitelisting

If whitelisting IP addresses presents a challenge:

Adding IPs Correctly

Ensure the IP addresses are correctly added to the ignoreip parameter in the jail.local file.

Restarting Fail2Ban Service

Remember to restart the Fail2Ban service after making changes to the configuration files.

In conclusion, by identifying and troubleshooting these common issues, you can ensure that your Fail2Ban installation functions as effectively as possible. Always double-check your configurations, and rigorously test your filters and actions before applying them to a live environment.

Conclusion

Securing your server environment is a crucial responsibility, and as we have seen throughout this blog post, Fail2Ban offers a powerful and flexible tool to help you do just that. From the basic installation process on different operating systems, to understanding and customizing its core configuration files, we’ve covered a wide range of topics that equip you with the knowledge to optimize Fail2Ban to your needs.

Initially, we delved into the basic installation steps on both Ubuntu 20.04 and RHEL 8, demonstrating that the process is quite straightforward, thanks to the package managers of these systems. Building upon that, we explored the intricate details of Fail2Ban’s configuration files – the jail.conf and jail.local files. We learned how to create and modify filters to match specific log entries, a critical aspect of tailoring Fail2Ban’s behavior.

In addition, we examined the process of configuring Fail2Ban to handle persistent offenders and discussed the importance of creating custom filters and actions. These steps allow you to refine Fail2Ban’s response to repeated threats and tailor its actions to match the unique security requirements of your server environment.

We also delved into the versatility of Fail2Ban’s APIs and how external scripts can further extend its capabilities. Furthermore, we discussed the need for whitelists and exemptions, understanding how to effectively implement them.

In summary, while Fail2Ban is a powerful tool, its effectiveness lies in proper configuration, regular monitoring, and adaptive management. As we’ve seen, the software offers numerous customization options that allow you to tailor its operations to your server’s unique needs. With careful implementation and monitoring, Fail2Ban can be an essential asset in your security toolkit.

June 29, 2023 0 comments
1 FacebookTwitterPinterestEmail
Linux

Basic Linux Commands

by pcplanet June 23, 2023
written by pcplanet 19 minutes read

Introduction

In the realm of operating systems, Linux holds a place of honor. It’s a symbol of versatility, power, and freedom in the world of software, with its open-source roots giving users a level of control and customization few other operating systems can match. At the heart of Linux’s prowess is its command-line interface, a powerful tool that provides unparalleled control over the system.

Whether you’re a developer, a system administrator, or a tech enthusiast, mastering Linux commands is not just a skill – it’s a rite of passage. These commands allow you to interact with your system, navigate through directories, manipulate files, monitor system resources, and even control other machines remotely. And that’s just scratching the surface. This blog aims to shed light on the essential Linux commands, their purpose, features, and how to use them effectively.

The command-line interface might seem daunting initially, especially if you’re used to graphical user interfaces. However, understanding the purpose of Linux commands (our first keyphrase) will demystify the Linux command line and reveal it as an indispensable tool, a true friend of every Linux user. You’ll discover that every command, from ‘ls’ to ‘sudo’, serves a specific purpose designed to make tasks easier, faster, and more efficient.

But understanding the purpose is just the first step. You’ll also explore the unique features of these commands, learning how options and arguments can change command behavior, and how commands can be combined for greater efficiency and automation. And, of course, we will guide you through the usage of these commands, with step-by-step examples and tips to help you navigate the Linux terminal with ease.

The Power of Linux Commands

In the dynamic realm of operating systems, Linux has carved a niche for itself as a paragon of flexibility, resilience, and power. A quintessential component of its power lies in the command-line interface, which offers a level of interaction that’s far beyond what any graphical user interface (GUI) can provide. It’s through this command-line interface that users can unlock the true potential of the Linux operating system.

Moving from the comfortable, graphical confines of operating systems like Windows or macOS to the text-based Linux command-line can initially seem challenging. However, real-world examples underscore the efficiency that comes with this shift. For instance, consider a simple task like finding all the PDF files in a directory and its subdirectories. A GUI would require you to manually click through each folder and subfolder. With a Linux command, such as find /path/to/directory -name "*.pdf", this task becomes a matter of seconds, regardless of how many nested folders you have.

Linux commands offer an unparalleled level of direct interaction with the system’s functions. A system administrator, for instance, can monitor real-time system processes using a command like top, which provides an ongoing look at processor activity in real time. A developer can streamline their workflow by using grep to search for a specific string in a codebase, or cron to schedule scripts to run at specific times. This direct control is a feature unique to command-line interfaces and is part of why learning Linux commands is indispensable for professionals in tech fields.

Think about the tech giants like Google, Amazon, and Facebook, who manage vast amounts of data across servers. These servers predominantly run on Linux, and understanding Linux commands is crucial for maintaining and troubleshooting these systems. For example, the rsync command is often used to synchronize files across multiple servers, while ssh allows administrators to remotely access and control these servers.

Thus, the command-line interface is not just another aspect of Linux; it’s a fundamental part of interacting with the system. Grasping the purpose and potential of Linux commands is not an option, but a necessity for those aiming to excel in Linux environments. So, let’s unravel the power and potential of these commands in the following sections.

Commonly Used Linux Commands and Their Purposes

Transitioning from our discussion on the overarching importance of Linux commands, we shift our focus to delve into specific, fundamental commands. Understanding these Linux commands and their usages paves the way towards effective navigation and interaction with the Linux environment. Let’s walk through 15 of the most useful beginner commands and their typical use-cases:

File and Directory Operations:

  1. ls: List directory contents
    • Example: ls (Lists all non-hidden files and directories in the current directory)
    • Example: ls -l (Lists files and directories in the current directory in long format, including additional information like permissions, owner, group, size, and modification time)
    • Example: ls -a (Lists all files and directories, including hidden ones)
  2. cd: Change directory
    • Example: cd /home/user/Documents (Changes the current directory to /home/user/Documents)
    • Example: cd .. (Navigates one directory up)
    • Example: cd (With no arguments, cd returns you to your home directory)
  3. pwd: Print working directory
    • Example: pwd (Displays the path of the current directory)
  4. touch: Create a new empty file
    • Example: touch myfile.txt (Creates a new empty file named myfile.txt in the current directory)
  5. cp: Copy files or directories
    • Example: cp source.txt destination.txt (Copies source.txt to destination.txt)
    • Example: cp -r sourcedir/ destinationdir/ (Copies a directory and all its contents to another directory)
  6. mv: Move or rename files or directories
    • Example: mv oldname.txt newname.txt (Renames a file from oldname.txt to newname.txt)
    • Example: mv myfile.txt /home/user/Documents/ (Moves myfile.txt to /home/user/Documents)
  7. rm: Remove files or directories
    • Example: rm myfile.txt (Deletes myfile.txt)
    • Example: rm -r mydir (Deletes a directory and its contents)
  8. find: Search for files or directories
    • Example: find /home/user/ -name '*.txt' (Searches the /home/user directory and all its subdirectories for files ending in .txt)
  9. mkdir: Create new directory
    • Example: mkdir newdir (Creates a new directory named newdir in the current directory)
  10. rmdir: Remove directory
    • Example: rmdir mydir (Deletes the directory named mydir. Note that this command only works on empty directories)

Folder/File Viewing and Editing:

  1. cat: Concatenate and display file content
    • Example: cat file.txt (Displays the content of file.txt)
  2. less: View file content page by page
    • Example: less file.txt (Opens file.txt for viewing in the terminal, one page at a time)
  3. more: Another tool to view file content page by page
    • Example: more file.txt (Opens file.txt for viewing in the terminal, one page at a time)
  4. head: View the start of a file
    • Example: head file.txt (Displays the first ten lines of file.txt)
    • Example: head -n 20 file.txt (Displays the first twenty lines of file.txt)
  5. tail: View the end of a file
    • Example: tail file.txt (Displays the last ten lines of file.txt)
    • Example: tail -n 20 file.txt (Displays the last twenty lines of file.txt)
  6. nano: Simple text editor
    • Example: nano file.txt (Opens file.txt in the Nano text editor for editing)
  7. vi: Advanced text editor
    • Example: vi file.txt (Opens file.txt in the Vi text editor for editing)

File Permissions and Ownership:

  1. chmod: Change file permissions
    • Example: chmod 755 script.sh (Sets the permissions of script.sh to 755, allowing the owner to read, write, and execute the file, and others to read and execute it)
    • Alternative: setfacl is an alternative tool that provides more fine-grained control over file permissions, allowing you to set permissions for specific users or groups.
    • Feature: chmod is a versatile command that enables you to modify file permissions to control read, write, and execute access for owners, groups, and others.
  2. chown: Change file ownership
    • Example: chown newuser file.txt (Changes the ownership of file.txt to newuser)
    • Example: chown newuser:newgroup file.txt (Changes both the ownership and group of file.txt)
    • Alternative: chgrp is a command used specifically to change group ownership of files and directories.
    • Feature: chown allows you to change the ownership of files or directories, providing control over access rights and privileges.
  3. chgrp: Change group ownership
    • Example: chgrp newgroup file.txt (Changes the group ownership of file.txt to newgroup)
    • Feature: chgrp is used to change the group ownership of files or directories, allowing you to manage file access permissions based on groups.

Process and Job Control:

  1. top: Display system summary and top processes
    • Example: top (Displays a dynamic, real-time view of the running system, including system summary information and a list of processes currently being managed by the kernel)
    • Alternative: htop provides an interactive and more user-friendly process viewer with features like sorting, filtering, and detailed system information.
    • Feature: top allows you to monitor system performance, view resource usage, and manage processes.
  2. ps: Report a snapshot of current processes
    • Example: ps (Displays a snapshot of the current processes)
    • Example: ps aux (Displays detailed information about all the current processes)
    • Alternative: pstree displays running processes in a tree-like structure, making it easier to visualize parent-child relationships.
    • Feature: ps provides information about active processes, including their IDs, resource usage, and relationships with other processes.
  3. kill: Terminate a process
    • Example: kill 1234 (Sends a signal to the process with PID 1234, usually resulting in that process terminating)
    • Example: killall process_name (Terminates all processes with the specified name)
    • Feature: kill allows you to send signals to processes, enabling you to terminate or control their behavior.
  4. bg: Send jobs to the background
    • Example: If you’re running a program like nano file.txt and you press Ctrl+Z, the program will suspend. Typing bg will make it continue running in the background.
    • Feature: bg allows you to move suspended or stopped jobs to the background, freeing up the terminal for other tasks.
  5. fg: Bring jobs to the foreground
    • Example: If you have a job running in the background (after using bg), you can type fg to bring it back to the foreground.
    • Feature: fg enables you to bring background jobs back to the foreground for interaction and control.

Package and System Management

  1. sudo: Execute a command as another user (usually the superuser)
    • Example: sudo apt-get update (Runs the apt-get update command with superuser permissions)
    • Feature: Allows regular users to run commands that require superuser permissions in a controlled manner.
    • Alternative: su (switch user), though it’s typically used less because it requires the root password and gives full root permissions, while sudo allows for more fine-grained control.
  2. apt-get: APT package handling utility (for Debian-based systems like Ubuntu)
    • Example: sudo apt-get install git (Installs the git package)
    • Example: sudo apt-get update (Updates the list of available packages and their versions, but it does not install or upgrade any packages)
    • Example: sudo apt-get upgrade (Upgrades all upgradable packages)
    • Feature: Easily manage packages on your system, allowing for simple installations, upgrades, and removals.
    • Alternative: apt is a newer tool that includes the most commonly used commands from apt-get and apt-cache with more user-friendly syntax.
  3. yum: Package manager (for Red Hat-based systems like CentOS)
    • Example: sudo yum install git (Installs the git package)
    • Example: sudo yum update (Updates all packages on the system)
    • Feature: Similar to apt-get, it allows easy management of packages but is used primarily on Red Hat-based systems.
    • Alternative: dnf is the next-generation version of yum used in newer Red Hat-based distributions like Fedora.
  4. shutdown: Shutdown or restart the system
    • Example: sudo shutdown -h now (Shuts down the system immediately)
    • Example: sudo shutdown -r 5 (Restarts the system after 5 minutes)
    • Feature: Provides a way to safely shut down or reboot your system.
    • Alternative: reboot for rebooting the system, poweroff to power it off.
  5. reboot: Reboot the system
    • Example: sudo reboot (Reboots the system immediately)
    • Feature: A quick way to restart your system.
    • Alternative: shutdown -r now

Networking

  1. ping: Send ICMP ECHO_REQUEST packets to network hosts
    • Example: ping google.com (Sends ICMP packets to google.com and reports the response time)
    • Feature: ping is commonly used to check network connectivity and measure the round-trip time (RTT) between the local machine and a remote host.
  2. ifconfig: Display or configure a network interface
    • Example: ifconfig (Displays information about all active network interfaces)
    • Example: ifconfig eth0 (Displays information about the network interface named eth0)
    • Alternative: ip command is a more modern and versatile alternative to ifconfig. It provides similar functionality with additional features and support for newer networking technologies.
    • Feature: ifconfig allows you to view and configure network interface settings, including IP addresses, netmasks, and other network parameters.
  3. netstat: Network statistics
    • Example: netstat (Shows network connections, routing tables, interface statistics, masquerade connections, and multicast memberships)
    • Alternative: ss command is a newer alternative to netstat that provides similar functionality but with better performance and more comprehensive output.
    • Feature: netstat provides information about network connections, network interfaces, routing tables, and various network statistics.
  4. ssh: Securely log into a remote machine
    • Example: ssh username@hostname (Logs into the machine hostname with the specified username)
    • Feature: ssh allows secure remote access to other machines over a network. It provides encrypted communication and secure authentication.
  5. scp: Securely copy files between hosts on a network
    • Example: scp sourcefile username@hostname:/path/to/destination (Copies sourcefile to the specified destination on the remote hostname)
    • Feature: scp enables secure file transfer between hosts on a network, utilizing SSH for encryption and authentication.
  6. wget: Retrieve files from the web
    • Example: wget http://website.com/file.txt (Downloads file.txt from the specified URL)
    • Feature: wget is a versatile command-line tool for downloading files from the web, supporting HTTP, HTTPS, and FTP protocols.

Disk Usage

  1. df: Report file system disk space usage
    • Example: df -h (Displays disk usage in human-readable format)
    • Feature: Provides information about the amount of disk space used and available on file systems.
    • Alternative: du command can be used to estimate file and directory space usage.
  2. du: Estimate file and directory space usage
    • Example: du -sh /path/to/directory (Displays the total size of the specified directory in human-readable format)
    • Feature: Allows you to determine the disk space occupied by files and directories.
    • Alternative: ncdu is a more interactive alternative that provides a detailed, navigable summary of disk usage.

Searching and Sorting

  1. grep: Print lines matching a pattern in a file
    • Example: grep "error" logfile.txt (Searches for the word “error” in logfile.txt and displays matching lines)
    • Alternative: ripgrep (rg) is an alternative tool to grep that offers faster searching with a similar syntax. It is optimized for speed and supports features like searching specific file types, ignoring files, and more.
    • Feature: grep is a versatile command-line tool that supports regular expressions and allows for complex pattern matching. It is widely used for searching and filtering text files.
  2. sort: Sort lines in text files
    • Example: sort names.txt (Sorts the lines in names.txt in ascending order)
    • Alternative: natsort is a natural sorting tool that sorts alphanumeric strings in a human-friendly way, producing more intuitive results compared to the default lexicographic sorting of sort.
    • Feature: sort provides extensive sorting capabilities, including numerical sorting, case-sensitive sorting, and the ability to sort based on specific keys or fields.
  3. uniq: Report or omit repeated lines
    • Example: uniq data.txt (Displays unique lines from data.txt, omitting duplicates)
    • Alternative: awk '!seen[$0]++' data.txt is an alternative way to achieve similar functionality using the Awk command. It eliminates duplicate lines and retains the original order.
    • Feature: uniq is a handy tool for identifying and eliminating duplicate lines from sorted or unsorted files. It also offers options to count the occurrences of each line and display only duplicates or unique lines.

Compression and Archives

  1. gzip: Compress or expand files
    • Example: gzip file.txt (Compresses file.txt and creates file.txt.gz)
    • Example: gzip -d file.txt.gz (Decompresses file.txt.gz and creates file.txt)
    • Alternative: pigz is a parallel implementation of gzip that utilizes multiple processor cores for faster compression and decompression.
    • Feature: gzip provides fast and efficient compression and decompression of files, commonly used for creating compressed archives or reducing file sizes.
  2. gunzip: Decompress files compressed by gzip
    • Example: gunzip file.txt.gz (Decompresses file.txt.gz and creates file.txt)
    • Feature: gunzip is a simple tool specifically designed to decompress files compressed using gzip.
  3. tar: Create, add to, or extract from an archive file
    • Example: tar -cvf archive.tar file1 file2 (Creates a tar archive named archive.tar containing file1 and file2)
    • Example: tar -xvf archive.tar (Extracts the contents of archive.tar)
    • Alternative: pax is a versatile archiving tool that supports multiple formats and provides more advanced features like extended file attributes and access control lists.
    • Feature: tar is commonly used for creating and manipulating archive files. It can compress files using other tools like gzip or bzip2 by combining commands, such as tar -cvzf to create a compressed tar archive.
  4. zip: Create, modify, or extract ZIP archives
    • Example: zip archive.zip file1 file2 (Creates a ZIP archive named archive.zip containing file1 and file2)
    • Example: unzip archive.zip (Extracts the contents of archive.zip)
    • Feature: zip is a widely used compression tool that supports various compression levels, password protection, and metadata preservation. It is compatible across different operating systems.

Help and Documentation

  1. man: Display the online manual of a command
    • Example: man grep (Displays the manual page for the grep command)
    • Feature: man provides detailed documentation, explanations, and usage examples for various commands and system functions.
  2. info: Display command’s info entry
    • Example: info tar (Displays the info entry for the tar command)
    • Feature: info is an alternative documentation system that provides more extensive and hypertextual documentation for commands and topics.
  3. whatis: Display one-line manual page descriptions
    • Example: whatis ls (Displays a brief description of the ls command)
    • Feature: whatis provides concise descriptions of commands, making it useful for quickly getting an overview of a command’s purpose.

Features of Linux Commands

  1. Piping (|): Piping is a powerful feature that allows the output of one command to be used as the input of another. This feature significantly enhances the interactivity of different commands. For instance, ls -l | grep ".txt" lists detailed information about only the .txt files in a directory, demonstrating a combination of ls and grep commands using a pipe.
  2. Redirection (>, >>, <): Redirection controls where the output of a command is sent. It can be directed to files, devices, or even to other commands. For example, ls -l > filelist.txt saves the long list of directory contents to the file filelist.txt. The >> appends the output to an existing file, while < takes input from a file.
  3. Command Chaining (;, &&, ||): Command chaining allows you to execute multiple commands consecutively. The ; operator executes commands in sequence, regardless of whether the previous command succeeded. On the other hand, the && operator only executes the second command if the first command succeeds, while || executes the second command only if the first fails. For instance, cd /var/log && ls changes to the /var/log directory and, if successful, lists its contents.
  4. Job Control (bg, fg, jobs, ctrl+z, &): Linux allows for great control over running processes. You can pause processes, resume them, run them in the background, or bring them back to the foreground. For example, a large file copy operation can be started with cp largefile newlocation & to run in the background, freeing up the terminal for other tasks.

These advanced features enhance the efficiency and flexibility of Linux commands, enabling users to perform complex operations, automate tasks, and customize their command-line experience. By mastering these features, you can unlock the full potential of the Linux command line.

How to Use Linux Commands

Having immersed ourselves in the world of Linux command features, it’s now time to transition into the practical aspect of our journey: using these commands effectively. In this section, we’ll explore a step-by-step guide to using basic Linux commands in the terminal, and share valuable tips for enhancing your command line efficiency.

  1. Open the Terminal: The first step to using Linux commands is to open the terminal. You can do this by searching for ‘terminal’ in your system’s application launcher or by using the keyboard shortcut Ctrl+Alt+T.
  2. Start with Basic Commands: Begin with simple commands like ls to list directory contents, cd to navigate between directories, and pwd to print your current working directory. Try these commands:
    • ls
    • cd /var
    • pwd
  3. Create and Remove Directories: Practice creating and removing directories using mkdir and rmdir respectively. For instance:
    • mkdir testdir
    • cd testdir
    • cd ..
    • rmdir testdir
  4. Create and View Files: Use the touch command to create a file and cat to view its contents. Try this:
    • touch testfile
    • cat testfile
  5. Delete Files: Practice caution while using the rm command to delete files as it does not move files to the trash, but deletes them permanently:
    • rm testfile
  6. Learn to Use Command Options: Most commands have options that modify their behavior. For instance, ls -l provides a detailed list of files, including permissions, number of links, owner, group, size, and time of last modification.
  7. Try Advanced Features: Once you are comfortable with the basics, explore advanced features like piping, redirection, and command chaining. Here’s an example of using piping and redirection together:
    • ls -l | grep ".txt" > txtfiles

Tips and Tricks for Efficient Command Usage

  • Use Tab Completion: When entering commands or file names, use the Tab key to auto-complete. This not only saves time but also reduces errors from typos.
  • Scroll Through Command History: Use the Up and Down Arrow keys to scroll through previously executed commands. This can be a great time-saver when you need to repeat commands.
  • Learn to Use man: The man command followed by any Linux command will bring up a helpful manual. Use this when you’re unsure about a command or want to learn more about its options: man ls.
  • Use clear or Ctrl+L to Clear the Terminal: Over time, the terminal can get cluttered with output from previous commands. Use clear or Ctrl+L to clear the terminal and start fresh.

Conclusion

In the world of operating systems, Linux commands stand out as a powerful tool that unlocks the true potential of the Linux operating system. The command-line interface offers unparalleled flexibility, resilience, and power, allowing users to interact with the system at a deeper level than graphical user interfaces can provide.

By understanding and utilizing Linux commands, you gain the ability to perform tasks efficiently and effectively. From simple operations like navigating directories and creating files to advanced features like piping, redirection, and command chaining, Linux commands offer a wide range of capabilities.

June 23, 2023 0 comments
0 FacebookTwitterPinterestEmail
Linux

How to Install Fedora: A Step-by-Step Guide

by pcplanet June 16, 2023
written by pcplanet 3 minutes read

Introduction to Fedora

Fedora, a powerful and robust operating system, is admired for its versatility, stability, and adherence to open-source principles. Originating from the revered lineage of Red Hat Linux, Fedora is a popular choice among developers, system administrators, and enthusiasts seeking an innovative yet dependable Linux distribution.

This post is designed to guide you through the process of how to install Fedora. Whether you’re a seasoned user making a switch or new to the world of Linux, this comprehensive tutorial will help you navigate the installation process with confidence and ease.

The beauty of Fedora lies in its ability to provide an advanced Linux environment that’s still accessible to beginners. By the end of this guide, you’ll have a firm grasp on how to install Fedora, setting you on the path towards mastering this outstanding operating system.

Preparing for Fedora Installation

Before embarking on the process to install Fedora, certain preliminary steps are essential. First and foremost, you’ll need to download the Fedora ISO file from the official Fedora website. Ensure that you select the correct version suitable for your system (32-bit or 64-bit).

Next, you’ll need to create a bootable USB or DVD with the downloaded Fedora ISO. There are various tools available for this purpose, such as Rufus or Fedora Media Writer. Follow the instructions provided by these tools to create your bootable device.

Finally, it’s prudent to back up any important data on the system where you plan to install Fedora. Although the installation process is generally safe, it’s always better to take precautions to prevent potential data loss.

Initiating the Fedora Installation Process

With your bootable device ready, it’s time to initiate the Fedora installation process. Restart your system and boot from the USB stick or DVD. This might require adjusting the boot order in your system’s BIOS or UEFI settings.

Once your system boots from the USB stick or DVD, you’ll encounter the Fedora welcome screen. Here, select your language preference and click on the ‘Continue’ button. You’ll then be directed to the Fedora Installation Summary screen.

On the Installation Summary screen, several options need to be configured, such as date and time, keyboard layout, installation destination, and more. Once you’ve carefully reviewed and configured these settings, click on the ‘Begin Installation’ button to proceed.

Completing the Fedora Installation

While Fedora is being installed, you’ll have the opportunity to set a root password and create a new user. It’s recommended to create a new user and assign administrative privileges to this account.

Once Fedora installation is complete, a ‘Finish Installation’ message will appear. Click on ‘Quit.’ Now, you can safely reboot your system, making sure to remove the installation media to avoid booting from it again.

Upon reboot, you’ll be greeted with the Fedora welcome screen, where you’ll finish up a few more configurations, such as privacy settings, online accounts, and more. Once completed, you’ll be directed to the Fedora desktop.

Getting Started with Fedora

Congratulations! You have successfully learned how to install Fedora. As you embark on your Fedora journey, keep in mind that Fedora, like any other operating system, might seem overwhelming at first, especially if you’re new to Linux.

However, with an array of resources available online, learning to navigate Fedora becomes much simpler. The Fedora community, in particular, is incredibly supportive, making it a fantastic source for resolving queries and expanding your knowledge.

In essence, mastering Fedora starts with familiarizing yourself with its environment. So, take the time to explore the Fedora workspace, try out different applications, and remember, every expert was once a beginner.

See our other Installation guides, choose your OS below

June 16, 2023 0 comments
0 FacebookTwitterPinterestEmail
Linux

How to Install Arch Linux: A Step-by-Step Guide

by pcplanet June 12, 2023
written by pcplanet 5 minutes read

Section 1: Introduction to Arch Linux

Arch Linux, one of the most popular Linux distributions, is known for its simplicity, user-centric approach, and versatility. While it’s primarily aimed at more experienced Linux users, beginners eager to learn more about Linux can also appreciate it.

If you’re thinking about taking the plunge and wondering how to install Arch Linux, this guide is for you. It aims to demystify the installation process and provide a comprehensive walkthrough to set up Arch Linux successfully.

Although the installation process might seem daunting initially, this step-by-step guide, when followed diligently, will give you a thorough understanding of how to install Arch Linux. It will guide you through the journey from downloading the ISO file to booting your system with a freshly installed Arch Linux.

Section 2: Pre-Installation Essentials

Before diving into the actual installation process, there are a few things you need to do. Firstly, visit the official Arch Linux website and download the latest ISO file. Be sure to verify the file using the provided checksum.

Next, create a bootable USB stick using the downloaded ISO file. Several tools, such as Rufus or Etcher, can help you create a bootable USB. If you’re already using a Linux distribution, the ‘dd’ command in the terminal is another way to achieve this.

Additionally, ensure that your system’s BIOS is set to boot from the USB stick. The method to access BIOS settings varies across different machines. Commonly, it involves pressing a specific key (like F2, F10, or Del) during system startup.

Section 3: Initiating the Arch Linux Installation Process

Once you’ve set your system to boot from the USB stick, restart your machine. On startup, you should see the Arch Linux boot menu. Here, select ‘Boot Arch Linux’ to proceed.

In the command line interface that appears, the first step is to check if your system’s BIOS is in UEFI mode by typing ‘ls /sys/firmware/efi/efivars’. If the directory exists, you’re in UEFI mode, which is essential for the next steps.

You then need to connect to the internet, partition your hard drive, format the partitions, and mount the file system. Each step is carried out using specific commands in the terminal. It’s essential to follow the instructions precisely as data loss can occur if these steps are incorrectly executed.

  1. Connect to the Internet: Arch Linux’s installation is network-based, which means you must have an internet connection to download the necessary files. This can be achieved by connecting via Ethernet or Wi-Fi. For Wi-Fi, use the iwctl command and follow the prompts to connect.
  2. Partition the Hard Drive: Partitions can be created using tools like fdisk or parted. For example, to use fdisk, the command would be fdisk /dev/sda (replace sda with your drive name).
  3. Format the Partitions: Once the partitions are created, they must be formatted. For example, to format a partition with an ext4 filesystem, you would use mkfs.ext4 /dev/sda1 (replace sda1 with your partition name).
  4. Mount the File System: After formatting, you need to mount the partitions. Typically, the root partition is mounted to /mnt with the command mount /dev/sda1 /mnt (replace sda1 with your root partition).
Note: In case you've created a separate partition for home or any other directory, they should also be mounted accordingly.
  1. Installation of the Base System: With the pacstrap script, install the base package: pacstrap /mnt base linux linux-firmware. This installs the base system along with the Linux kernel and firmware.
  2. Generate an Fstab File: Generate an fstab file to define how disk partitions, block devices, or remote filesystems should be mounted into the filesystem. This can be done with the genfstab command: genfstab -U /mnt >> /mnt/etc/fstab.
  3. Chroot Into Your New System: Change root into the new system with arch-chroot /mnt. This allows you to work in the newly installed environment.
  4. Set Timezone, Locale, and Other Settings: Various commands are used for these settings, such as ln -sf /usr/share/zoneinfo/Region/City /etc/localtime for time zone, and locale-gen after uncommenting required locales in /etc/locale.gen for locales.
  5. Configure the Network: You’ll need to set a hostname and enable the dhcpcd service for network management.
  6. Install a Bootloader: To be able to boot your Arch Linux system, you’ll need a bootloader. grub is a common choice for many users. Install it using pacman -S grub, and then install it to your hard drive with grub-install --target=i386-pc /dev/sda and grub-mkconfig -o /boot/grub/grub.cfg.

Remember to replace /dev/sda with your own drive.

  1. Set a Root Password: Use the passwd command to set a new password for the root account.

Once you’ve completed all these steps, you should be able to exit the chroot environment and reboot into your new Arch Linux installation.

Section 4: Completing the Arch Linux Installation

After mounting the file system, you can proceed to install the base system onto your hard drive using the ‘pacstrap’ command. Once completed, generate an fstab file, which will define how disk partitions should be mounted.

Next, chroot (change root) into your new system, set your time zone, adjust the hardware clock, and set the locale. Also, you’ll need to configure the network for your new system, install a bootloader, and set a root password.

After completing these configurations, you can exit the chroot environment and reboot your machine. If all steps were correctly followed, you should boot into your new Arch Linux system.

Section 5: Post-Installation Steps

Congratulations! You’ve managed to install Arch Linux on your machine. Post-installation, there are a few additional steps to enhance your Arch Linux experience. You might want to create a regular user account, as working directly with the root account is not recommended.

Additionally, you’ll want to install some essential software. The ‘pacman’ package manager that comes with Arch Linux makes software installation straightforward. A desktop environment or window manager can also be installed if you prefer a graphical user interface.

Remember, Arch Linux is a rolling-release distribution, so ensure to periodically update your system using the ‘pacman -Syu’ command.

June 12, 2023 0 comments
0 FacebookTwitterPinterestEmail
Linux

How to Install Apache on CentOS 8

by pcplanet March 1, 2023
written by pcplanet 3 minutes read

This article will talk about how to instal and run the Apache web server on CentOS 8.

The most popular web server worldwide is Apache HTTP server. It is a powerful, open-source, free, and cross-platform HTTP server that can be expanded with a huge selection of modules.

Installing Apache

The installation of Apache is fairly simple and includes access to the default CentOS repositories.

httpd is the name of the Apache package and service on RHEL-based distributions. Run the following command as root or a user with sudo permissions to install Apache:

sudo yum install httpd

After installation is finished, turn on and launch the Apache service:

sudo systemctl enable httpd
sudo systemctl start httpd

Check the service’s status to ensure that it is active:

sudo systemctl status httpd

The final result should resemble this:

● httpd.service - The Apache HTTP Server
Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)
Active: active (running) since Sat 2022-12-1 15:24:58 UTC; 6s ago
...

Adjusting the Firewall

On Centos 8, FirewallD is the pre-installed firewall program.

Apache creates firewalld service files with pre-set rules for allowing access to HTTP (80) and HTTPS (443) ports during installation.

The required ports will be permanently opened by the following commands:

sudo firewall-cmd --permanent --zone=public --add-service=httpsudo firewall-cmd --permanent --zone=public --add-service=https
sudo firewall-cmd --reload

Managing Apache

What follows is a detailed breakdown of the Apache configuration file structure, as well as recommendations for optimal administration of the Apache web server.

The /etc/httpd directory houses all of Apache’s configuration files.

The httpd.conf file in the /etc/httpd/conf directory is where Apache’s primary settings are stored.

The main Apache configuration file incorporates all.conf-ending configuration files in the /etc/httpd/conf.d subdirectory.

The /etc/httpd/conf.modules.d folder contains configuration files used to load specific Apache modules.

Each Apache vhost file must have a.conf extension and live in the /etc/httpd/conf.d folder. Create as many virtual hosts as you like. When you make a virtual host (vhost) for each domain, you reduce the server’s administration burden.

Establishing and sticking to a consistent naming convention is a good idea. As an illustration, if the domain is mydomain.com, the corresponding configuration file should also be named mydomain.com. conf Apache log files (access log and error log) are located in the /var/log/httpd/ directory. In order to keep track of what went wrong in each vhost, it’s best to keep the access and error logs separate.

You’re free to choose any directory you like as the root directory of your domain. Webroot is most frequently used in the following places:

/home/<user_name>/<site_name>
/var/www/<site_name>
/var/www/html/<site_name>
/opt/<site_name>

Conclusion

Your CentOS 8 server now has Apache installed successfully. Now that you’re prepared, you can use Apache as a web or proxy server to begin deploying your applications.

Similar to how you manage other systemd units, you can manage the Apache service.

Please leave a comment if you have any queries or suggestions.

March 1, 2023 0 comments
1 FacebookTwitterPinterestEmail
LinuxRHEL

How to Install MariaDB on CentOS 8

by pcplanet February 22, 2023
written by pcplanet 2 minutes read

In this tutorial, we will explain how to install and secure MariaDB 10.3 on CentOS 8/Rocky.

MariaDB is a free and open-source relational database management system (RDBMS) that can be used as a drop-in replacement for MySQL. Many people in the community, including some of MySQL’s original creators, work on it.

Installing MariaDB on CentOS 8/Rocky

The latest stable release of MariaDB for CentOS 8/Rocky can be found as version 10.3 in the official repositories.

MariaDB 10.3 for CentOS 8/Rocky can be installed by running the following command as root or a user with sudo privileges:

sudo dnf install @mariadb

Using the @mariadb module, MariaDB server and all required components are set up.

Once everything is set up, you can start the MariaDB service and have it start automatically at boot time by typing:

sudo systemctl enable --now mariadb

In order to ensure that MariaDB is up and running, type:

sudo systemctl status mariadb

The results should demonstrate that the service has been activated:

● mariadb.service - MariaDB 10.3 database server
   Loaded: loaded (/usr/lib/systemd/system/mariadb.service; enabled; vendor preset: disabled)
   Active: active (running) since Sun 2019-12-08 21:05:26 UTC; 15s ago
   ..

Securing MariaDB

Mysql secure installation, a script included in the MariaDB server package, sets the root password and performs several other security-related tasks.

Type the following to activate the script:

sudo mysql_secure_installation

The MariaDB root user requires a password, which you will be prompted to create. After that, the script will request that you delete the test database, disable the anonymous user, and limit root access to the local machine. Every question needs to be answered with a “Y” (yes).

Now that MariaDB is up and running on your CentOS server, you can begin using it.

Connect to the MariaDB Shell

In order to log in to the MariaDB server as the root user, enter:

mysql -u root -p

When prompted, enter the root password to access the MariaDB shell:

Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 18
Server version: 10.3.11-MariaDB MariaDB Server
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [(none)]> 

Conclusion

We’ve covered everything from downloading MariaDB to securing it during installation on CentOS 8/Rocky, plus command line access to the server itself.

It’s time to start making use of your MariaDB server now that you’ve established shell access to it and can begin making new databases and users.

MySQL 8.0 is included with CentOS 8/Rocky. Check out the How to Install MySQL on CentOS 8/Rocky manual if you’d rather set up MySQL than MariaDB. Remember that MariaDB and MySQL cannot coexist on the same server.

Feel free to leave a comment below with any questions, thoughts, or suggestions.

February 22, 2023 0 comments
0 FacebookTwitterPinterestEmail
LinuxRHEL

How to install Python on CentOS 8

by pcplanet February 15, 2023
written by pcplanet 3 minutes read

To help you get Python 3 and Python 2 up and running on CentOS 8/Rocky Linux, we’ve put together this detailed installation guide.

It’s no surprise that Python is a widely used programming language. Python’s simple and straightforward syntax makes it a favorite among both inexperienced and seasoned programmers.

CentOS 8/Rocky Linux is not like other Linux distributions in that Python is not pre-installed.

In case you didn’t know, Python comes in not one but two distinct flavors. In 2020, Python 2 will no longer be supported. Python 3 is the cutting edge of programming today and tomorrow.

To prevent users from being locked into a specific version of Python, RHEL/CentOS 8/Rocky Linux does not include an unversioned system-wide python command by default. As an alternative, it allows the user to select which version of Python they would like to use during setup and execution. The internal Python binary and libraries are used by the system tools like yum.

When we say unversioned system-wide, we mean in the terminal.
Unversioned: python
Versioned: python3, python2

Installing Python 3 on CentOS 8/Rocky Linux

On CentOS 8/Rocky Linux, enter the following command in the terminal as the root or sudo user to install Python 3:

sudo dnf install python3

In order to make sure everything is set up properly, you can check the Python version by typing:

python3 --version

As of this writing, “3.6.x” is the most recent version of Python 3 that can be found in the CentOS repositories:

Python 3.6.8

Additionally, pip will be set up with this command.

In order to use Python 3, you must type python3, and to use pip, you must type pip3.

Whenever possible, use yum or dnf to install the python modules that came with your distribution, as these modules have been validated for use with CentOS 8/Rocky Linux and are guaranteed to work properly. Pip should only be used inside of a sandbox. Using Python Virtual Environments, Python modules can be installed locally for use with a single project, rather than globally. There will be no ripple effects on other Python programs.

Python 3 module package names begin with the prefix “python3.” A typical command to install a module would be:

sudo dnf install python3-xyz

As of writing this guide, the latest major release of the Python is 3.8. To install it, you will have to build it from the source .

Installing Python 2 on CentOS 8/Rocky Linux

Python 2 packages are distributed in the official CentOS 8 and Rocky Linux distribution repositories.

Use this command to set up Python 2:

sudo dnf install python2

Type in the following to ensure the installation went smoothly:

python2 --version

The result should resemble this:

Python 2.7.15

Python 2 can be run by entering python2, and pip can be launched by typing pip2.

Set Default Python Version (Unversioned Python Command)

The unversioned python command and the default version must be created if any existing programs require the presence of the python command in the system’s path.

Using the alternatives program, you can make Python 3 the default unversioned python command on your entire system:

sudo alternatives --set python /usr/bin/python3

When using Python 2, enter:

sudo alternatives --set python /usr/bin/python2

Using the alternatives command, a symbolic link named python will be created and pointed to the version of Python you specify.

Enter python —version into the terminal to see the installed version of Python.

Use one of the preceding commands to alter the setup’s default build. Remove the unversioned python command by entering:

sudo alternatives --auto python

Conclusion

Python is not pre-installed on CentOS 8/Rocky Linux.

Python 2 can be installed with dnf install python2, and Python 3 can be installed with dnf install python3.

If you have any questions or feedback, feel free to comment below.

February 15, 2023 1 comment
0 FacebookTwitterPinterestEmail
LinuxUbuntu

How To Set Up Nginx Server Blocks on Ubuntu 20.04

by pcplanet February 8, 2023
written by pcplanet 3 mins read

We’ll show you how to set up Nginx server blocks (the equivalent of Apache Virtual Hosts) on Ubuntu 20.04.

Multiple websites can be hosted on a single server using Nginx Server Blocks. With Server Blocks, you can do a lot of useful things, such as designating a unique security policy for each website, using unique SSL certificates, and more.

Prerequisites

Before you continue with the tutorial, make sure that you have done the following:

  • Your public server IP is pointed to by a domain name. We’ll employ example.com.
  • By following these guidelines, Nginx is installed.
  • You have access as a user with sudo rights.

Sometimes you’ll see the term “Virtual host” used to describe Server Blocks. The term “virtual host” was coined by Apache.

Create the Directory Structure

A domain’s document root is the directory from which all files for that domain will be served when the domain is accessed by a user’s browser. The document root can be changed to any directory you like.

The following folder hierarchy will be used:

/var/www/
├── domain1.com
│   └── public_html
├── domain2.com
│   └── public_html
├── domain3.com
│   └── public_html

Each domain name that will be hosted on this server will have its own directory under /var/www. We’ll make a public html folder inside each of these directories to store the files for the various sites under the given domain.

Let’s get started by making our domain’s main directory, example.com’s /.

sudo mkdir -p /var/www/example.com/public_html

We will make an index.html file in the root directory of the domain for testing purposes.

Launch your preferred text editor and draft the sample file:

nano /var/www/example.com/public_html/index.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Welcome to example.com</title>
  </head>
  <body>
    <h1>Success! example.com home page!</h1>
  </body>
</html>

By using the sudo command, we can ensure that all new files and directories created by these commands are set to be owned by the root user.

To prevent any permissions issues, you should change the domain document root directory’s ownership to the Nginx user (www-data):

sudo chown -R www-data:www-data /var/www/example.com

Create a Server Block

The Nginx server blocks configuration files on Ubuntu systems are located in the /etc/nginx/sites-available directory and are activated via symbolic links to the /etc/nginx/sites-enabled/ directory.

Prepare the following server block file in your preferred text editor:

nano /etc/nginx/sites-available/example.com
server {
    listen 80;
    listen [::]:80;

    root /var/www/example.com/public_html;

    index index.html;

    server_name example.com www.example.com;

    access_log /var/log/nginx/example.com.access.log;
    error_log /var/log/nginx/example.com.error.log;

    location / {
        try_files $uri $uri/ =404;
    }
}

The configuration file can have any name you like, but the domain name is the most common and logical choice.

It is necessary to create a symbolic link from the new server block file to the sites-enabled directory, which is read by Nginx at startup, in order to activate the file.

sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/

Ensure proper syntax when setting up Nginx:

sudo nginx -t

The expected result should look like this:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

To make the modifications take effect, restart the Nginx service:

sudo systemctl restart nginx

Finally, open http://example.com in your preferred browser, and if everything is in order, you should see something like this:

Conclusion

You now know how to configure a server block in Nginx so that a single Ubuntu server can host multiple domains. If you need more server blocks for your domains, just follow the same steps we showed you above.

This tutorial will show you how to install a free LetsEncrypt SSL certificate on your website.

Secure Nginx with Let’s Encrypt on Ubuntu 20.04

Please share your experiences in the comments if you are having difficulties.

February 8, 2023 0 comments
2 FacebookTwitterPinterestEmail
LinuxUbuntu

How to Install Nginx on Ubuntu 20.04

by pcplanet February 1, 2023
written by pcplanet 3 mins read

Learn How to Install Nginx on Ubuntu 20.04 with the help of this tutorial.

Some of the busiest websites on the Internet rely on Nginx, an open-source, high-performance HTTP and reverse proxy server pronounced “engine x.” Besides serving as a reverse proxy for HTTP and non-HTTP servers, it can also act as a load balancer, content cache, and standalone web server.

Nginx has a smaller memory footprint per connection and can handle a much larger number of simultaneous connections than Apache.

Prerequisites

  • Access to a Sudo User
  • Ubuntu server 18.04 or 20.04 or 22.04

Installing Nginx

In Ubuntu, Nginx can be found in the official packages. The following commands must be entered in order to set it up:

sudo apt update
sudo apt install nginx

After setup is complete, the Nginx service will immediately begin running. It can be checked by using:

sudo systemctl status nginx

The final result might look like this:

● nginx.service - A high performance web server and a reverse proxy server
     Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
     Active: active (running) since Sat 2020-05-02 20:25:43 UTC; 13s ago
...

You should now see Nginx in your Ubuntu server’s list of programs. The Nginx service can be controlled just like any other systemd component.

Configuring firewall

Once Nginx has been installed and is running, the firewall must be set up to permit traffic on the HTTP (80) and HTTPS (443) ports. Using UFW, you can do so by activating the “Nginx Full” profile, which includes the necessary rules for both ports:

sudo ufw allow 'Nginx Full'

In order to check the current status, enter:

sudo ufw status

You can expect something like this from the output:

Status: active

To                         Action      From
--                         ------      ----
22/tcp                     ALLOW       Anywhere
Nginx Full                 ALLOW       Anywhere
22/tcp (v6)                ALLOW       Anywhere (v6)
Nginx Full (v6)            ALLOW       Anywhere (v6)
Test the Installation

Open “http://YOUR IP” in your preferred browser to check out your new Nginx installation, and you should see the default Nginx landing page, as depicted in the image below:

Nginx Configuration File’s Structure and Best Practices

The settings for Nginx are all in the /etc/nginx folder.

The main file for configuring Nginx is /etc/nginx/nginx.conf.

If you want to make it easier to manage your Nginx configuration, you should make a separate file for each domain. You can use as many server block files as you need.

The block files for a Nginx server are in the /etc/nginx/sites-available folder. If the files in this directory aren’t also linked to /etc/nginx/sites-enabled, Nginx won’t use them for configuration.

A symlink must be used to move the configuration file sites from the sites-available directory to the sites-enabled directory (a pointer).

It’s best to use standard names when naming things. In this case, /etc/nginx/sites-available/mydomain.com.conf would be the location of the configuration file for the mydomain.com domain.

In the /etc/nginx/snippets directory, you can find a list of configuration snippets that can be added to the server block files. You can turn configuration chunks that you use often into snippets and then add the snippet file to the server blocks.

Nginx log files (access.log and error.log) are located in the /var/log/nginx directory. For each server partition, it’s best to keep a separate set of access and error log files.

The “document root” of a domain can be a folder anywhere you like. Webroot is most often found in these places:

/home/<user_name>/<site_name>
/var/www/<site_name>
/var/www/html/<site_name>
/opt/<site_name>

Conclusion

We’ve demonstrated how to set up Nginx on Ubuntu 20.04. Nginx is now ready for use as a web or proxy server, and you can begin deploying your applications.

We welcome your thoughts and questions in the form of comments.

February 1, 2023 0 comments
0 FacebookTwitterPinterestEmail
LinuxUbuntu

How to Install PHP 8 on Ubuntu

by pcplanet January 25, 2023
written by pcplanet 3 mins read

Introduction

WARNING: PHP 8 End of Life Alert

Before proceeding with any system updates or software deployments, it’s crucial to address a significant change in your technology stack. PHP 8 has reached its End of Life (EOL), meaning it will no longer receive security updates or support. Using outdated software can introduce vulnerabilities and impact the security and functionality of your applications.

https://www.php.net/supported-versions.php

Installing PHP 8 on Ubuntu 20.04 and combining it with Nginx and Apache is covered in detail here.

Among server-side languages, PHP has the most widespread use. PHP is used to create a wide variety of content management systems and frameworks.

The one of the current stable version of PHP is 8.0. It adds several new features, including named arguments, a JIT compiler, union types, a match expression, and more, as well as a number of breaking changes and improved efficiency.

In the time of this writing, PHP 7.4 may be found in the default Ubuntu 20.04 repository. Now we’ll use the ondrej/php PPA repository to install PHP.

Make sure your software is compatible with PHP 8 before updating or installing it.

All Ubuntu-based distributions, including Kubuntu, Linux Mint, and Elementary OS, follow the same procedures as described here, not only Ubuntu 18.04.

Enabling PHP Repository

A Debian developer by the name of Ondej Sur runs a repository that contains a number of different PHP distributions. In order to activate the repository, type:

Bash
sudo apt install software-properties-common
sudo add-apt-repository ppa:ondrej/php

Once the PPA is enabled, you can install PHP 8.

Installing PHP 8.0 with Apache

PHP may be used as either an Apache module or PHP-FPM while the Apache web server is in use.

Install PHP as Apache Module

Installation of PHP as an Apache module is a simple process:

Bash
sudo apt update
sudo apt install php8.0 libapache2-mod-php8.0

After the packages have been installed, Apache must be restarted so that the PHP module can be loaded.

Bash
sudo systemctl restart apache2

Configure Apache with PHP-FPM

Php-FPM is a PHP-specific FastCGI process manager. Execute the command below to install the required packages:

Bash
sudo apt update
Bash
sudo apt install php8.0-fpm libapache2-mod-fcgid

Apache is not configured to use PHP-FPM by default. To enable it, run:

Bash
sudo a2enmod proxy_fcgi setenvif
sudo a2enconf php8.0-fpm

To apply the modifications, restart Apache:

Bash
systemctl restart apache2

Installing PHP 8.0 with Nginx

Nginx does not have built-in support for parsing PHP files. To handle PHP files with Nginx, you need to install PHP-FPM (FastCGI Process Manager).

To install PHP and PHP-FPM packages, run the following commands:

Bash
sudo apt update
sudo apt install php8.0-fpm

After the installation is complete, the PHP-FPM service will automatically start running. You can check the status of the service by executing:

Bash
systemctl status php8.0-fpm

You should see output similar to:

Bash
● php8.0-fpm.service - The PHP 8.0 FastCGI Process Manager
     Loaded: loaded (/lib/systemd/system/php8.0-fpm.service; enabled; vendor preset:enabled)
     Active: active (running) since Thu 2020-12-03 16:10:47 UTC; 6s ago

To configure Nginx to handle PHP files, you need to modify the Nginx server block. Open the server block configuration file and add the following lines inside the server block:

Nginx
server {
    # . . . other code
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php8.0-fpm.sock;
    }
}

This configuration tells Nginx to pass PHP files to the PHP-FPM process for execution. The location block matches any request ending with .php and passes it to the PHP-FPM socket file (/run/php/php8.0-fpm.sock).

After making the changes, save the configuration file and restart the Nginx service for the new configuration to take effect:

Bash
sudo systemctl restart nginx

Your Nginx server is now set up to handle PHP files using PHP-FPM.

Installing PHP Extensions

PHP extensions are libraries that enhance PHP’s core functionality, enabling features such as database interaction, image manipulation, and more. These extensions can be easily installed using the apt package manager on Debian-based systems, including Ubuntu.

To install a PHP extension, run the following command:

Bash
sudo apt install php8.0-[extension-name]

For instance, to install the MySQL and GD extensions, you would execute:

Bash
sudo apt install php8.0-mysql php8.0-gd

Efficient Installation of Multiple Extensions

To optimize the process of installing multiple PHP extensions, consider these approaches:

  1. Single Command Installation: You can install multiple extensions simultaneously by specifying them in a single apt command:
Bash
sudo apt install php8.0-mysql php8.0-gd php8.0-curl
  1. Brace Expansion: This technique utilizes brace expansion to minimize typing when installing several extensions. It is particularly handy for quickly adding multiple extensions:
Bash
sudo apt install php8.0-{mysql,gd,curl}

This command expands to install the MySQL, GD, and cURL extensions for PHP 8.0.

Restart Your Web Server

After installing new PHP extensions, it’s crucial to restart your web server or PHP FastCGI Process Manager (FPM) to ensure the extensions are properly loaded.

  • For Apache:
Bash
sudo systemctl restart apache2
  • For PHP-FPM:
Bash
sudo systemctl restart php8.0-fpm

Restarting your server or PHP service activates the newly installed extensions, making them available for use in your PHP applications.

Conclusion

It doesn’t take much effort to set up PHP 8 on a server running Ubuntu 20.04. Installing PHP 8 with apt is as simple as enabling the “ondrej/php” repository.

Please share your thoughts and questions by posting a comment below.

January 25, 2023 0 comments
1 FacebookTwitterPinterestEmail
Newer Posts
Older Posts

Recent Posts

  • Creating Custom Nginx Rules for Different Subdomains in DirectAdmin
  • Nginx Reverse Proxy for Nextcloud: A Guide
  • How to Reverse Proxy in DirectAdmin with Nginx_Apache
  • How to install Python 3.10 on RHEL
  • How to install Python 3.10 on Ubuntu 20.04

Recent Comments

  1. Daron Buesgens on Introduction to PHP Server-Side Scripting Language
  2. Tim Slosek on How to install Python on CentOS 8
  3. аналитика леонида малолетова on 15,000 WordPress Sites hacked with Malicious Redirects
  4. 076 on Websites Posing as MSI Afterburner That Spread CoinMiner
  • Home
  • Tools
    • CHMOD Calculator
    • Subnet Calculator
  • Linux Guides & Tutorials
    • Beginner Guides
    • Linux Installation Tutorials
    • Command Line Tutorials
    • Server Administration Guides
    • Security Tutorials
    • Database Tutorials
    • Open-Source Software
      • Nextcloud Guides
      • Apache
    • Operating Systems
      • Ubuntu
      • RHEL/Rocky/Alma
  • Ransomware News
  • Cybersecurity Laws and Regulations

Recent Posts

Creating Custom Nginx Rules for Different Subdomains in DirectAdmin
Nginx Reverse Proxy for Nextcloud: A Guide
How to Reverse Proxy in DirectAdmin with Nginx_Apache
How to install Python 3.10 on RHEL

Most Viewed

Best Linux distribution (distros) in 2022
15,000 WordPress Sites hacked with Malicious Redirects
How to Install Python 3.9 on Ubuntu 18.04
6aabc923d85895a8823d81efa5e551d7
PCPlanet – Tech Blogs | Information
  • Home