How to Make a Tool Like Molly-Guard Using a Bash Script?

The previous article explained how the Molly-Guard tool can protect Linux servers from accidental reboot or shutdown commands. Unfortunately, this tool is only available on Debian/Ubuntu distros and their derivatives, while sysadmins generally have many Linux servers from various distros.

 

Problem

How to make a tool like Molly-Guard using a bash script?

 

Solution

To create a tool like Molly-Guard, you can use a bash script, and this script has been tested on Ubuntu Server 24.04, RockyLinux9, and OpenSUSE 15 distros. And this script should be applied throughout the Linux distro to replace the Molly Guard tool. Here are the steps:

1. Check the paths

First, check where the reboot, shutdown, poweroff, and halt commands are located on the Linux server by running the command below:

whereis -b reboot
whereis -b shutdown
whereis -b poweroff
whereis -b halt

Check the paths in RockyLinux

 

As far as I know, Linux distributions such as RockyLinux and Ubuntu only provide one binary file for each command for the reboot, shutdown, poweroff, or halt command, usually in the folder /usr /sbin. However, on certain distros, for example, the OpenSUSE distro, when you run the command above, the result will be as shown in the image below:

Check the paths in OpenSUSE

 

From the image above, you can see that 2 files represent each of these commands. Because this article uses the commands in the /usr/sbin folder, you can rename the commands in the /sbin folder using the commands below:

mv /sbin/reboot /sbin/reboot_backup 
mv /sbin/shutdown /sbin/shutdown_backup
mv /sbin/poweroff /sbin/poweroff_backup
mv /sbin/halt /sbin/halt_backup

Rename the file

 

2. Create a bash script

Copy the bash script below into the /usr/local/bin/ folder and give it a molly-guard-costume.sh name:

#!/usr/bin/env bash

# molly-guard-custome.sh: Prevent accidental reboot or shutdown like molly-guard tool

##########################################################################################
# The functions

check_hostname_reboot() {
# Compare the user input with the actual hostname
if [ "$USER_INPUT" == "$ACTUAL_HOSTNAME" ]; then
        echo "Hostname confirmed."
        echo
        sleep 1
        echo "Proceeding with the command..."
        echo
        sleep 1
        echo "The system will reboot now!"
        echo
        sleep 1
        /usr/sbin/reboot_server 
else
        echo "Hostname mismatch. Aborting the reboot operation."
        exit 1
fi
}

check_hostname_halt() {
# Compare the user input with the actual hostname
if [ "$USER_INPUT" == "$ACTUAL_HOSTNAME" ]; then
        echo "Hostname confirmed."
        echo
        sleep 1
        echo "Proceeding with the command..."
        echo
        sleep 1
        /usr/sbin/halt_server 
else
        echo "Hostname mismatch. Aborting the halt operation."
        exit 1
fi
}

check_hostname_poweroff() {
# Compare the user input with the actual hostname
if [ "$USER_INPUT" == "$ACTUAL_HOSTNAME" ]; then
        echo "Hostname confirmed."
        echo
        sleep 1
        echo "Proceeding with the command..."
        echo
        sleep 1
        echo "The system will reboot now!"
        echo
        sleep 1
        /usr/sbin/poweroff_server 
else
        echo "Hostname mismatch. Aborting the poweroff operation."
        exit 1
fi
}

check_hostname_shutdown() {
# Compare the user input with the actual hostname
if [ "$USER_INPUT" == "$ACTUAL_HOSTNAME" ]; then
        echo "Hostname confirmed."
        echo
        sleep 1
        echo "Proceeding with the command..."
        echo
        sleep 1
        echo "The system will reboot now!"
        echo
        sleep 1
        /usr/sbin/shutdown_server 
else
        echo "Hostname mismatch. Aborting the shutdown operation."
        exit 1
fi
}

##########################################################################################

# Get the actual system hostname
ACTUAL_HOSTNAME=$(hostname)

# Ask the user to input the hostname
echo "Please confirm the hostname to proceed it."
read -p "Enter the hostname: " USER_INPUT

# Check the command
ps aux | grep reboot > /tmp/reboot.txt
ps aux | grep halt > /tmp/halt.txt
ps aux | grep poweroff > /tmp/poweroff.txt
ps aux | grep shutdown > /tmp/shutdown.txt

