Code Monkey home page Code Monkey logo

batchshield's Introduction

batchshield's People

Contributors

devbubba avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

batchshield's Issues

Try this :

import time
import random
import string
import subprocess
import sys
import glob

from colorama import Back, Fore, Style
import fade

MIN_PYTHON = (3, 10)
REQUIRED_MODULES = ["colorama", "fade", "glob"]

class ModuleCheckError(Exception):
    pass

class InvalidInputError(Exception):
    pass

def check_python_version():
    if sys.version_info < MIN_PYTHON:
        raise ModuleCheckError(f"BatchShield requires Python {MIN_PYTHON[0]}.{MIN_PYTHON[1]} or higher. You are using {sys.version_info[0]}.{sys.version_info[1]}.")

def check_required_modules():
    missing_modules = [module for module in REQUIRED_MODULES if module not in sys.modules]
    
    if missing_modules:
        raise ModuleCheckError(f"The following required modules are missing: {', '.join(missing_modules)}")

def install_missing_modules(missing_modules):
    for module in missing_modules:
        subprocess.call(['pip', 'install', module])
    print("All missing modules have been installed, please re-run BatchShield!")
    time.sleep(5)
    exit()

def main():
    try:
        check_python_version()
        check_required_modules()
    except ModuleCheckError as e:
        print(f"{Fore.RED}[-] {e}{Style.RESET_ALL}")
        if input("Would you like to automatically install any missing modules? [y/n] :  ").lower() == "y":
            install_missing_modules(e.args[0].split(', '))
        exit()

    auto_detect = input('{:<27}: '.format(f"{Fore.YELLOW}[+] AutoDetect .Bat File [Y/N]  {Style.RESET_ALL}"))

    if auto_detect.lower() not in ['y', 'n']:
        raise InvalidInputError("Invalid Input!")
    
    path = auto_detect_path(auto_detect)

    level = int(input('{:<27}: '.format(f'{Fore.YELLOW}[+] Obfuscation Level [1/2]  {Style.RESET_ALL}')))
    if level not in [1, 2]:
        raise InvalidInputError("Invalid Input!")

    confirm = input('{:<27}: '.format(f"{Fore.YELLOW}[+] Are You Sure You Would Like To Obfuscate {path}? [Y/N]  {Style.RESET_ALL}"))

    if confirm.lower() not in ['y', 'n']:
        raise InvalidInputError("Invalid Input!")

    obfuscate_code(path, level, confirm)

def auto_detect_path(auto_detect):
    path = ''
    if auto_detect.lower() == "y":
        os.getcwd()
        bat_files = glob.glob("*.bat")
        if not bat_files:
            raise FileNotFoundError("No .Bat Files Found!")
        elif len(bat_files) > 1:
            print(f"{Fore.GREEN}[+] Multiple .Bat Files Found!{Style.RESET_ALL}")
            path = choose_bat_file(bat_files)
        else:
            path = bat_files[0]
        print(f"{Fore.GREEN}[+] AutoDetected .Bat File - {path}{Style.RESET_ALL}")
    elif auto_detect.lower() == "n":
        path = input('{:<27}: '.format(f"{Fore.YELLOW}[+] File Path Including (.bat)  {Style.RESET_ALL}"))
        os.getcwd()
        bat_files = glob.glob(path)
        if not bat_files:
            raise FileNotFoundError("File Not Found!")
        path = bat_files[0]
        print(f"{Fore.GREEN}[+] Found .Bat File - {path}{Style.RESET_ALL}")
    return path

def choose_bat_file(bat_files):
    for idx, file in enumerate(bat_files):
        print(f"{Fore.RED}[{idx+1}] {file}{Style.RESET_ALL}")
    try:
        selection = int(input('{:<27}: '.format(f"{Fore.YELLOW}[+] Select File [1-{len(bat_files)}]  {Style.RESET_ALL}")))
        if selection < 1 or selection > len(bat_files):
            raise ValueError
        path = bat_files[selection-1]
    except ValueError:
        raise InvalidInputError("Invalid Input!")
    return path

