azils3/bash
0
1# Ultroid - UserBot2# Copyright (C) 2021-2025 TeamUltroid3#4# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >5# PLease read the GNU Affero General Public License in6# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.7 8from . import get_help9 10__doc__ = get_help("help_devtools")11 12import inspect13import sys14import traceback15from io import BytesIO, StringIO16from os import remove17from pprint import pprint18 19from telethon.utils import get_display_name20 21from pyUltroid import _ignore_eval22 23from . import *24 25# Used for Formatting Eval Code, if installed26try:27 import black28except ImportError:29 black = None30from random import choice31 32try:33 from yaml import safe_load34except ImportError:35 from pyUltroid.fns.tools import safe_load36 37from . import upload_file as uf38from telethon.tl import functions39 40fn = functions41 42 43@ultroid_cmd(44 pattern="sysinfo$",45)46async def _(e):47 xx = await e.eor(get_string("com_1"))48 x, y = await bash("neofetch|sed 's/\x1B\\[[0-9;\\?]*[a-zA-Z]//g' >> neo.txt")49 if y and y.endswith("NOT_FOUND"):50 return await xx.edit(f"Error: `{y}`")51 with open("neo.txt", "r", encoding="utf-8") as neo:52 p = (neo.read()).replace("\n\n", "")53 haa = await Carbon(code=p, file_name="neofetch", backgroundColor=choice(ATRA_COL))54 if isinstance(haa, dict):55 await xx.edit(f"`{haa}`")56 else:57 await e.reply(file=haa)58 await xx.delete()59 remove("neo.txt")60 61 62@ultroid_cmd(pattern="bash", fullsudo=True, only_devs=True)63async def _(event):64 carb, rayso, yamlf = None, None, False65 try:66 cmd = event.text.split(" ", maxsplit=1)[1]67 if cmd.split()[0] in ["-c", "--carbon"]:68 cmd = cmd.split(maxsplit=1)[1]69 carb = True70 if cmd.split()[0] in ["-r", "--rayso"]:71 cmd = cmd.split(maxsplit=1)[1]72 rayso = True73 except IndexError:74 return await event.eor(get_string("devs_1"), time=10)75 xx = await event.eor(get_string("com_1"))76 reply_to_id = event.reply_to_msg_id or event.id77 stdout, stderr = await bash(cmd, run_code=1)78 OUT = f"**☞ BASH\n\n• COMMAND:**\n`{cmd}` \n\n"79 err, out = "", ""80 if stderr:81 err = f"**• ERROR:** \n`{stderr}`\n\n"82 if stdout:83 if (carb or udB.get_key("CARBON_ON_BASH")) and (84 event.is_private85 or event.chat.admin_rights86 or event.chat.creator87 or event.chat.default_banned_rights.embed_links88 ):89 li = await Carbon(90 code=stdout,91 file_name="bash",92 download=True,93 backgroundColor=choice(ATRA_COL),94 )95 if isinstance(li, dict):96 await xx.edit(97 f"Unknown Response from Carbon: `{li}`\n\nstdout`:{stdout}`\nstderr: `{stderr}`"98 )99 return100 url = uf(li)101 OUT = f"[\xad]({url}){OUT}"102 out = "**• OUTPUT:**"103 remove(li)104 elif (rayso or udB.get_key("RAYSO_ON_BASH")) and (105 event.is_private106 or event.chat.admin_rights107 or event.chat.creator108 or event.chat.default_banned_rights.embed_links109 ):110 li = await Carbon(111 code=stdout,112 file_name="bash",113 download=True,114 backgroundColor=choice(ATRA_COL),115 rayso=True,116 )117 if isinstance(li, dict):118 await xx.edit(119 f"Unknown Response from Carbon: `{li}`\n\nstdout`:{stdout}`\nstderr: `{stderr}`"120 )121 return122 url = uf(li)123 OUT = f"[\xad]({url}){OUT}"124 out = "**• OUTPUT:**"125 remove(li)126 else:127 if "pip" in cmd and all(":" in line for line in stdout.split("\n")):128 try:129 load = safe_load(stdout)130 stdout = ""131 for data in list(load.keys()):132 res = load[data] or ""133 if res and "http" not in str(res):134 res = f"`{res}`"135 stdout += f"**{data}** : {res}\n"136 yamlf = True137 except Exception as er:138 stdout = f"`{stdout}`"139 LOGS.exception(er)140 else:141 stdout = f"`{stdout}`"142 out = f"**• OUTPUT:**\n{stdout}"143 if not stderr and not stdout:144 out = "**• OUTPUT:**\n`Success`"145 OUT += err + out146 if len(OUT) > 4096:147 ultd = err + out148 with BytesIO(str.encode(ultd)) as out_file:149 out_file.name = "bash.txt"150 await event.client.send_file(151 event.chat_id,152 out_file,153 force_document=True,154 thumb=ULTConfig.thumb,155 allow_cache=False,156 caption=f"`{cmd}`" if len(cmd) < 998 else None,157 reply_to=reply_to_id,158 )159 160 await xx.delete()161 else:162 await xx.edit(OUT, link_preview=not yamlf)163 164 165pp = pprint # ignore: pylint166bot = ultroid = ultroid_bot167 168 169class u:170 _ = ""171 172 173def _parse_eval(value=None):174 if not value:175 return value176 if hasattr(value, "stringify"):177 try:178 return value.stringify()179 except TypeError:180 pass181 elif isinstance(value, dict):182 try:183 return json_parser(value, indent=1)184 except BaseException:185 pass186 elif isinstance(value, list):187 newlist = "["188 for index, child in enumerate(value):189 newlist += "\n " + str(_parse_eval(child))190 if index < len(value) - 1:191 newlist += ","192 newlist += "\n]"193 return newlist194 return str(value)195 196 197@ultroid_cmd(pattern="eval", fullsudo=True, only_devs=True)198async def _(event):199 try:200 cmd = event.text.split(maxsplit=1)[1]201 except IndexError:202 return await event.eor(get_string("devs_2"), time=5)203 xx = None204 mode = ""205 spli = cmd.split()206 207 async def get_():208 try:209 cm = cmd.split(maxsplit=1)[1]210 except IndexError:211 await event.eor("->> Wrong Format <<-")212 cm = None213 return cm214 215 if spli[0] in ["-s", "--silent"]:216 await event.delete()217 mode = "silent"218 elif spli[0] in ["-n", "-noedit"]:219 mode = "no-edit"220 xx = await event.reply(get_string("com_1"))221 elif spli[0] in ["-gs", "--source"]:222 mode = "gsource"223 elif spli[0] in ["-ga", "--args"]:224 mode = "g-args"225 if mode:226 cmd = await get_()227 if not cmd:228 return229 if not mode == "silent" and not xx:230 xx = await event.eor(get_string("com_1"))231 if black:232 try:233 cmd = black.format_str(cmd, mode=black.Mode())234 except BaseException:235 # Consider it as Code Error, and move on to be shown ahead.236 pass237 reply_to_id = event.reply_to_msg_id or event238 if any(item in cmd for item in KEEP_SAFE().All) and (239 not (event.out or event.sender_id == ultroid_bot.uid)240 ):241 warning = await event.forward_to(udB.get_key("LOG_CHANNEL"))242 await warning.reply(243 f"Malicious Activities suspected by {inline_mention(await event.get_sender())}"244 )245 _ignore_eval.append(event.sender_id)246 return await xx.edit(247 "`Malicious Activities suspected⚠️!\nReported to owner. Aborted this request!`"248 )249 old_stderr = sys.stderr250 old_stdout = sys.stdout251 redirected_output = sys.stdout = StringIO()252 redirected_error = sys.stderr = StringIO()253 stdout, stderr, exc, timeg = None, None, None, None254 tima = time.time()255 try:256 value = await aexec(cmd, event)257 except Exception:258 value = None259 exc = traceback.format_exc()260 tima = time.time() - tima261 stdout = redirected_output.getvalue()262 stderr = redirected_error.getvalue()263 sys.stdout = old_stdout264 sys.stderr = old_stderr265 if value:266 try:267 if mode == "gsource":268 exc = inspect.getsource(value)269 elif mode == "g-args":270 args = inspect.signature(value).parameters.values()271 name = ""272 if hasattr(value, "__name__"):273 name = value.__name__274 exc = f"**{name}**\n\n" + "\n ".join([str(arg) for arg in args])275 except Exception:276 exc = traceback.format_exc()277 evaluation = exc or stderr or stdout or _parse_eval(value) or get_string("instu_4")278 if mode == "silent":279 if exc:280 msg = f"• <b>EVAL ERROR\n\n• CHAT:</b> <code>{get_display_name(event.chat)}</code> [<code>{event.chat_id}</code>]"281 msg += f"\n\n∆ <b>CODE:</b>\n<code>{cmd}</code>\n\n∆ <b>ERROR:</b>\n<code>{exc}</code>"282 log_chat = udB.get_key("LOG_CHANNEL")283 if len(msg) > 4000:284 with BytesIO(msg.encode()) as out_file:285 out_file.name = "Eval-Error.txt"286 return await event.client.send_message(287 log_chat, f"`{cmd}`", file=out_file288 )289 await event.client.send_message(log_chat, msg, parse_mode="html")290 return291 tmt = tima * 1000292 timef = time_formatter(tmt)293 timeform = timef if not timef == "0s" else f"{tmt:.3f}ms"294 final_output = "__►__ **EVAL** (__in {}__)\n```{}``` \n\n __►__ **OUTPUT**: \n```{}``` \n".format(295 timeform,296 cmd,297 evaluation,298 )299 if len(final_output) > 4096:300 final_output = evaluation301 with BytesIO(str.encode(final_output)) as out_file:302 out_file.name = "eval.txt"303 await event.client.send_file(304 event.chat_id,305 out_file,306 force_document=True,307 thumb=ULTConfig.thumb,308 allow_cache=False,309 caption=f"```{cmd}```" if len(cmd) < 998 else None,310 reply_to=reply_to_id,311 )312 return await xx.delete()313 await xx.edit(final_output)314 315 316def _stringify(text=None, *args, **kwargs):317 if text:318 u._ = text319 text = _parse_eval(text)320 return print(text, *args, **kwargs)321 322 323async def aexec(code, event):324 exec(325 (326 "async def __aexec(e, client): "327 + "\n print = p = _stringify"328 + "\n message = event = e"329 + "\n u.r = reply = await event.get_reply_message()"330 + "\n chat = event.chat_id"331 + "\n u.lr = locals()"332 )333 + "".join(f"\n {l}" for l in code.split("\n"))334 )335 336 return await locals()["__aexec"](event, event.client)337 338 339DUMMY_CPP = """#include <iostream>340using namespace std;341 342int main(){343!code344}345"""346 347 348@ultroid_cmd(pattern="cpp", only_devs=True)349async def doie(e):350 match = e.text.split(" ", maxsplit=1)351 try:352 match = match[1]353 except IndexError:354 return await e.eor(get_string("devs_3"))355 msg = await e.eor(get_string("com_1"))356 if "main(" not in match:357 new_m = "".join(" " * 4 + i + "\n" for i in match.split("\n"))358 match = DUMMY_CPP.replace("!code", new_m)359 open("cpp-ultroid.cpp", "w").write(match)360 m = await bash("g++ -o CppUltroid cpp-ultroid.cpp")361 o_cpp = f"• **Eval-Cpp**\n`{match}`"362 if m[1]:363 o_cpp += f"\n\n**• Error :**\n`{m[1]}`"364 if len(o_cpp) > 3000:365 os.remove("cpp-ultroid.cpp")366 if os.path.exists("CppUltroid"):367 os.remove("CppUltroid")368 with BytesIO(str.encode(o_cpp)) as out_file:369 out_file.name = "error.txt"370 return await msg.reply(f"`{match}`", file=out_file)371 return await eor(msg, o_cpp)372 m = await bash("./CppUltroid")373 if m[0] != "":374 o_cpp += f"\n\n**• Output :**\n`{m[0]}`"375 if m[1]:376 o_cpp += f"\n\n**• Error :**\n`{m[1]}`"377 if len(o_cpp) > 3000:378 with BytesIO(str.encode(o_cpp)) as out_file:379 out_file.name = "eval.txt"380 await msg.reply(f"`{match}`", file=out_file)381 else:382 await eor(msg, o_cpp)383 os.remove("CppUltroid")384 os.remove("cpp-ultroid.cpp")385 