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:
1 2 3 | firewall-cmd --permanent --add-rich-rule 'rule family="ipv4" source address="115.146.126.xxx/32" port protocol="tcp" port="xxx" accept' firewall-cmd --reload |
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)
1 2 | pip3.7 install python-telegram-bot |
Step 2: Code bot handles connection rule declaration on Firewalld
Create a file bot_anhln.py with the content as below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | #!/usr/bin/env python # -*- coding: utf-8 -*- # pip3.7 install python-telegram-bot import os import logging from telegram import Update, ForceReply from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext # Enable Loging INFO/DEBUG logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.DEBUG) logger = logging.getLogger(__name__) def error(update, context): """Log Errors caused by Updates.""" logger.warning('Update "%s" caused error "%s"', update, context.error) def firewalld_add_source_ip_port(update, context): firewalld1 = '''firewall-cmd --permanent --add-rich-rule 'rule family="ipv4" source address="'''+str(context.args[0])+'''/32" port protocol="tcp" port="'''+str(context.args[1])+'''" accept'''+"'" print(firewalld1) firewalld2= "firewall-cmd --reload" os.system(firewalld1) os.system(firewalld2) update.message.reply_text('Server Dev: 115.146.126.xx add firewalld Ok') def main(): """Start the bot.""" # Create the Updater and pass it your bot's token. # Make sure to set use_context=True to use the new context based callbacks # Post version 12 this will no longer be necessary updater = Updater("{Token Telegram}", use_context=True) # Get the dispatcher to register handlers dp = updater.dispatcher # on different commands - answer in Telegram dp.add_handler(CommandHandler("firewalld_add_source_ip_port", firewalld_add_source_ip_port)) # log all errors dp.add_error_handler(error) # Start the Bot updater.start_polling() # Run the bot until you press Ctrl-C or the process receives SIGINT, # SIGTERM or SIGABRT. This should be used most of the time, since # start_polling() is non-blocking and will stop the bot gracefully. updater.idle() if __name__ == '__main__': main() |
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
1 2 | nohup python3.7 bot_anhln.py & |