Exemplo n.º 1
0
 def SvcStop(self):
     self.logger.info("IDF SERVICE stop....")
     try:
         pids = win32pdhutil.FindPerformanceAttributesByName("python")
         pids2 = win32pdhutil.FindPerformanceAttributesByName(
             "pythonservice")
         pids.extend(pids2)
         for i in range(len(pids)):
             handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0,
                                           pids[i])
             win32api.TerminateProcess(handle, 0)  # kill by handle
             win32api.CloseHandle(handle)
     except Exception, ex:
         pass
Exemplo n.º 2
0
def killAllProcName(procname):
    """ Terminates _all_ processes with procname. Administrator can
        end processes owned by the system account.
    """
    try:
        win32pdhutil.GetPerformanceAttributes('Process','ID Process',procname)
    except:
        pass

    pids = win32pdhutil.FindPerformanceAttributesByName(procname)
    try:
        pids.remove(win32api.GetCurrentProcessId())
    except ValueError:
        pass

    success = 1
    if len(pids) > 0:
        priv = win32security.LookupPrivilegeValue(None, win32con.SE_DEBUG_NAME)
        newpriv = [(priv, win32con.SE_PRIVILEGE_ENABLED)]
        flags = ntsecuritycon.TOKEN_ADJUST_PRIVILEGES | ntsecuritycon.TOKEN_QUERY
        htoken = win32security.OpenProcessToken(win32api.GetCurrentProcess(), flags)
        win32security.AdjustTokenPrivileges(htoken, False, newpriv)
        result = []
        for p in pids:
            try:
                handle = win32api.OpenProcess(True, win32con.PROCESS_TERMINATE, p)
                win32api.TerminateProcess(handle, -1)
                win32api.CloseHandle(handle)
            except win32api.error:
                success = 0

    return success
Exemplo n.º 3
0
def cmd_kill(ensoapi, process_name):
    """ Kills the processes with the given name """
    pids = win32pdhutil.FindPerformanceAttributesByName(process_name)
    for p in pids:
        handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0, p)
        win32api.TerminateProcess(handle, 0)
        win32api.CloseHandle(handle)
Exemplo n.º 4
0
def isrunning(processname):
    try:
        return len(
            win32pdhutil.FindPerformanceAttributesByName(processname,
                                                         bRefresh=1)) > 0
    except:
        return False
Exemplo n.º 5
0
def killProcName(procname):
    # Change suggested by Dan Knierim, who found that this performed a
    # "refresh", allowing us to kill processes created since this was run
    # for the first time.
    try:
        win32pdhutil.GetPerformanceAttributes('Process', 'ID Process', procname)
    except:
        pass

    pids = win32pdhutil.FindPerformanceAttributesByName(procname)

    # If _my_ pid in there, remove it!
    try:
        pids.remove(win32api.GetCurrentProcessId())
    except ValueError:
        pass

    if len(pids) == 0:
        result = "Can't find %s" % procname
    elif len(pids) > 1:
        result = "Found too many %s's - pids=`%s`" % (procname, pids)
    else:
        handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0, pids[0])
        win32api.TerminateProcess(handle, 0)
        win32api.CloseHandle(handle)
        result = ""

    return result
Exemplo n.º 6
0
 def getpidsforprocess(processname):
     import win32pdh, win32pdhutil
     win32pdh.EnumObjects(None, None, 0, 1)  # refresh internal cache
     pids = win32pdhutil.FindPerformanceAttributesByName(processname,
                                                         "Process",
                                                         "ID Process")
     return pids
