Piekļuve Linux serverim, izmantojot Telegram botu Python valodā

Pietiekami bieži notiek situācijas, kad piekļuve serverim nepieciešama šeit un tagad. Tomēr ne vienmēr SSH savienojums ir visērtākais veids, jo pie rokas var nebūt SSH klients, servera adrese vai lietotāja/paroļu kombinācija. Protams, ir Webmin, kas vienkāršo administrēšanu, taču tas arī nepiedāvā tūlītēju piekļuvi.

Tādēļ es nolēmu īstenot vienkāršu, bet interesantu risinājumu. Proti — uzrakstīt Telegram botu, kas, palaižot to uz paša servera, izpildīs tam nosūtītās komandas un atgriezīs rezultātu. Izpētot dažas rakstus šajā jomā, es sapratu, ka tādas īstenošanas vēl neviens nav aprakstījis.

Šo projektu es īstenoju uz Ubuntu 16.04, taču, lai bez problēmām palaistu uz citiem izplatījumiem, es centos visu izdarīt vispārīgi.

Bota reģistrācija

Reģistrējam jaunu botu pie @BotFather. Nosūtot tam /newbot un turpinot pa tekstu. Mums būs nepieciešams jaunā bota tokens un jūsu id (to var iegūt, piemēram, pie @userinfobot).

Python sagatavošana

Bota palaišanai izmantosim bibliotēku telebot (pip install pytelegrambotapi). Ar bibliotēkas palīdzību subprocess mēs izpildīsim komandas serverī.

Bota palaišana

Uz servera izveidojam failu bot.py:
nano bot.py

Un ielīmējam tajā kodu:

from subprocess import check_output
import telebot
import time

bot = telebot.TeleBot("XXXXXXXXX:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")#bota tokens
user_id = 0 #jūsu konta id
@bot.message_handler(content_types=["text"])
def main(message):
   if (user_id == message.chat.id): #pārbaudām, vai raksta tieši īpašnieks
      comand = message.text  #ziņas teksts
      try: #ja komanda nav izpildāma - check_output izsauks izņēmumu
         bot.send_message(message.chat.id, check_output(comand, shell = True))
      except:
         bot.send_message(message.chat.id, "Nederīga ievade") #ja komanda ir nepareiza
if __name__ == '__main__':
    while True:
        try:#pievienojam try, lai nodrošinātu nepārtrauktu darbību
            bot.polling(none_stop=True)#bota palaišana
        except:
            time.sleep(10)#ja gadās krišana

Aizvietojam tajā bota tokenu ar to, ko piešķīra @BotFather, un user_id — ar jūsu konta id vērtību. Pārbaude par id lietotāju ir nepieciešama, lai bots nodrošinātu piekļuvi jūsu serverim tikai jums. Funkcija check_output() izpilda nodoto komandu un atgriež rezultātu.

Vēl tikai jāpalaiž bots. Procesu palaišanai uz servera es izvēlos izmantot screen (sudo apt-get install screen):

screen -dmS ServerBot python3 bot.py

(kur "ServerBot" — procesa identifikators)

Process will automatically start in the background. Let's proceed to the dialogue with the bot and check that everything works as intended:

Piekļuve Linux serverim, izmantojot Telegram botu Python valodā

Congratulations! The bot executes the commands sent to it. Now, to access the server, simply open the dialogue with the bot.

Repeating commands

Often, to monitor the server status, you have to execute the same commands multiple times. Therefore, implementing command repetition without resending them will be quite useful.

We will implement it using inline buttons under messages:

from subprocess import check_output
import telebot
from telebot import types #Add button import
import time

bot = telebot.TeleBot("XXXXXXXXX:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")#Bot token
user_id = 0 #your account id
@bot.message_handler(content_types=["text"])
def main(message):
   if (user_id == message.chat.id): #check that the owner is the one writing
      comand = message.text  #message text
      markup = types.InlineKeyboardMarkup() #create keyboard
      button = types.InlineKeyboardButton(text="Repeat", callback_data=comand) #create button
      markup.add(button) #add button to keyboard
      try: #if the command is not executable - check_output will raise an exception
         bot.send_message(user_id, check_output(comand, shell = True,  reply_markup = markup)) #call the command and send a message with the result
      except:
         bot.send_message(user_id, "Invalid input") #if the command is incorrect

@bot.callback_query_handler(func=lambda call: True)
def callback(call):
  comand = call.data #read the command from the button data field
  try:#if the command is not executable - check_output will raise an exception
     markup = types.InlineKeyboardMarkup() #create keyboard
     button = types.InlineKeyboardButton(text="Repeat", callback_data=comand) #create button and pass the command in data
     markup.add(button) #add button to keyboard
     bot.send_message(user_id, check_output(comand, shell = True), reply_markup = markup) #call the command and send a message with the result
  except:
     bot.send_message(user_id, "Invalid input") #if the command is incorrect

if __name__ == '__main__':
    while True:
        try:#add try for uninterrupted operation
            bot.polling(none_stop=True)#start the bot
        except:
            time.sleep(10)#in case of crash

Restarting the bot:

killall python3
screen -dmS ServerBot python3 bot.py

Let's check again that everything is working correctly:

Piekļuve Linux serverim, izmantojot Telegram botu Python valodā

Upon pressing the button under the message, the bot should repeat the command from which this message was sent.

Noslēgumā

Certainly, this method does not claim to replace classic connection methods, however, it allows for quickly knowing the server status and sending it commands that do not require complex output.

Avots: habr.com

Iegādājieties uzticamu tīmekļa hostingu ar DDoS aizsardzību, VPS VDS serveriem 🔥 Iegādājieties uzticamu tīmekļa hostingu ar DDoS aizsardzību, VPS VDS serveriem | ProHoster