Table of Contents
In this article, I will show you how to control iptables in the bash script. Iptables is a firewall that is built into almost all Linux operating systems. Using it makes your system a more secure layer.
Controlling the iptables service and its rules manually, most people have done. But sometimes, iptables needs to work automatically, so how?
Assumption
Assuming that my web server receives a lot of requests every day, I know it’s a bad request. But my server is too weak to use a WAF layer on the 7th floor, such as Mod Security or Naxsi. The only way to mitigate that risk is to write a bash script that automatically identifies the bad requests that I know, filters the source IP address and blocks it in iptables.
So far, many people think why not use fail2ban? You know, the use of tools depends on the circumstances.
Control iptables in bash script
To automatically add a rule to iptables, just type:
iptables -A INPUT ...Next is to save the iptables table again:
service iptables saveAnd then restart the iptables service (eg CentOS):
service iptables restartIt’s easy, but when you test, you’ll soon realize that the iptables service is not controlled exactly as the script you write. Why is that?
The answer is environment variable. To control the iptables service, you need root or sudo permissions, and the corresponding user is their environment. The bash script is declared #!/bin/bash at the beginning and it does not include the iptables environment.
The simplest solution is to get the value of the current PATH variable on your system and add it to the top of the script file. Type the following command to get the system’s PATH:
echo $PATH
Conclusion
This trick is not difficult, but before, I also took a while to find out why my script can not work.
I look back to my script many times and not find the error. Hope this article will help you solve this small problem. Controlling iptables in bash scripts is easy.
(This is an article from my old blog that has been inactive for a long time, I don’t want to throw it away so I will keep it and hope it helps someone).