reboot_size=`ls -al /tmp/reboot.txt | awk '{print $5}'`
halt_size=`ls -al /tmp/halt.txt | awk '{print $5}'`
poweroff_size=`ls -al /tmp/poweroff.txt | awk '{print $5}'`
shutdown_size=`ls -al /tmp/shutdown.txt | awk '{print $5}'`

# Compare the command

if [ $reboot_size -gt 90 ];
then
        rm -f /tmp/reboot.txt /tmp/halt.txt /tmp/poweroff.txt /tmp/shutdown.txt
        check_hostname_reboot
elif [ $shutdown_size -gt 90 ];
then
        rm -f /tmp/reboot.txt /tmp/halt.txt /tmp/poweroff.txt /tmp/shutdown.txt
        check_hostname_shutdown
elif [ $poweroff_size -gt 90 ];
then
        rm -f /tmp/reboot.txt /tmp/halt.txt /tmp/poweroff.txt /tmp/shutdown.txt
        check_hostname_poweroff
elif [ $halt_size -gt 90 ];
then
        rm -f /tmp/reboot.txt /tmp/halt.txt /tmp/poweroff.txt /tmp/shutdown.txt
        check_hostname_halt
fi

 

Then run the command below so that it can be run:

chmod +x /usr/local/bin/molly-guard-costume.sh

 

3. Copy the commands

Use the commands below to copy the commands :

file_path=$(whereis -b "reboot" | cut -d ' ' -f 2);sudo cp $file_path ${file_path}_server > /dev/null 2>&1
file_path=$(whereis -b "shutdown" | cut -d ' ' -f 2);sudo cp $file_path ${file_path}_server > /dev/null 2>&1
file_path=$(whereis -b "poweroff" | cut -d ' ' -f 2);sudo cp $file_path ${file_path}_server > /dev/null 2>&1
file_path=$(whereis -b "halt" | cut -d ' ' -f 2);sudo cp $file_path ${file_path}_server > /dev/null 2>&1

Copy the commands

 

To see the result, type the command below:

ls -al /usr/sbin/ | grep server

Link the script to the command

 

4. Link the script to the commands

Then, link the bash script to the commands by running the command below:

ln -sf /usr/local/bin/molly-guard-costume.sh /usr/sbin/reboot
ln -sf /usr/local/bin/molly-guard-costume.sh /usr/sbin/shutdown
ln -sf /usr/local/bin/molly-guard-costume.sh /usr/sbin/poweroff
ln -sf /usr/local/bin/molly-guard-costume.sh /usr/sbin/halt

The result of copying the command

 

To see the results, type the command below:

ls -al /usr/sbin/ | grep molly

The result of linking the script to the commands

 

5. Test the result

Now, try to do the reboot command and write the wrong hostname, and your Linux server shouldn’t reboot. However, try to write the correct hostname, then your Linux server should be rebooted, like in the image below:

Test the results

 

You should get the same results when running other commands such as poweroff, shutdown, and halt.

 

Note

Unlike the Molly-Guard tool, this script will continue to work even though you run the reboot or shutdown command without an SSH connection or directly connect the keyboard to the Linux server.

 

References

unix.bris.ac.uk
stackoverflow.com
geeksforgeeks.org




How to Protect the Linux Server From an Accidental Reboot?

As a Sysadmin, accessing a Linux server is a normal daily activity. But sometimes we accidentally make mistakes rebooting or shutting down the production server, causing the server to be inaccessible. Therefore, we need a tool to confirm if someone reboots or shuts down a Linux server.

 

Problem

How to protect the Linux server from an accidental reboot or shutdown?

 

Solution

In the Debian/Ubuntu distribution, the molly-guard tool can be used to protect the Linux server from an accidental reboot or shutdown. Use the two commands below to install molly-guard:

sudo apt update
sudo apt-get install molly-guard

 

After that, try to reboot the server, and there should be a notification like the image below:

A notification appears when trying to reboot the server

 

Someone who wants to reboot the server must write the server’s hostname. If the nameserver does not match the hostname on the server, the reboot process will not be continued, but if it matches the hostname on the server, the reboot process will be continued.

protect the Linux server from an accidental reboot
Try to reboot the server

 