def obfuscate_code(path, level, confirm):
    with open(path, 'r', encoding='utf-8') as f:
        code = f.read()

    if confirm.lower() == "y":
        try:
            if level == 1:
                with open(f'obfuscated_{os.path.basename(path)}', 'w+', encoding='utf-8') as f:
                    f.write(Methods.LevelOne(code))
            elif level == 2:
                with open(f'obfuscated_{os.path.basename(path)}', 'w+', encoding='utf-8') as f:
                    f.write(Methods.LevelTwo(code, path))
            print(f"{Fore.GREEN}[+] Successfully Obfuscated {path}!{Style.RESET_ALL}")
            print(f"{Fore.RED}[-] Exiting...{Style.RESET_ALL}")
            time.sleep(5)
            exit()
        except Exception as e:
            print(f"{Fore.RED}[-] Error: {e}{Style.RESET_ALL}")
            print(f"{Fore.RED}[-] Exiting...{Style.RESET_ALL}")
            time.sleep(5)
            exit()

class Methods:
    @staticmethod
    def LevelOne(code: str) -> str:
        if not isinstance(code, str):
            raise TypeError("Input 'code' Parameter Must Be A String Type!")
        if not code.strip():
            raise ValueError("Input 'code' Parameter Cannot Be Empty!")

        obfuscated = ''.join(f'%{random_str()}%' if char == '%' else char for char in code)
        if not obfuscated.strip():
            raise ValueError("Output From 'LevelOne()' Method Cannot Be Empty!")
        return obfuscated

    @staticmethod
    def random_str():
        return ''.join(random.choice(string.ascii_letters) for _ in range(random.randint(5, 15)))

    @staticmethod
    def LevelTwo(code: str, path: str) -> bytes:
        if not isinstance(code, str):
            raise TypeError("Input 'code' Parameter Must Be A String Type!")
        if not code.strip():
            raise ValueError("Input 'code' Parameter Cannot Be Empty!")

        obfuscated = bytearray(b'\xFF\xFE\n\r')
        encoded = Methods.LevelOne(code)
        try:
            code_bytes = encoded.encode('utf-8', 'strict')
        except UnicodeEncodeError:
            raise ValueError("Cannot Encode Obfuscated Code In UTF-8!")
        if not code_bytes:
            raise ValueError("Output From 'encode()' Method In 'LevelTwo()' Method Cannot Be Empty!")

        if not all(c in string.printable for c in encoded):
            raise ValueError("Input 'code' Parameter Contains Non-Printable Characters!")

        if not all(ord(c) < 128 for c in encoded):
            raise ValueError("Input 'code' Parameter Contains Characters Not Supported By The UTF-8 Encoding!")

        with open(f'obfuscated_{os.path.basename(path)}', 'wb') as f:
            f.write(obfuscated + code_bytes)

        if not obfuscated:
            raise ValueError("Output From 'LevelTwo()' Method Cannot Be Empty!")
        return bytes(obfuscated)

if __name__ == '__main__':
    try:
        main()
    except InvalidInputError as e:
        print(f"{Fore.RED}[-] {e}{Style.RESET_ALL}")
        print(f"{Fore.RED}[-] Exiting...{Style.RESET_ALL}")
        time.sleep(5)
        exit()
class Methods:
    @staticmethod
    def random_str():
        return ''.join(random.choice(string.ascii_letters) for _ in range(random.randint(5, 15)))

    @staticmethod
    def obfuscate_with_nonprintable(code: str) -> str:
        if not isinstance(code, str):
            raise TypeError("Input 'code' Parameter Must Be A String Type!")
        if not code.strip():
            raise ValueError("Input 'code' Parameter Cannot Be Empty!")
        # Map every character to non-printable ones
        mapping = {chr(i): chr(1 + i % 32) for i in range(33, 127)}
        # Obfuscate the code using the mapping
        obfuscated = ''.join(mapping.get(c, c) for c in code)
        # Encapsulate the obfuscated code into a self-extracting batch script
        decoder = f'''
@echo off
setlocal EnableDelayedExpansion
set "obfuscated_code={obfuscated}"
for %%A in ({' '.join(f'"{k}" "{v}"' for k, v in mapping.items())}) do (
    set "obfuscated_code=!obfuscated_code:%%A=%%~B!"
)
%obfuscated_code%
        '''
        return decoder

