Controlando el servidor desde Telegram via Bot

Share

En esta entrada veremos como generar un script en python para interactuar con nuestros servidores vía Telegram:

Instalar las librerías que se necesitan:

pip install future

pip install urllib3

pip install certifi

pip install python-telegram-bot

 

El template sería algo así:

 
#
# Code to interact with your server.
#
import telegram
import sys
import logging
import os


bot = telegram.Bot("API")
#chat_id=_NUMERO_



def log_update(update):
  message = update.message.text.encode('utf-8')
  bot_chat_id = update.message.chat.id
  update_id = update.update_id
  first_name = update.message.from_user.first_name
  last_name = update.message.from_user.last_name
  from_id = update.message.from_user.id

  if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
    logging.debug('Update %d from %s %s (%d) in chat %d received:', update_id,first_name, last_name, from_id, bot_chat_id)
    logging.debug(update)
  else:
    logging.info('Update %d from %s %s (%d) in chat %d: Received "%s"', update_id,first_name, last_name, from_id, bot_chat_id, message)


try:
    LAST_UPDATE_ID = bot.getUpdates()[-1].update_id
except IndexError:
    LAST_UPDATE_ID = None

while(True):


    for update in bot.getUpdates(offset=LAST_UPDATE_ID, timeout=30):
      bot_chat_id = update.message.chat.id
      message = update.message.text.encode('utf-8')
      update_id = update.update_id
      log_update(update)
      if chat_id >= 0 and chat_id != bot_chat_id:
        logging.warning('Unauthorized chat_id %d found. Update ignored.', bot_chat_id)
        continue

#command help
      if '/help' == message:
        status = "/GetFile - Get a file.\n/ExecCommand - Exec a pre set command.\n/OtherCommands - Send a Message"
        bot.sendMessage(chat_id = bot_chat_id, text=status, parse_mode=telegram.ParseMode.MARKDOWN)

#command NewPasswordsFile

      elif '/GetFile' == message:
        fd=open('/path/to/file.txt','r')
        bot.sendDocument(chat_id=bot_chat_id, document=fd)
        fd.close()

      elif '/ExecCommand' == message:
        os.system('echo command to exec > /path/to/file')

      elif '/OtherCommands' == message:
        bot.sendMessage(chat_id=bot_chat_id,text='Ideas are welcome :P, use /Suggest idea to submit crazy features.')

      else:
        #bot.sendMessage(chat_id=bot_chat_id,text='Welcome to My bot. Accepted commands:\n\n/help - Info aobut commands.')
        os.system('echo x > /dev/null')

      LAST_UPDATE_ID = update_id + 1
   

A disfrutarlo 🙂

1 comentario

  1. Qué miedo me da que ahora reproduzcamos vía Telegram todos los problemas de seguridad de invocar comandos de sistema a través de CGIs. ¡La historia se repite!

Responder a anon1 Cancelar la respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *