How to control iptables in bash script

by Daniel Pham
Published: Updated:

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?


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 save

And then restart the iptables service (eg CentOS):

service iptables restart

It’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
How to control iptables in bash script
Add PATH variable to bash script.


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).

0 0 votes
Article Rating

You may also like

Notify of
Inline Feedbacks
View all comments

DevOps Lite is a personal blog specializing in technology with main topics about DevOps, DevSecOps, SRE and System Administrator. Articles are shared for free and contributed to the community.



Subscribe my Newsletter for new blog posts. Stay updated from your inbox!

© 2021-2024 – All rights reserved.

Please write sources “” when using articles from this website.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More

Would love your thoughts, please comment.x

Adblock Detected

Please support us by disabling your AdBlocker extension from your browsers for our website.