I fixed ur code ( it works now )

try:
    from colorama import Back, Fore, Style
    import glob, os
    import random
    import string
    import time
    import fade
    import os

except ImportError as e:
    missing_module = str(e).split()[-1] # get the name of the missing module from the error message
    if "No module named" in str(e):
        print(f"[-] Error! You don't have the '{missing_module}' module installed to run Batch Obfuscater V2.1. Please install it using pip install {missing_module} and try again.")
    elif "version" in str(e):
        print(f"[-] Error! The version of the '{missing_module}' module installed on your system is not compatible with Batch Obfuscater V2.1. Please upgrade or downgrade to the required version and try again.")
    elif "download" in str(e):
        print(f"[-] Error! There was an issue downloading the '{missing_module}' module required by Batch Obfuscater V2.1. Please check your internet connection and try again.")
    else:
        print("[-] Error! You don't have all the required modules installed to run Batch Obfuscater V2.1. Please open install.bat to fix!")
    time.sleep(5)
    exit()




text = """\n
 ▒█████   ▄▄▄▄     █████▒█    ██   ██████  ▄████▄   ▄▄▄     ▄▄▄█████▓ ▒█████   ██▀███  
▒██▒  ██▒▓█████▄ ▓██   ▒ ██  ▓██▒▒██    ▒ ▒██▀ ▀█  ▒████▄   ▓  ██▒ ▓▒▒██▒  ██▒▓██ ▒ ██▒
▒██░  ██▒▒██▒ ▄██▒████ ░▓██  ▒██░░ ▓██▄   ▒▓█    ▄ ▒██  ▀█▄ ▒ ▓██░ ▒░▒██░  ██▒▓██ ░▄█ ▒
▒██   ██░▒██░█▀  ░▓█▒  ░▓▓█  ░██░  ▒   ██▒▒▓▓▄ ▄██▒░██▄▄▄▄██░ ▓██▓ ░ ▒██   ██░▒██▀▀█▄  
░ ████▓▒░░▓█  ▀█▓░▒█░   ▒▒█████▓ ▒██████▒▒▒ ▓███▀ ░ ▓█   ▓██▒ ▒██▒ ░ ░ ████▓▒░░██▓ ▒██▒
░ ▒░▒░▒░ ░▒▓███▀▒ ▒ ░   ░▒▓▒ ▒ ▒ ▒ ▒▓▒ ▒ ░░ ░▒ ▒  ░ ▒▒   ▓▒█░ ▒ ░░   ░ ▒░▒░▒░ ░ ▒▓ ░▒▓░
  ░ ▒ ▒░ ▒░▒   ░  ░     ░░▒░ ░ ░ ░ ░▒  ░ ░  ░  ▒     ▒   ▒▒ ░   ░      ░ ▒ ▒░   ░▒ ░ ▒░
░ ░ ░ ▒   ░    ░  ░ ░    ░░░ ░ ░ ░  ░  ░  ░          ░   ▒    ░      ░ ░ ░ ▒    ░░   ░ 
    ░ ░   ░                ░           ░  ░ ░            ░  ░            ░ ░     ░     
               ░                          ░                                            

Batch Obfuscater | V2.1
DevBubba#6642    

"""

print(fade.fire(text))

