Block an IP on a linux server
You probably find out find that your server is being attacked by brute force SSH attacks, port scanning, viruses scanning for the ability to spread, things like that or for some other reason you want to block a specific IP on your server.
In this article, I’ll show you how to block an IP address on Linux server using IPTables.
First, I’ll assume you are already using iptables. You can check that using this command line:
iptables -V
Second, you have to create 2 shell script files in /etc/init.d folder.
So go in the folder with cd /etc/init.d and create the first file:
vi blockip.sh
press “i”
paste this script inside
#!/bin/bash #blocking iptables /sbin/iptables -A INPUT -s $1 -j DROP #saving iptables /sbin/iptables-save > /etc/sysconfig/iptables
save the file by pressing the escape key then :wq!
Then, create the second file:
vi allowip.sh
press “i”
paste this script inside
#!/bin/bash #allowing iptables /sbin/iptables -D INPUT -s $1 -j DROP #saving iptables /sbin/iptables-save > /etc/sysconfig/iptables save the file like you did before
Now, you can use sudo ./blockip.sh 1.2.3.4 (where 1.2.3.4 is the IP you want to block) anywhere on the server.
To check if the IP was added, use this: /sbin/iptables -L INPUT -v -n | grep 1.2.3.4
To remove the IP from blocked list, use sudo ./allowip.sh 1.2.3.4
Hope this helped.