This is very useful if the sysadmin accidentally types the reboot command on the server. However, this tool not only protects the server from the reboot command, but also other commands such as the poweroff, shutdown, coldreboot, pm-hibernate, pm-suspend, and pm-suspend-hybrid commands.

protect the Linux server from an accidental reboot
Try to turn off the server

 

Note

Keep in mind that this molly-guard tool can only work in the Debian/Ubuntu distribution and its derivatives, and this tool only works on SSH connections. If you access the Linux server without an SSH connection, for example, by directly connecting the keyboard to the Linux server, this tool will not work, so if you run the reboot command, the Linux server will immediately reboot.

 

References

manpages.ubuntu.com
launchpad.net
techbits.io




How to Change the Color of Comments in the vi Application?

By default, if you open the vi application on Linux (especially using PuTTY), the color for comments is blue. However, sometimes this makes it very difficult for me to read the comments, especially if the background color of the terminal is black.

 

Problem

How to change the color of comments in the vi application?

 

Solution

Below is an image of a /etc/crontab file opened using Putty:

Comment color in the vi application

 

For me, it’s very difficult to read the comments in the Linux file if they’re blue like in the image above. So, if you want to change the color of comments in the vi application, for example, if you want to change the color of comments to yellow, then open the .vimrc file by:

vi ~/.vimrc

 

Type the script below into the file:

highlight Comment ctermfg=yellow

 

After that, open the file using the vi application, and the comments on the file should change to yellow as in the image below:

change the color of comments in the vi
Comment color after configuration in the vi application

 

You can see that the comment color is changed to yellow after you configure the .vimrc file.

Info
Please note that the steps above only change per user. If you want all users to change the comment color to yellow then place the above command in the /etc/vim/vimrc.local file.

 

Note

Currently, the vi application can support up to 256 colors that can be used in the vi application. So if you want to use more colors supported by the vi application, in the .vimrc file type the script below:

set t_Co=256

 

Then you can choose the colors on this page, for example, you want to use purple for comments, then enter the script below in the .vimrc file:

set t_Co=256
highlight Comment ctermfg=93

 

Then the comments in the vi/vim application should be purple as in the image below:

change the color of comments in the vi
Change the color of comments in the vi

 

References

spinspire.com
linode.com




How to Change Crontab Using a Bash Script?

Crontab, which stands for cron table, is used to run one or more scripts in Linux based on a specific time. Usually, if you want to change something in the crontab, you use the crontab -e command and then change the crontab. But I want to change crontab using a shell script.

 

Problem

How to change crontab using a bash script?

 

Solution

I create a bash script to execute something on my Linux server, and in my script, I want to change the crontab so the script will add, change, or remove the script in the crontab. Here are ways to change crontab using a script:

1. Add a script in crontab

For example, if you want to add a random.sh script which is in the /root/scripts folder in crontab and will run every 5 minutes, then use the command below:

(crontab -l 2>/dev/null || true; echo "*/5 * * * *		/root/scripts/random.sh") | crontab -

Add a script to the crontab

 

Or if you want to add the script to the crontab in another form of writing, then you can use the command below:

(crontab -l 2>/dev/null || true; echo "*/5 * * * *             cd /root/scripts;./random.sh") | crontab -

Another method to add the script to the crontab

 

2. Change the script in crontab

If you want to change the file in crontab to once every 10 minutes (previously every 5 minutes) for the random.sh script in the /root/scripts folder, then use the command below:

crontab -l | sed 's/\*\/5 \* \* \* \*                \/root\/scripts\/random.sh/\*\/10 \* \* \* \*                \/root\/scripts\/random.sh/g' | crontab -

change crontab using a script

 

Or, you can execute the command below if your script uses another form of writing in crontab:

crontab -l | sed 's/\*\/5 \* \* \* \*             cd\ \/root\/scripts\;\.\/random.sh/\*\/10 \* \* \* \*             cd\ \/root\/scripts\;\.\/random.sh/g' | crontab -

Change the script using another form of writing in Crontab using a script

 

3. Disable and enable the script

If you want to disable the random.sh script in crontab, then use the command below:

crontab -l | sed 's/\*\/10 \* \* \* \*             cd\ \/root\/scripts\;\.\/random.sh/\#\*\/10 \* \* \* \*             cd\ \/root\/scripts\;\.\/random.sh/g' | crontab -

