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