prompt shell in window service via python

128 Views Asked by At

I want to prompt up a shell in windows service via python. The following is my code. It runs buy the prompt is running background instead of showing up. Thank you very much!

import win32service
import win32serviceutil
import win32event 
import requests
import sys
import subprocess
import os

class PySvc(win32serviceutil.ServiceFramework):
    _svc_name_ = "ServicePython"  # NET START/STOP the service by the following name
    _svc_display_name_ = "ServicePython Service"  # name in the Service  Control Manager (SCM)
    _svc_description_ = "This service writes stuff to a file"  #  description in the SCM

    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self,args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)

    def SvcDoRun(self):
        import servicemanager   
        self.start()  
        win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)  

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) #tell the SCM 
        win32event.SetEvent(self.hWaitStop)         # fire the stop event
        self.stop()

    def start():
        pass  

    def stop():
        pass 

class MyService(PySvc): 
    def start(self):
        os.system("start cmd.exe /k \"cd /d C:\\ & dir\"") ####this does not show, runs at background only

if __name__ == '__main__':
    sys.argv.append("start")
    win32serviceutil.HandleCommandLine(MyService)
1

There are 1 best solutions below

0
On

Some how I solved the problem. Here are my steps:

  1. install the windows service using the --interactive option.
    If the filename of the above python script is service.py, then install it via "python service.py --interactive install" in cmd. Start the service manually.

  2. Use remote desktop to connect to session 0.
    Window services are displayed to only session 0's users by default. I follow the link to connect to session 0, and the prompt shell is now visible.

Thank you very much.