System files on a server are often targets for unauthorized changes, which can result in system vulnerabilities or instability. For system administrators, it is crucial to have the ability to monitor changes in these files and respond to them promptly. One of the tools that facilitates this on the CentOS 7 operating system is inotify, a specific implementation in the Linux kernel for file system monitoring.
Prerequisites
Before you begin, ensure that you have:
- Access to a CentOS 7 server with root privileges or a user with sudo permission.
- Installed basic development tools (Development Tools).
Installing Required Packages
The first step is to install inotify-tools, which contain tools for working with inotify. To install, run the following command in the terminal:
sudo yum install inotify-tools
Configuring inotify
inotify operates at the kernel level, which means it is extremely efficient in terms of performance. However, by default, it has a limit on the number of watchable files, which may be too low for some applications. To increase this limit, open the /etc/sysctl.conf
file and add the following lines:
fs.inotify.max_user_watches=524288
fs.inotify.max_user_instances=256
After adding the lines, apply the changes using the command:
sudo sysctl -p
Using inotify
The basic usage of inotify is to monitor changes in files or directories. To begin, let's create a script monitor.sh
that will monitor changes in a specific directory and its subdirectories. Open a new file using your favorite text editor and insert the following script:
#!/bin/bash
DIRECTORY_TO_MONITOR="/var/www/HTML"
EVENTS="create,delete,modify,move"
inotifywait -m -r -e "$EVENTS" --format '%w%f %e %T' --timefmt '%Y-%m-%d %H:%M:%S' "$DIRECTORY_TO_MONITOR" | while read FILE
do
echo "Detected $FILE"
# Here you can add additional actions, such as sending email alerts
done
Make the script executable using the command:
chmod +x monitor.sh
And execute it:
./monitor.sh
The script will now continuously monitor file creations, deletions, modifications, and movements in the specified directory, displaying information about each detected event in real-time.
Automation and Further Steps
For long-term monitoring, you can run the script in the background or utilize the system's facilities such as systemd
or cron
to automatically start it after system reboot.
inotify offers many configuration and usage possibilities. For example, you can monitor specific types of files, exclude certain directories from monitoring, or modify actions taken upon detecting changes. For more detailed information on inotify and its capabilities, I recommend studying the official documentation and usage examples.