Exemplo n.º 7
0
 def mem(t='', p=1):
     global last_mem
     last_mem = win32pdhutil.FindPerformanceAttributesByName(
         "python", counter="Virtual Bytes")
     if p:
         print(t, last_mem,
               '%.3fMb' % (int(long(wmi_mem()) // 1024.0) / 1000.))
     return last_mem
Exemplo n.º 8
0
def Kill_Process(process):
    #get process id’s for the given process name
    pids = win32pdhutil.FindPerformanceAttributesByName(process)
    for p in pids:
        handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0,
                                      p)  #get process handle
        win32api.TerminateProcess(handle, 0)  #kill by handle
        win32api.CloseHandle(handle)  #close api
Exemplo n.º 9
0
def _GetMozillaPIDs(exename):
    if sys.platform.startswith("win"):
        win32pdh.EnumObjects(None, None, 0, 1)  # refresh internal cache
        pids = win32pdhutil.FindPerformanceAttributesByName(
            exename, "Process", "ID Process")
        return pids
    else:
        raise "Don't know how to list the mozilla PIDs yet on this OS."
Exemplo n.º 10
0
    def prepare_for_run(self, config, year, check_tcw_process=False):
        """before calling travel model macro, check if transcad GUI is running, 
        if not, try to start transcad binary process"""
        ## TODO: TransCAD COM server is very picky about tcw.exe process in memory
        ## as of April 2007, a tcw process started by python won't work
        ## so manually start TransCAD program is needed before running this script

        set_project_ini_file(config, year)
        if not check_tcw_process:
            return

        cmdline = config['transcad_binary']
        head, tail = os.path.split(cmdline)
        procname, ext = os.path.splitext(tail)  #tcw

        kill_process = False
        start_program = False
        tc_program_classname = "tcFrame"  #ClassName for TransCAD program
        try:
            hwnd = win32gui.FindWindow(tc_program_classname, None)
        except:
            start_program = True  # No Transcand Window found, we'll need to start TransCAD program
        else:
            try:
                #first check if tcw process is in memory
                win32pdhutil.GetPerformanceAttributes('Process', 'ID Process',
                                                      procname)
                pids = win32pdhutil.FindPerformanceAttributesByName(procname)
                for pid in pids:
                    win32process.TerminateProcess(pid)
                start_program = True
            except:
                raise RuntimeError, "Unable to kill TransCAD process in memory"

        ##transcad not started, try to start it
        if start_program:
            try:
                pass
                cmdline = win32api.GetShortPathName(cmdline)
                cmdline = cmdline + " -q"
                os.system('start /B "start TransCAD" ' +
                          cmdline)  #start TransCAD in background
                time.sleep(9)
                #procHandles = win32process.CreateProcess(None, cmdline, None, None, 0, 0, None, None,
                #win32process.STARTUPINFO())
                #self.hProcess, hThread, PId, TId = procHandles
            except:
                logger.log_error(
                    "Unable to start TransCAD in %s; it must be running to invoke travel model macro."
                    % cmdline)
                sys.exit(1)
Exemplo n.º 11
0
 def openProcess(self, procName):
     pids = win32pdhutil.FindPerformanceAttributesByName(
         procName, None, None, win32pdh.PDH_FMT_LONG, None, True)
     print(pids)
     if len(pids) == 0:
         print("fail")
         return False
     elif len(pids) > 0:
         self.PID = pids[0]
         self.procHandle = self.kernel32.OpenProcess(
             privileges['PROCESS_ALL_ACCESS'], False, self.PID)
         self.baseAddr = win32process.EnumProcessModulesEx(
             self.procHandle)[0]
         return True
def TerminateAllProcesses(process_name):
    """Helper function to terminate all processes with the given process name

  Args:
    process_name: String containing the process name, i.e. "firefox"
  """

    # Get all the process ids of running instances of this process, and terminate them.
    try:
        pids = win32pdhutil.FindPerformanceAttributesByName(
            process_name, counter="ID Process")
        for pid in pids:
            TerminateProcess(pid)
    except:
        # Might get an exception if there are no instances of the process running.
        pass
Exemplo n.º 13
0
def haveProc(procname):
    """ Tests if procname is running. """
    try:
        win32pdhutil.GetPerformanceAttributes('Process', 'ID Process', procname)
    except:
        pass

    pids = win32pdhutil.FindPerformanceAttributesByName(procname)
    try:
        pids.remove(win32api.GetCurrentProcessId())
    except ValueError:
        pass

    if len(pids) == 0:
        return 0
    else:
        return 1
    def TerminateAllProcesses(self, *process_names):
        """Helper function to terminate all processes with the given process name

        Args:
            process_name: String or strings containing the process name, i.e. "firefox"
        """
        for process_name in process_names:
            # Get all the process ids of running instances of this process, and terminate them.
            try:
                # refresh list of processes
                win32pdh.EnumObjects(None, None, 0, 1)
                pids = win32pdhutil.FindPerformanceAttributesByName(process_name, counter="ID Process")
                for pid in pids:
                    self.TerminateProcess(pid)
            except:
                # Might get an exception if there are no instances of the process running.
                continue
Exemplo n.º 15
0
def get_pids(name, minimun_pid=0):
    """Get all the pids matching name, exclude any pids below minimum_pid."""
    if os.name == 'nt' or sys.platform == 'cygwin':
        #win32pdhutil.ShowAllProcesses()  #uncomment for testing
        pids = win32pdhutil.FindPerformanceAttributesByName(name)

    else:
        # get_pids_cmd = ['ps', 'ax']
        # h = killableprocess.runCommand(get_pids_cmd, stdout=subprocess.PIPE, universal_newlines=True)
        # h.wait(group=False)
        # data = h.stdout.readlines()
        data = getoutput(['ps', 'ax']).splitlines()
        pids = [
            int(line.split()[0]) for line in data if line.find(name) is not -1
        ]

    matching_pids = [m for m in pids if m > minimun_pid]
    return matching_pids
def ProcessesWithNameExist(process_name):
    """Returns true if there are any processes running with the
     given name.  Useful to check whether a Firefox process is still running

  Args:
    process_name: String containing the process name, i.e. "firefox"

  Returns:
    True if any processes with that name are running, False otherwise.
  """

    try:
        pids = win32pdhutil.FindPerformanceAttributesByName(
            process_name, counter="ID Process")
        return len(pids) > 0
    except:
        # Might get an exception if there are no instances of the process running.
        return False
Exemplo n.º 17
0
def kill_processes(process_name):
    if sys.platform != 'win32':
        raise NotImplementedError('Implement me!')
    try:
        import win32api
        import win32pdhutil
        import win32con
    except ImportError:
        log.warn('Python win32 is required for killing processes.')
        return

    pids = win32pdhutil.FindPerformanceAttributesByName(
        process_name, counter="ID Process")

    for pid in pids:
        handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE, False, pid)
        win32api.TerminateProcess(handle, -1)
        win32api.CloseHandle(handle)
Exemplo n.º 18
0
def get_pids(name, minimun_pid=0):
    """Get all the pids matching name, exclude any pids below minimum_pid."""
    if sys.platform == 'win32':
        import win32api, win32pdhutil, win32con
        #win32pdhutil.ShowAllProcesses()  #uncomment for testing
        pids = win32pdhutil.FindPerformanceAttributesByName(name)

    else:
        get_pids_cmd = ['ps', 'ax']
        h = killableprocess.runCommand(get_pids_cmd,
                                       stdout=subprocess.PIPE,
                                       universal_newlines=True)
        h.wait()
        data = h.stdout.readlines()
        pids = [
            int(line.split()[0]) for line in data if line.find(name) is not -1
        ]

    matching_pids = [m for m in pids if m > minimun_pid and m != os.getpid()]
    return matching_pids
Exemplo n.º 19
0
        def _GetProcessIdByName(self, name):
            """
            Try and get pid for a process by name.
            """

            try:
                win32pdhutil.GetPerformanceAttributes('Process', 'ID Process',
                                                      name)
            except:
                sys.stdout.write("Memory: Unable to locate process [%s]\n" %
                                 name)
                raise

            pids = win32pdhutil.FindPerformanceAttributesByName(name)

            # If _my_ pid in there, remove it
            try:
                pids.remove(win32api.GetCurrentProcessId())
            except ValueError:
                pass

            return pids[0]
    def ProcessesWithNameExist(self, *process_names):
        """Returns true if there are any processes running with the
            given name.  Useful to check whether a Browser process is still running

        Args:
            process_name: String or strings containing the process name, i.e. "firefox"

        Returns:
            True if any processes with that name are running, False otherwise.
        """

        for process_name in process_names:
            try:
                # refresh list of processes
                win32pdh.EnumObjects(None, None, 0, 1)
                pids = win32pdhutil.FindPerformanceAttributesByName(process_name, counter="ID Process")
                if len(pids) > 0:
                    return True 
            except:
                # Might get an exception if there are no instances of the process running.
                continue
        return False
Exemplo n.º 21
0
import win32pdhutil, win32pdh, wmi, win32api, win32process
c = wmi.WMI(
)  #<-- this takes a ling time to set up. but after this initialiseation it is very quick

#to get a process's attributes you have to name them
a = str(
    win32pdhutil.FindPerformanceAttributesByName("explorer",
                                                 counter="Virtual Bytes"))

print "Explorer virtual Bytes: ", a  #will give you virtual bytes

#to get system you do it slightly differently
z = str(win32pdhutil.GetPerformanceAttributes("Memory", "Page Faults/sec"))

print "memory Page Faults", z  # will give you memory page faults a second

#Now here is the fun bit to get the process's cpu-usage is very difficult
# it is not simple like i thought this
cpu = str(
    win32pdhutil.FindPerformanceAttributesByName("explorer",
                                                 counter="% Processor Time"))
print "Explorer CPU Time is: ", cpu

#after searching high and low on the internet i finally found how to do it using WMI (so windows only)
process_info = {}
for p in c.Win32_PerfRawData_PerfProc_Process(name='explorer'):
    n1, d1 = long(p.PercentProcessorTime), long(p.Timestamp_Sys100NS)
    n0, d0 = process_info.get(id, (0, 0))

    try:
        percent_processor_time = (float(n1 - n0) / float(d1 - d0)) * 100.0
Exemplo n.º 22
0
                    disk.Caption, "%.1fGb free %.1fGb avail -- %0.2f%% free" %
                    ((long(disk.FreeSpace)) * 1.0e-9,
                     (long(disk.Size)) * 1.0e-9,
                     (100.0 * long(disk.FreeSpace) / long(disk.Size))))
        except:
            pass

    import win32process
    current_id = win32process.GetCurrentProcessId()

    def wmi_mem():
        c = wmi.WMI(find_classes=False)
        for process in c.Win32_Process(['WorkingSetSize'], Handle=current_id):
            return process.WorkingSetSize

    last_mem = win32pdhutil.FindPerformanceAttributesByName(
        "python", counter="Virtual Bytes")
    last_wmi = wmi_mem()

    def mem(t='', p=1):
        global last_mem
        last_mem = win32pdhutil.FindPerformanceAttributesByName(
            "python", counter="Virtual Bytes")
        if p:
            print(t, last_mem,
                  '%.3fMb' % (int(long(wmi_mem()) // 1024.0) / 1000.))
        return last_mem

    def dmem(t='', p=1):
        lmem = last_mem
        nmem = mem(p=0)
        ret = [(nmem[n] - lmem[n]) * 1.0e-3
Exemplo n.º 23
0
        tray_icon_path = '"' + os.path.join(BASEDIR, 'lib',
                                            'TrayIcon.pyw') + '"'
        try:

            regpath = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run'
            key = _winreg.OpenKeyEx(_winreg.HKEY_LOCAL_MACHINE, \
                    regpath, 0, _winreg.KEY_SET_VALUE)
            _winreg.DeleteKey(key, 'AutomationTrayIcon')
            _winreg.CloseKey(key)
        except WindowsError:
            _winreg.CloseKey(key)

        print "Killing automation tray processes"
        try:
            #get process id's for the given process name
            pids = win32pdhutil.FindPerformanceAttributesByName('pythonw')

            for p in pids:
                print "Killing: %s" % (str(p))
                #get process handle
                handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0, p)
                win32api.TerminateProcess(handle, 0)  #kill by handle
                win32api.CloseHandle(handle)  #close api
            print "success!"
            #Remove the machine entry from deathstar
            host_ip, sftp, lines = run_cmd('ipconfig')
            remove_machine_registration(host_ip, sftp, lines)
        except:
            print "failed to remove tray icon"

################################################################################