Saturday, February 17, 2024

Mastering Cron Jobs in Linux: A Comprehensive Guide with Examples

Introduction:

Cron jobs are an indispensable tool in the world of system administration and automation. They allow users to schedule tasks to run periodically at fixed intervals, making them essential for automating routine tasks, such as backups, log rotations, and system maintenance. In this blog post, we'll delve into the world of cron jobs, exploring what they are, how they work, and providing practical examples to help you harness their power effectively.


What are Cron Jobs?

Cron is a time-based job scheduler in Unix-like operating systems, including Linux and macOS. It enables users to schedule tasks (referred to as cron jobs) to run periodically at specified times or intervals. These tasks can range from simple commands to complex scripts and programs.


Syntax and Components:

Cron jobs are defined using a specific syntax that consists of five fields:

 

* * * * * command_to_execute

|   |  |  |  |

|   |  |  | +----- Day of week (0 - 7) (Sunday is 0 or 7)

|   |  | +------- Month (1 - 12)

|   |  +--------- Day of month (1 - 31)

|   +----------- Hour (0 - 23)

+------------- Minute (0 - 59)



Syntax Examples:

1. Run a Script Every Hour:

0 * * * * /path/to/script.sh

This cron job executes the script `/path/to/script.sh` every hour, on the hour.


2. Run a Command Daily at Midnight:

0 0 * * * command_to_run

This cron job executes `command_to_run` every day at midnight (00:00).

3. Run a Task Every 15 Minutes:

*/15 * * * * command_to_execute

This cron job runs `command_to_execute` every 15 minutes.

4. Run a Task Every Weekday at 8:00 AM:

0 8 * * 1-5 command_to_execute

This cron job executes `command_to_execute` at 8:00 AM from Monday to Friday.

5. Run a Job Monthly on the 1st at Noon:

0 12 1 * * command_to_execute

This cron job runs `command_to_execute` at noon on the 1st day of every month.


Command Examples:


1. Open Cron Configuration File:

   Start by editing the cron configuration file. Use your preferred text editor, such as nano or vim:

#sudo vim /etc/crontab

or

# crontab -e 

or

# crontab -e -u harry
This command you can use to set  the cron jobs for the harry user.


2. Adding a Cron Job:

   Suppose you want to schedule a script to run every day at 2:00 AM. You would add a line like this to the cron configuration file:

   0 2 * * * /path/to/your/script.sh

   Replace `/path/to/your/script.sh` with the actual path to your script.


3. Save and Exit:

   After adding your cron job, save the file and exit the text editor.


4 Verify the Cron Job:

   

To ensure that the cron job was added successfully, you can list the current cron jobs using the following command:

  sudo crontab -l

   This command will display all the cron jobs configured for the root user.


  sudo crontab -l -u harry

   This command will display all the cron jobs configured for the harry user.


5. Delete Cron jobs:

  sudo crontab -r -u harry

   This command will remove all the cron jobs configured for the harry user.


6. Restart the Cron Service:

   It's a good practice to restart the cron service to apply any changes made to the cron configuration file:

#sudo systemctl restart crond

7. Viewing Logs (Optional):

   If your cron job is not running as expected, you can check the cron logs to troubleshoot the issue. The cron logs are typically located at `/var/log/cron`.

#tail -f  /var/log/cron

That's it! You've now successfully set up a cron job on Linux. Your script will execute at the specified time according to the cron schedule you've configured.

Conclusion:

Cron jobs are an invaluable tool for automating repetitive tasks on Unix-like systems. By understanding the syntax and components of cron jobs and exploring practical examples, you can effectively leverage them to streamline your workflow and improve system efficiency. Experiment with different cron job configurations to tailor automation solutions to your specific needs and maximize productivity. With mastery of cron jobs, you'll unlock a powerful arsenal for automating tasks and managing your system with precision and ease.

A Step-by-Step Guide to Installing MongoDB on Oracle Linux 8 | How to install MongoDB on RedHat 8/ Rocky Linux 8

