Using Telegram Bot Declare FirewallD rule with Python

Tram Ho

For those of you using Centos 7 operating system, it is no stranger to the concept of FirewallD , it is a powerful firewall solution installed by default on RHEL 7 and Centos 7 to replace Iptables. FirewallD uses “zone” and “services” instead of “chain” and “rule” in Iptables.

In this article, I will not go into depth about FirewallD, but will guide you to write a simple Telegram Bot to declare connection rules on FirewallD.

To declare the connection rule on the server, we need to run the commands:

The problem is that the Telegram Bot will receive the 2 address and port values ​​that we enter and execute the above 2 commands.

Step 1: Prepare the environment

  • Create a Telegram Bot
  • Install python-telegram-bot environment (here I have installed python3.7 environment on server)

Step 2: Code bot handles connection rule declaration on Firewalld

Create a file bot_anhln.py with the content as below

On the above code:

  • I have created a function firewalld_add_source_ip_port that handles the user inputting 2 source ip and port values ​​to be declared, in telegram bot you use context.args[i] to get each user input value.
  • Then I used os.system in python to execute commands on linux.
  • And use message.reply_text to notify again when the connection rule declaration has been completed.

So we have finished creating a simple bot to declare FirewallD, every time a user requests to declare a connection, but you are not working on the computer, you can still make the declaration normally.

Step 3: Enjoy the results

I will leave nohup to run the bot

image.png

 

Share the news now

Source : Viblo