def main() -> None:
  auto_detect = input('{:<27}: '.format(f"{Fore.YELLOW}[+] AutoDetect .Bat File [Y/N]  {Style.RESET_ALL}"))
  path = ''
  if auto_detect == "Y" or "y":
    os.getcwd()
    for file in glob.glob("*.bat"):
      print(f"{Fore.GREEN}[+] AutoDetected .Bat File - {file}{Style.RESET_ALL}")
      path = file
      
  elif auto_detect == "N" or "n":
    path = input('{:<27}: '.format(f"{Fore.YELLOW}[+] File Path Including (.bat)  {Style.RESET_ALL}"))
    os.getcwd()
    for file in glob.glob(path):
      print(f"{Fore.GREEN}[+] Found .Bat File - {file}{Style.RESET_ALL}")

  else:
    print(f"{Fore.RED}[-] Please Enter A Valid Argument!{Style.RESET_ALL}")
    print(f"{Fore.RED}[-] Exiting...{Style.RESET_ALL}")
    time.sleep(5)
    exit()

  level = int(input('{:<27}: '.format(f'{Fore.YELLOW}[+] Obfuscation Level [1/2]  {Style.RESET_ALL}')))

  confirm = input('{:<27}: '.format(f"{Fore.YELLOW}[+] Are You Sure You Would Like To Obfuscate {file}? [Y/N]  {Style.RESET_ALL}"))

  with open(path, 'r', encoding='utf-8') as f:
    code = f.read()

  if confirm == "Y" or "y":
    if level == 1:
      with open('obfuscated.bat', 'w') as f:
        f.write(Methods.methodOne(code))

    elif level == 2:
      with open('obfuscated.bat', 'wb') as f:
        f.write(Methods.methodTwo(code))
    
    print(f"{Fore.GREEN}[+] Succsesfully Obfuscated {file}!{Style.RESET_ALL}")
    print(f"{Fore.RED}[-] Exiting...{Style.RESET_ALL}")
    time.sleep(5)
    exit()

  if confirm == "N" or "n":
    print(f"{Fore.RED}[-] Cancelled Obfuscation!{Style.RESET_ALL}")
    print(f"{Fore.RED}[-] Exiting...{Style.RESET_ALL}")
    time.sleep(5)
    exit()
    
  else:
    print(f"{Fore.RED}[-] Please Enter A Valid Argument!{Style.RESET_ALL}")
    print(f"{Fore.RED}[-] Exiting...{Style.RESET_ALL}")
    time.sleep(5)
    exit()

class Methods:
    @staticmethod
    def methodOne(code: str) -> str:
        obfuscated = ''
        for line in code.splitlines():
            for char in line:
                if char == '\n':
                    obfuscated += char
                elif char == '%':
                    obfuscated += char
                    while char != '%':
                        char = line[line.index(char) + 1]
                        obfuscated += char
                else:
                    ran_str = ''.join(
                        random.choice(string.ascii_letters)
                        for _ in range(random.randint(5, 15)))
                    obfuscated += f'{char}%{ran_str}%'
        return obfuscated

    @staticmethod
    def methodTwo(code: str) -> bytes:
        obfuscated = bytearray(b'\xFF\xFE\n\r')
        encoded = Methods.methodOne(code)
        code_bytes = bytes(encoded, 'utf-8')
        obfuscated.extend(code_bytes)
        return bytes(obfuscated)




if __name__ == '__main__':
  main()

add this

make it when it prints more than 1 bat file, it lets the user choose between them by typing their index dependent on what order they were printed out

better code for modules errors

try:
    from colorama import Back, Fore, Style
    import glob, os
    import random
    import string
    import time
    import fade
    import os

except ImportError as e:
    missing_module = str(e).split()[-1] # get the name of the missing module from the error message
    if "No module named" in str(e):
        print(f"[-] Error! You don't have the '{missing_module}' module installed to run Batch Obfuscater V2.1. Please install it using pip install {missing_module} and try again.")
    elif "version" in str(e):
        print(f"[-] Error! The version of the '{missing_module}' module installed on your system is not compatible with Batch Obfuscater V2.1. Please upgrade or downgrade to the required version and try again.")
    elif "download" in str(e):
        print(f"[-] Error! There was an issue downloading the '{missing_module}' module required by Batch Obfuscater V2.1. Please check your internet connection and try again.")
    else:
        print("[-] Error! You don't have all the required modules installed to run Batch Obfuscater V2.1. Please open install.bat to fix!")
    time.sleep(5)
    exit()

Issues bbg

Remove the unnecessary import of glob in required_modules.
Change the os.getcwd() to os.chdir(path) to change the working directory.
Fix the Methods.LevelTwo() method to return str instead of bytes.
Fix the Methods.LevelTwo() method to properly create a new obfuscated file.

incorporate this into ur discord

basically people can choose their bat file, level through slash commands and a bot ( u will need to code this ) will reply back in dms with the obfuscated code.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.