简体   繁体   中英

How to Keep terminating a program using a Windows Service in Python?

I have a Python Script that creates a Windows Service and checks whether Powershell is running using psutil . However there is an issue in the code that I can't figure out.

Either the Service starts and stops immediately ( like in the current state ) or it starts but does not terminate the program. ( if for example else: break is changed to else: continue )

I want the service to run indefinitely (until a service stop command is issued ) and constantly check whether powershell.exe has been started and terminate it.

I also wanted to expand to if 'powershell' or 'powershell_ise' in (p.name() for p in psutil.process_iter()): but that for some reason is always True even if powershell is not started.

Here is the part of the code that is relevant:

def SvcDoRun(self):
        
        while True:
               
            result = win32event.WaitForSingleObject(self._stop_event, 1000)
            
            if result == win32event.WAIT_OBJECT_0:
                break 
              
            else: 
                if 'powershell' in (p.name() for p in psutil.process_iter()):
                    os.system("taskkill /f /t /im powershell.exe") 
                else:
                    break

Break in the else would mean, that if there is no powershell process, you would end the service. I don't think that is what you intend. Either there should be a continue or no else block altogether.

the condition

if 'powershell' or 'powershell_ise' in (p.name() for p in psutil.process_iter()):

is always True, because bool('powershell) is always True and the operator precedence is as

if 'powershell' or ('powershell_ise' in ['notepad']):

You can use set intersection

if {'powershell', 'powershell_ise'} & set(psutils.process_iter()):

You could try psutil.kill:

for proc in psutil.process_iter():
    if proc.name() in ('powershell', 'powershell_ise'):
        proc.kill()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM