📜 ⬆️ ⬇️

Access to the linux server using Telegram-bot in Python

Quite often there are situations when access to the server is needed here and now. However, not always an SSH connection is the most convenient way, because there may not be an SSH client, server addresses, or a “user / password” connection at hand. Of course, there is Webmin , which simplifies administration, but it also does not provide instant access.

Therefore, I decided to implement a simple but interesting solution. Namely, to write a Telegram bot, which, starting at the server itself, will execute the commands sent to it and return the result. Having studied several articles on this topic, I realized that no one has yet described such implementations.

I implemented this project on Ubuntu 16.04, but for a smooth launch on other distributions, I tried to do everything in a general way.

Bot registration


Register a new bot at @BotFather. We send him /newbot and hereinafter. We will need the token of the new bot and your id (you can get it, for example, from @userinfobot ).
')

Python preparation


To launch the bot, we will use the telebot library ( pip install pytelegrambotapi ). With the help of the subprocess library we will execute commands on the server.

Run bot


On the server, create a bot.py file:
nano bot.py

And paste the code into it:

 from subprocess import check_output import telebot import time bot = telebot.TeleBot("XXXXXXXXX:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")#  user_id = 0 #id   @bot.message_handler(content_types=["text"]) def main(message): if (user_id == message.chat.id): #,     comand = message.text #  try: #   - check_output  exception bot.send_message(message.chat.id, check_output(comand, shell = True)) except: bot.send_message(message.chat.id, "Invalid input") #   if __name__ == '__main__': while True: try:# try    bot.polling(none_stop=True)#  except: time.sleep(10)#   

Replace the bot token with the one that issued @BotFather, and user_id with the id value of your account. Checking the user id is necessary for the bot to provide access to your server only to you. The check_output() function executes the passed command and returns the result.

It remains only to run the bot. To run processes on the server, I prefer to use screen ( sudo apt-get install screen ):

 screen -dmS ServerBot python3 bot.py 
(where "ServerBot" is a process identifier)

The process will automatically start in background mode. Let's go into a dialogue with the bot and check that everything works as it should:



Congratulations! Bot executes commands sent to it. Now, to gain access to the server, you just need to open a dialogue with the bot.

Command repetition


Often, the same commands have to be executed to monitor server status. Therefore, the implementation of the repetition of commands without their re-sending will be very relevant.

We will implement using inline buttons under the messages:

 from subprocess import check_output import telebot from telebot import types #   import time bot = telebot.TeleBot("XXXXXXXXX:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")#  user_id = 0 #id   @bot.message_handler(content_types=["text"]) def main(message): if (user_id == message.chat.id): #,     comand = message.text #  markup = types.InlineKeyboardMarkup() #  button = types.InlineKeyboardButton(text="", callback_data=comand) #  markup.add(button) #    try: #   - check_output  exception bot.send_message(user_id, check_output(comand, shell = True, reply_markup = markup)) #       except: bot.send_message(user_id, "Invalid input") #   @bot.callback_query_handler(func=lambda call: True) def callback(call): comand = call.data #     data try:#    - check_output  exception markup = types.InlineKeyboardMarkup() #  button = types.InlineKeyboardButton(text="", callback_data=comand) #    data   markup.add(button) #    bot.send_message(user_id, check_output(comand, shell = True), reply_markup = markup) #       except: bot.send_message(user_id, "Invalid input") #   if __name__ == '__main__': while True: try:# try    bot.polling(none_stop=True)#  except: time.sleep(10)#   

Restart the bot:

 killall python3 screen -dmS ServerBot python3 bot.py 

Check again that everything works correctly:



By pressing the button under the message, the bot must repeat the command from which the message was sent.

Instead of conclusion


Of course, this method does not pretend to be a substitute for the classical connection methods, however, it allows you to quickly find out about the status of the server and send it commands that do not require complex output.

Source: https://habr.com/ru/post/443846/


All Articles