Introduction:
MongoDB is a powerful, open-source NoSQL database that provides flexibility and scalability for modern applications. In this guide, we'll walk through the process of installing MongoDB on Oracle Linux 8 and configuring it to ensure security best practices are followed.


Step 1: Prerequisites

Before we begin, make sure you have:

1. An instance of Oracle Linux 8 set up and running.

2. Root or sudo access to the server.


Step 2 – Install  MongoDB 

1. Open a terminal window on your Oracle Linux 8 server and update it.

#yum update

  After patch update make sure you reboot the server 


2. Add the MongoDB repository to your system:

#vim /etc/yum.repos.d/mongodb-org-4.4.repo

Add the following contents:

[mongodb-org-4.4]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/4.4/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-4.4.asc

Save and close the file once you are done.


3. Install MongoDB:

# sudo dnf install -y mongodb-org

4. Start the MongoDB service and enable it to start on boot:

# sudo systemctl start mongod

# sudo systemctl enable mongod

mongod --version

Step 3: Configure MongoDB

1. Open the MongoDB configuration file:

# sudo vim /etc/mongod.conf

2. Bind MongoDB to localhost or IP:

bindIp: 127.0.0.1

3. Enable authentication:

security:

  authorization: enabled


4. Save and close the file.


Step 4: Secure MongoDB

1. Create an administrative user:

First, connect to the MongoDB instance with the command 

mongo

Once you are connected, create a database named admin using the following command:

use admin

Next, create an admin user and set a password with the following command:

db.createUser(
  {
    user: "admin",
    pwd: passwordPrompt(),
    roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]

  }

)


You will be asked to set a password.


2. Exit the MongoDB shell:

exit

3. Restart MongoDB to apply the changes:

sudo systemctl restart mongod

Step 5: Test MongoDB Authentication

1. Open the MongoDB shell as the administrative user:

# mongo -u admin -p --authenticationDatabase admin

or 

#mongo --port 27017 --authenticationDatabase admin -u admin -p



2. You'll be prompted to enter the password for the admin user.

3. Once logged in, you can create additional users and databases as needed.


Step 6 – Create a Database in MongoDB

In this section, we will show you how to interact with the MongoDB database.

To create a database named testdb, run the following command:

use testdb

Next, add some data to the testdb database using the following command:

db.person.insertOne(
  { "Nirmal Singh" : "20",
   "Tom " : "18",
   "Harry" : "25"
  }
)

You can now list available databases using the following command db prompt:

db

You will get the following output:

testdb

To show documents in your database, run the following command:

show collections

You will get the following output:

person

To show the contents of your database collection, run the following command:

db.person.find()

You will get the output for all records:

To switch the database to admin, use the following command:

use admin

To list all users, run the following command:

db.getUsers()

You will get a list of all users in the following output formate:

[
	{
		"_id" : "admin.admin",
		"userId" : UUID("504b73he-aaed-4ad9-bb60-4fb8df334709"),
		"user" : "admin",
		"db" : "admin",
		"roles" : [
			{
				"role" : "userAdminAnyDatabase",
				"db" : "admin"
			},
			{
				"role" : "readWriteAnyDatabase",
				"db" : "admin"
			}
		],
		"mechanisms" : [
			"SCRAM-SHA-1",
			"SCRAM-SHA-256"
		]
	}
]


Step 7: Firewall Configuration (Optional)

If you have a firewall enabled on your server, you may need to open the MongoDB port (default is 27017) to allow external connections. Use the following command to open the port:


sudo firewall-cmd --zone=public --add-port=27017/tcp --permanent

# sudo firewall-cmd --reload


Conclusion:

Congratulations! You've successfully installed MongoDB on Oracle Linux 8 and configured it to ensure security. By following these steps, you can confidently deploy MongoDB for your applications while adhering to best practices for database security. Remember to regularly update MongoDB and review your security measures to protect your data effectively.

Mastering Cron Jobs in Linux: A Comprehensive Guide with Examples

Introduction: Cron jobs are an indispensable tool in the world of system administration and automation. They allow users to schedule tasks t...