def test_cmdline(self): sys_value = re.sub('[ ]+', ' ', win32api.GetCommandLine()).strip() psutil_value = ' '.join(psutil.Process().cmdline()) if sys_value[0] == '"' != psutil_value[0]: # The PyWin32 command line may retain quotes around argv[0] if they # were used unnecessarily, while psutil will omit them. So remove # the first 2 quotes from sys_value if not in psutil_value. # A path to an executable will not contain quotes, so this is safe. sys_value = sys_value.replace('"', '', 2) self.assertEqual(sys_value, psutil_value)
def __init__(self, CommandLine=None): if CommandLine == None: CommandLine = win32api.GetCommandLine() argv_count = ctypes.c_int() self.cmd_string = ctypes.c_wchar_p(CommandLine) CommandLineToArgvW = ctypes.windll.shell32.CommandLineToArgvW self.array_memory_address = CommandLineToArgvW( self.cmd_string, ctypes.byref(argv_count)) match_array_type = ctypes.c_wchar_p * argv_count.value self.raw_result = match_array_type.from_address( self.array_memory_address) self.result = [arg for arg in self.raw_result] self.argv = self.result[:]
def test_cmdline(self): sys_value = re.sub(' +', ' ', win32api.GetCommandLine()).strip() psutil_value = ' '.join(psutil.Process().cmdline()) self.assertEqual(sys_value, psutil_value)
continue cprint("Please Choose And Exploit\n" \ "\t ---------------------------------------------------\n\n" "Do note that you may also add your own moduels!\n" "[ * ] - >") continue #Powershell Module #scripts = './data/scripts/Modules/PowerShell' # Need to create a listing for all the available scripts for that specific modules #MODULE_DIR = './data/scripts/Modules/PowerShell/' Dur_Hur = "ps {}.format("MODULE_DIR") try: print(winapi.GetCommandLine(Dur_Hur)) except Exception as e: print("{-} Did Not Work:\n{} [~]".format(e)) except KeyboardInterrupt: choice = str(input("[ + ] Would you like to exit? [ + ]\n->")).lower() if choice != "y": print("Ight Den") return if choice == 'y': print([!!] Cya! [!!]") sys.exit(1)
def ProcessArgs(self, args, dde=None): # If we are going to talk to a remote app via DDE, then # activate it! if len(args) < 1 or not args[ 0]: # argv[0]=='' when started without args, just like Python.exe! return i = 0 while i < len(args): argType = args[i] i += 1 if argType.startswith('-'): # Support dash options. Slash options are misinterpreted by python init # as path and not finding usually 'C:\\' ends up in sys.path[0] argType = '/' + argType[1:] if not argType.startswith('/'): argType = win32ui.GetProfileVal("Python", "Default Arg Type", "/edit").lower() i -= 1 # arg is /edit's parameter par = i < len(args) and args[i] or 'MISSING' if argType in ['/nodde', '/new', '-nodde', '-new']: # Already handled pass elif argType.startswith('/goto:'): gotoline = int(argType[len('/goto:'):]) if dde: dde.Exec("from pywin.framework import scriptutils\n" "ed = scriptutils.GetActiveEditControl()\n" "if ed: ed.SetSel(ed.LineIndex(%s - 1))" % gotoline) else: from . import scriptutils ed = scriptutils.GetActiveEditControl() if ed: ed.SetSel(ed.LineIndex(gotoline - 1)) elif argType == "/edit": # Load up the default application. i += 1 fname = win32api.GetFullPathName(par) if not os.path.isfile(fname): # if we don't catch this, OpenDocumentFile() (actually # PyCDocument.SetPathName() in # pywin.scintilla.document.CScintillaDocument.OnOpenDocument) # segfaults Pythonwin on recent PY3 builds (b228) win32ui.MessageBox( "No such file: %s\n\nCommand Line: %s" % (fname, win32api.GetCommandLine()), "Open file for edit", win32con.MB_ICONERROR) continue if dde: dde.Exec("win32ui.GetApp().OpenDocumentFile(%s)" % (repr(fname))) else: win32ui.GetApp().OpenDocumentFile(par) elif argType == "/rundlg": if dde: dde.Exec( "from pywin.framework import scriptutils;scriptutils.RunScript(%r, %r, 1)" % (par, ' '.join(args[i + 1:]))) else: from . import scriptutils scriptutils.RunScript(par, ' '.join(args[i + 1:])) return elif argType == "/run": if dde: dde.Exec( "from pywin.framework import scriptutils;scriptutils.RunScript(%r, %r, 0)" % (par, ' '.join(args[i + 1:]))) else: from . import scriptutils scriptutils.RunScript(par, ' '.join(args[i + 1:]), 0) return elif argType == "/app": raise RuntimeError( "/app only supported for new instances of Pythonwin.exe") elif argType == '/dde': # Send arbitary command if dde is not None: dde.Exec(par) else: win32ui.MessageBox( "The /dde command can only be used\r\nwhen Pythonwin is already running" ) i += 1 else: raise ValueError("Command line argument not recognised: %s" % argType)
import win32api as api import win32con as con for disk in "CDEF": F = api.GetDiskFreeSpace(disk + ":") rest = F[0] * F[1] * F[2] / 1e9 total = F[0] * F[1] * F[3] / 1e9 print("Rest:", rest, "G", "Total:", total, "G") print(api.GetComputerName()) print(api.GetConsoleTitle()) print(api.GetCommandLine()) print(api.GetCursorPos()) print(api.GetDomainName()) print(api.GetEnvironmentVariable('path')) print(api.GetFileAttributes('.')) print(api.GetFileVersionInfo('C:\\windows\\system32\\cmd.exe', "\\")) print(api.GetFullPathName('.')) print(api.GetLocalTime()) print(api.GetLogicalDriveStrings().replace('\x00', ' ')) print(api.GetLogicalDrives()) print(api.GetLongPathName('C:')) print(api.GetModuleFileName(0)) print(api.GetNativeSystemInfo()) print(hex(api.GetSysColor(con.COLOR_WINDOW))) print(api.GetSystemDirectory()) print(api.GetSystemInfo()) print(api.GetSystemMetrics(con.SM_CXSCREEN)) print(api.GetSystemTime()) print(api.GetTickCount()) # print(api.GetTimeZoneInformation()) print(api.GetUserDefaultLangID()) print(api.GetUserName())
from ctypes.wintypes import BOOL from ctypes import * import win32process import pywintypes import win32event import win32job import win32con import win32api import sys import os #### Params DESKTOP_NAME = 'UniqueDesktop-%s' % os.getpid() commandLine = win32api.GetCommandLine() splittedCommandLine = filter(lambda x: len(x) != 0, commandLine.split(' ')) if len(splittedCommandLine) < 3: print 'Usage:\n\tpython %s <child process command line>' % os.path.basename( sys.argv[0]) sys.exit(10) childCmdLine = ' '.join(splittedCommandLine[2:]) #### Windows API definitions GENERIC_ALL = 0x10000000 class SECURITY_ATTRIBUTES(Structure): _fields_ = [("Length", c_ulong), ("SecDescriptor", c_void_p), ("InheritHandle", BOOL)]
# Keep this as short as possible, cos error output is only redirected if # this runs OK. Errors in imported modules are much better - the messages go somewhere (not any more :-) import sys import os import win32api import win32ui if not sys.argv: # Initialize sys.argv from commandline. When sys.argv is empty list ( # different from [''] meaning "no cmd line arguments" ), then C # bootstrapping or another method of invocation failed to initialize # sys.argv and it will be done here. ( This was a workaround for a bug in # win32ui but is retained for other situations. ) argv = win32api.CommandLineToArgv(win32api.GetCommandLine()) sys.argv = argv[1:] if os.getcwd() not in sys.path and "." not in sys.path: sys.path.insert(0, os.getcwd()) # You may wish to redirect error output somewhere useful if you have startup errors. # eg, 'import win32traceutil' will do this for you. # import win32traceutil # Just uncomment this line to see error output! # An old class I used to use - generally only useful if Pythonwin is running under MSVC # class DebugOutput: # softspace=1 # def write(self,message): # win32ui.OutputDebug(message) # sys.stderr=sys.stdout=DebugOutput()
# create a startup item inside the registry hive, so our program starts on startup. import win32api as winapi try: print(winapi.GetCommandLine(" REG ADD HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce\\Albert")) print(winapi.GetCommandLine("REG ADD HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce /v Albert /t REG_MULTI_SZ /f"))
def persist(self, persist): """Add/Remove persistence to reboots by adding a registry key entry which autoruns a vbs script on boot. The vbs script is required in order to run this component silently and is created/removed during this method. This method is automatically called to add persistence during initialisation and remove persistence during the kill routine. @param persist: whether to add or remove persistence """ dir_name = os.path.dirname(os.path.abspath(__file__)) vbs_script_file = os.path.join(dir_name, "data.vbs") if persist: if not os.path.exists(vbs_script_file): curr_file = win32api.GetModuleFileName(0) target_exe = os.path.basename(curr_file) if target_exe == "python.exe": logging.debug( "Running as python script, adding args to persistence script." ) curr_file = win32api.GetCommandLine() vbs_script = open(vbs_script_file, "w") # Windows doesn't like it when something being executed using the autorun registry key being used here # modifies the registry, so the '-r' argument is passed to this script to disable the persistence # adding routine on bootup. vbs_script.write( 'Dim WShell\nSet WShell = CreateObject("Wscript.Shell")\nWShell.Run "{0} -r", 0\nSet WShell = Nothing' .format(curr_file)) # nopep8 vbs_script.close() startup_script = "wscript \"{0}\"".format(vbs_script_file) curr_script = None try: key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, self.PERSISTENCE_KEY, 0, win32con.KEY_QUERY_VALUE) curr_script = win32api.RegQueryValueEx( key, self.REG_KEY_ENTRY) win32api.RegCloseKey(key) except Exception as e: logging.exception("Unhandled Exception: {0}".format(e)) # if curr_script is None (no value) or incorrect, replace with correct one if startup_script != curr_script: logging.debug( "Adding {0} to run on startup...".format(curr_file)) logging.debug( "Script executed by registry key on boot: {0}".format( startup_script)) try: key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, self.PERSISTENCE_KEY, 0, win32con.KEY_SET_VALUE) win32api.RegSetValueEx(key, self.REG_KEY_ENTRY, 0, win32con.REG_SZ, "{0}".format(startup_script)) win32api.RegCloseKey(key) except Exception as e: logging.exception("Unhandled Exception: {0}".format(e)) else: logging.debug("Removing from startup...") if os.path.exists(vbs_script_file): logging.debug("Removing vbs script.") try: os.remove(vbs_script_file) except Exception as e: logging.exception("Unhandled Exception: {0}".format(e)) try: key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, self.PERSISTENCE_KEY, 0, win32con.KEY_SET_VALUE) win32api.RegDeleteValue(key, self.REG_KEY_ENTRY) win32api.RegCloseKey(key) except Exception as e: logging.exception("Unhandled Exception: {0}".format(e))