使用Python Telegram bot访问Linux服务器

在很多情况下,此时此刻需要访问服务器。 但是,SSH连接并不总是最方便的方法,因为SSH客户端,服务器地址或用户/密码链接可能并不在手。 当然,有Webmin ,它可以简化管理,但也不能提供即时访问。

因此,我决定实施一个简单但有趣的解决方案。 即,编写一个Telegram机器人,该机器人从服务器本身开始,将执行发送给它的命令并返回结果。 研究有关该主题的几篇 文章之后 ,我意识到还没有人描述这种实现。

我在Ubuntu 16.04上实现了该项目,但是为了在其他发行版上无故障启动,我尝试以常规方式进行所有操作。

机器人注册


用@BotFather注册一个新的机器人。 我们发送给他/newbot并在文本中进一步说明。 我们将需要新机器人的令牌和您的ID(例如,您可以从@userinfobot获得它)。

Python准备


要启动该机器人,我们将使用telebot库( pip install pytelegrambotapi )。 使用subprocess库,我们将在服务器上执行命令。

机器人启动


在服务器上,创建bot.py文件:
nano bot.py

并将代码粘贴到其中:

 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)#   

我们将其中的机器人令牌替换为@BotFather颁发的机器人令牌,并将user_id替换为您帐户的ID值。 检查用户ID是必要的,以便该bot仅向您提供对服务器的访问。 check_output()函数执行传递的命令并返回结果。

它仍然只是启动机器人。 要在服务器上启动进程,我更喜欢使用screensudo apt-get install screen ):

 screen -dmS ServerBot python3 bot.py 
(其中“ ServerBot”是进程标识符)

该过程将在后台自动启动。 让我们进入与机器人的对话,并检查一切是否正常运行:



恭喜你! 机器人执行发送给它的命令。 现在,要访问服务器,您只需要打开与机器人的对话框即可。

重复命令


通常,要监视服务器的状态,您必须执行相同的命令。 因此,重复执行命令而不再次发送命令将非常不合适。

我们将使用消息下方的嵌入式按钮来实现:

 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)#   

重新启动机器人:

 killall python3 screen -dmS ServerBot python3 bot.py 

再次检查一切是否正常:



通过按下消息下方的按钮,机器人应重复发送消息的命令。

而不是结论


当然,该方法不能伪装成经典连接方法的替代方法,但是,它使您可以快速了解服务器的状态,并向其发送不需要复杂输出的命令。

Source: https://habr.com/ru/post/zh-CN443846/


All Articles