change crontab using a bash script
Disable the script in the crontab

 

But if you want to enable it, use the command below:

crontab -l | sed 's/\#\*\/10 \* \* \* \*             cd\ \/root\/scripts\;\.\/random.sh/\*\/10 \* \* \* \*             cd\ \/root\/scripts\;\.\/random.sh/g' | crontab -

change crontab using a bash script
Enable the script in the crontab

 

4. Deleting the script in crontab

Use the command below if you want to delete the random.sh file in crontab:

crontab -l | sed '/\*\/5 \* \* \* \*         \/root\/scripts\/random.sh/d' | crontab -

change crontab using a bash script
Delete the script in the crontab

 

Or, you can execute the command below if your script uses another form of writing in crontab:

crontab -l | sed '/\*\/5 \* \* \* \*             cd\ \/root\/scripts\;\.\/random.sh/d' | crontab -

change crontab using a bash script
Delete the script in crontab using another form

 

Note

You have to pay attention to whether the script in the crontab uses spaces or tabs because it greatly affects whether the script that you run can change something in the crontab or not. You have to put a backslash(\) if you want to change or delete your script in crontab that uses symbols like an asterisk(*), forward slash(/), hash(#), space, and so on.

 

References

techtarget.com
stackoverflow.com
webopedia.com




How to Move the Partition to a New Partition in the Linux Server?

If you install a Linux server, you will usually install it with only one partition and not separate the other partitions. Problems will arise if one of these partitions uses a large enough hard disk, resulting in you running out of HDD space on your Linux server.

 

Problem

How to move the partition to a new partition in the Linux server?

 

Solution

In this article, I use the Ubuntu Server OS, and this article should be applied to any Linux distribution. Currently, the condition of the hard disk on my Ubuntu server is like the image below:

Condition of the hard disk in my Ubuntu server

 

From the image above, the root partition only has a free HDD of 9 percent. After I checked, it turned out that the cause was the /var partition, which took up a lot of hard disk so I want to move the /var partition to the new partition.

Check the largest partition size

 

Here are the steps to move the partition to a new partition in the Linux Server:

Info
The steps in this article will make your Linux server enter maintenance mode which means that the Linux server cannot be accessed from anywhere results in the application or database that may be in the Linux server also inaccessible. So discuss first with your boss if you want to do the steps in this article

 

1. Add a new hard drive

I insert a new 10 GB HDD into my Linux server. After that, I check if the new HDD is detected by Linux using the command:

fdisk -l

Check the new HDD in the Linux server

 

From the image above, it can be seen that the new HDD was detected by Linux with a partition in sdb.

 

2. Create a new partition

Run the command below to create a new partition in Linux (Adjust to the hard disk partition detected on your Linux server after typing the fdisk -l command):

fdisk /dev/sdb

 

Press the n and p keys, then the number ,1 and enter 2x, then press the w button as seen in the image below:

Create a new partition in the new HDD

 

Then create a filesystem from the new HDD, and I want to use ext4 for the filesystem of the new HDD using the command:

mkfs.ext4 /dev/sdb1

Create a filesystem in the partition of the new HDD

 

3. Create and mount a new folder

After that, create a new folder using the command:

mkdir /mnt/newvar

 

Then, mount the new partition to the new folder using the command:

mount /dev/sdb1 /mnt/newvar

move the partition to a new partition
Create and mount a new folder

 

4. Enter maintenance mode

Type the command below:

init 1

to enter the rescue mode:

move the partition to a new partition
Enter the maintenance mode

 

After that, press the Enter button to enter maintenance mode.

 

5. Copy the folder

Go to the /var folder and copy all the files and folders in the folder into a new folder by typing the following commands:

cd /var
cp -ax * /mnt/newvar

move the partition to a new partition
Copy the folder

 

6. Rename the folder

Once the copy process is complete, change the /var folder to the var.old folder and then create a new /var folder using the command:

cd /
mv var var.old
mkdir /var

move the partition to a new partition
Rename the folder

 

7. Mount the new folder

Next, do umount on the /sdb1 partition by using the command:

umount /dev/sdb1

 

And mount the /sdb1 partition to the new /var folder using the command:

mount /dev/sdb1 /var

move the partition to a new partition
Mount the new folder

 

8. Change the fstab file

Change the /etc/fstab file by adding the following script to the file:

/dev/sdb1	/var	ext4	defaults	0 0

move the partition to a new partition
Script additions in fstab file

 

9. Restart the server

After that, restart the Linux server and make sure there is no problem when the Linux server reboots.

 

10. Delete the folder

If the Linux server has finished restarting, then you can delete the var.old folder so that the size of the hard disk of the root partition increases by using the command:

cd /
rm -rf var.old

move the partition to a new partition
Before and after moving the partition

 

Note

Reboot the server again to make sure there are no problems after you delete the var.old folder. You can use the steps above when you want to move another folder to a new partition in the Linux server.

 

References

blog.oshim.net
phoenixnap.com




How to Manage a Container in Docker?

The previous article explained how to install Docker on Linux. This article will explain how to manage a container in Docker.

 

Problem

How to manage a container in Docker?

 

Solution

To manage a container in Docker, you have to remember basic Docker commands. And here are the basic Docker commands:

1. Search for container images

To run containers in Docker, we need a Docker image. A Docker image is an immutable (unchangeable) file that contains the source code, libraries, dependencies, tools, and other files needed for an application to run. The place to store Docker images is known as the Docker registry, which by default uses the Docker Hub located at hub.docker.com. If you are looking for a container image in Docker, use the format below:

docker search container_name

 

For example, if you want to find an nginx image, then use the command below:

docker search nginx

manage a container in docker
Searching the nginx image

 

2. Download the Docker image

To download the Docker image, use the following format:

docker image pull image_name:tag_version

 

where the tag_version is the version of the image, and if you don’t write the tag, it is considered that you want to install the latest version of the image. For example, if you want to download the newest version of the nginx image, use the command:

docker image pull nginx

manage a container in docker
Download the nginx image

 

But if you want to download nginx with a certain version, for example, version 1.27.2, then use the command:

docker image pull nginx:1.27.2

manage a container in docker
Download the nginx with a certain version

 

3. List the Docker image(s)

To display the Docker image that you have downloaded, use the command below:

docker image ls

List the Docker images

 

Or you can use the command below:

docker images

List the Docker images

 

4. Create a container

You can create the container using the format:

docker container create –name container_name image_name:tag

 

For example, if you want to create a container with the name webapp1, which contains the nginx application, then use the command below:

docker container create --name webapp1 nginx

 

When you use this command, Docker will first check whether the nginx image is on the server. If the image is not on the server, then Docker will download the nginx image, and after that, it will create an nginx container, and the image will remain on your server, as shown in the image below:

manage a container in docker
Create the container

 

You can use an image to create multiple containers as long as the container names are different, as in the image below:

manage a container in docker
Create the containers with 1 image

 

5. List the status of the container(s)

To display the container status, you can use the command:

docker ps

manage a container in docker
List the status of running Docker

 

Maybe you are confused about why there is no container status displayed, even though you have made 2 containers before. Remember that the docker ps command only displays the ongoing container status. While the 2 containers you made had not been running, you just made a container. If you want to display all container statuses, use the command below:

docker ps -a

manage a container in docker
List all container statuses in Docker

 

6. Turn on the container

To turn on a container, you can use the format:

docker container start container_id/container_name

 

Usually, I use container_name instead of container_id because it’s easier to memorize, so I run the following command:

docker container start webapp1

manage a container in docker
Turn on the container

 

7. Pause the container

You can pause a container with the following format:

docker container pause container_id/container_name

 

So, you can use the command below to pause the container:

docker container pause webapp1

manage a container in docker
Pause the container

 

To resume the container, use the following format:

docker containers unpause container_id/container_name

 

You can use the command below to resume the container:

docker container unpause webapp1

manage a container in docker
Resume the container

 

8. Run a container with a single command

As explained above, if you want to run a container, you have to download the image first, create a container, and turn on the container (see numbers 2, 4, and 6). There is a command that can summarize the three commands above, using the format below:

docker run -d --name container_id/container_name image_name:tag

 

where the -d option is to run the container in the background. So if you want to run a container with the name webapp2, which contains the nginx application, then use the command below:

docker run -d --name webapp3 nginx

manage a container in docker
Run the container

 

9. Display the size of Docker

To display how large Docker is installed on your server, use the command below:

docker system df

Display the size of Docker

 

To display a Docker size in detail, use the command below:

docker system df -v

Display the size of the Docker

 

 

10. Display logs

To display logs of the running container to check something, follow the format below:

docker container logs container_id/container_name

 

So, run the command below to check the logs of your container:

docker container logs webapp1

manage a container in docker
Display logs in the container

 

If you want to display real-time logs of the container, give an option -f like in the below command:

docker container logs -f webapp1

Press Ctrl-C to exit the log.

manage a container in docker
Display real-time logs in the container

 

11. Inspect the container

To display detailed information about a container, use the following format:

docker inspect container_name/container_id

 

So, if you want to see the detailed information about the container that you created before, use the command below:

docker inspect webapp1

manage a container in docker
Inspect the container

 

If you only want to display specific items when running the inspect command, use the following format:

docker container inspect container_name/container_id -f '{{json .the item_you_want_to_display<.sub_item> }}' | python -m json.tool

 

So if you want to display only the network section when using the Docker inspect command, use the command below:

docker container inspect webapp1 -f '{{json .NetworkSettings.Networks }}' | python3 -m json.tool

manage a container in docker
Inspect the network of the container only

 

12. Stop the container(s)

To stop the container, use the format below:

docker container stop container_id/container_name

 

For example, if I want to stop my container, then use the command below:

docker container stop webapp1

manage a container in docker
Stop the container

 

You can stop all the containers running with the below command:

docker stop webapp1 webapp2

manage a container in docker
Stop more than one container

 

Or use the below command to stop all the running containers:

docker kill $(docker ps -q)

manage a container in docker
Stop all running containers

 

13. Remove the container(s)

Before you remove the container, you have to stop the container first. To delete a container that’s already turned off, use the format below:

docker container rm container_id/container_name

 

Run the command below to remove the container:

docker container rm webapp1

manage a container in docker
Delete the container

 

By default, you can’t remove a container if the container is still running. You can use the command below to delete the container even if the container is still running, but it is not recommended:

docker container rm -f webapp2

manage a container in docker
Force delete the running container

 

If you have a lot of containers that are no longer used and you don’t want to delete them one by one, you can use the command below to delete all the unused containers:

docker rm $(docker ps -a -q)

manage a container in docker
Delete all the stop containers

 

You can also use the command below to delete all the stop containers:

docker container prune

Delete the stop containers using the prune command

 

14. Delete the image(s)

To delete the Docker image that you have already downloaded, use the format below:

docker image rm image_name

 

Run the image below if you want to delete the nginx image:

docker image rm nginx

manage a container in docker
Delete the image

 

However, you must know that you can’t delete the Docker image if the image is still running in the container. So you must remove the container first before you delete the image. If you want to delete multiple Docker images, use the following format:

docker image rm image_name1 image_name2 ...

 

So if you want to delete the nginx image and nginx:1.27.2 at once, then use the command below:

docker image rm nginx nginx:1.27.2

manage a container in docker
Delete more than one image

 

And if you want to delete all the images, you can use the command below:

docker rmi $(docker images -a -q)

manage a container in docker
Delete all the images

 

Or, you can use the command below to remove the unused images:

docker image prune -a

Delete all the unused images using the prune command

 

Note

If you forget or don’t know what command to use in Docker, use the following command:

docker --help

Using the docker help command

 

After that, if you want to know the options in the Docker command, then use the following format:

docker command --help

 

For example, if you want to know the options of the run command in Docker, then type the command below:

docker run --help

Using the docker run help command

 

You can shorten all the Docker container commands to just the docker command to shorten the typing time. For example, if you want to create a container, you can use the command:

docker create --name webapp6 nginx

manage a container in docker
Using the docker create command

 

References

geeksforgeeks.org
mygreatlearning.com
youtube.com
youtube.dimas-maryanto.com




How to Check a Public IP in the Spam List Using a Bash Script?

The previous article explained how to see the status of a public IP, whether it is indicated as spam or not, using a PHP script. This article will explain the status of a public IP that is indicated as spam or does not use bash scripts.

 

Problem

How to check a public IP in the spam list using a bash script?

 

Solution

To run the bash script to check whether a public IP address in the spam list is spam or not, you must install the required packages below:

Ubuntu/Debian

apt-get install -y dnsutils

 

RHEL/CentOS/RockyLinux/AlmaLinux

yum install bind-utils -y

 

Then copy the bash script below and give the name check_ip_spam.sh:

#!/usr/bin/env bash
# -- $Id: blcheck,v 1.4 2007/06/16 01:08:10 j65nko Exp $ --
# Check if an IP address is listed on one of the following blacklists
# The format is chosen to make it easy to add or delete
# The shell will strip multiple whitespace
BLISTS="
bl.spamcop.net
cbl.abuseat.org
dnsbl.justspam.org
dnsbl.sorbs.net
relays.mail-abuse.org
spam.dnsbl.sorbs.net
spamguard.leadmon.net
zen.spamhaus.org
"

# simple shell function to show an error message and exit
# $0 : the name of shell script, $1 is the string passed as argument
# >&2 : redirect/send the message to stderr
ERROR() {
echo $0 ERROR: $1 >&2
exit 2
}

# -- Sanity check on parameters
[ $# -ne 1 ] && ERROR 'Please specify a single IP address'

# -- if the address consists of 4 groups of minimal 1, maximal digits, separated by '.'
# -- reverse the order
# -- if the address does not match these criteria the variable 'reverse will be empty'
reverse=$(echo $1 |sed -ne "s~^\([0-9]\{1,3\}\)\.\([0-9]\{1,3\}\)\.\([0-9]\{1,3\}\)\.\([0-9]\{1,3\}\)$~\4.\3.\2.\1~p")
if [ "x${reverse}" = "x" ] ; then
ERROR "IMHO '$1' doesn't look like a valid IP address"
exit 1
fi

# Assuming an IP address of 11.22.33.44 as parameter or argument
# If the IP address in $0 passes our crude regular expression check,
# the variable ${reverse} will contain 44.33.22.11
# In this case the test will be:
# [ "x44.33.22.11" = "x" ]
# This test will fail and the program will continue
# An empty '${reverse}' means that shell argument $1 doesn't pass our simple IP address check
# In that case the test will be:
# [ "x" = "x" ]
# This evaluates to true, so the script will call the ERROR function and quit
# -- do a reverse ( address -> name) DNS lookup
REVERSE_DNS=$(dig +short -x $1)
echo IP $1 NAME ${REVERSE_DNS:----}
EXITCODE=0

# -- cycle through all the blacklists
for BL in ${BLISTS} ; do

# print the UTC date (withour linefeed)
printf $(env TZ=UTC date "+%Y-%m-%d_%H:%M:%S_%Z")

# show the reversed IP and append the name of the blacklist
printf "%-40s" " ${reverse}.${BL}."

# use dig to lookup the name in the blacklist
#echo "$(dig +short -t a ${reverse}.${BL}. | tr '\n' ' ')"
LISTED="$(dig +short -t a ${reverse}.${BL}.)"
echo [${LISTED:-OK}]
echo $LISTED | grep '127\.' >/dev/null && EXITCODE=4
done
exit $EXITCODE
# --- EOT ------

 

Type the command below so that the bash script can run:

chmod +x check_ip_spam.sh

 

To run this bash script, use the format below:

./check_ip.sh public_IP_address

 

For example, you want to check IP 172.217.194.113, then run the script by:

./check_ip.sh 172.217.194.113

 

And there will be the following display:

Results of public IP checks indicated by spam

 

From the image above, it can be seen that the public IP does not include spam. If a public IP is included in the spam list, for example, IP 24.209.96.220, it will come out [127.0.0.x] as in the image below:

Public IP check results that do not indicate spam

 

If you want to check over one IP, then use the syntax format:

for X in public_ip_address_1 public_ip_address_2 ...; do echo;./check_ip $X; echo; done

 

For example, if you want to check two public IP addresses, 172.217.194.113 and 24.209.96.220, you can type:

for X in 172.217.194.113 24.209.96.220 ; do echo; ./check_ip.sh $X ;echo; done

check a public IP in the spam list
Check more than 1 public IP

 

Note

If you want to change the DNSBL or Domain Name System Blacklists list, then you can change it in lines 7-14 of the scrip,t and you can add the DNSBL list here. The more you enter the DNSBL list, the more valid the output will be.

 

References

daemonforums.org
maxmind.com
cyberciti.biz
tecmint.com