Pywin32 Windows Service Script Not Connecting with Main Function and Service Unable To Finish Starting?

I’m working on a python app that, among other things, works to block common RCA applications. Because I want it to be able to run on start up and in the background, I figured the best way was to make it into a Windows Service. I know you can do things manually, like schedule the task via task manager, but I want it to run without that user involvement, so I decided to use pywin32.

With that in mind, let me tell you my issue: Installing the python script as a service works fine, you can see it added to the windows service manager, but starting the service is where the error comes in.

Svc_manager.py, which is what controls the service, just continuously tries to call the main function in scamwatch_main.py and is unable to. It times out when starting and then the service stays stuck in “Starting” and I have to kill it from the task manager.

I even tried renaming the main file to see if there was any call confusion since there’s a main function in both files, but that didn’t work. I also tried moving the service code into the main file instead, but that gave me more errors and just overall made everything worse. I’ve also tried restarting my computer after installing the service.

Debugging logs have not helped outside of it staying at “calling main from scamwatch_main.py”. Windows logs simply show that the service has started.

If you start the script up manually from the cmd line, it runs perfectly fine, so it has to be that connection from svg_manager.py, right? I feel like it’s probably something simple that I’m just missing, but I have no idea.

Anyway, here’s the svc_manager.py code:

# this file handles the pywin32 config for using ScamWatch as a service

import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
from scamwatch_main import scamwatch_main
import logging
import os

class SWWinService(win32serviceutil.ServiceFramework):
    _svc_name_ = "ScamWatchService"
    _svc_display_name_ = "ScamWatch Service"

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

        log_dir = 'Log Directory Path'
        os.makedirs(log_dir, exist_ok=True)
        log_file = os.path.join(log_dir, 'ScamWatch.log')

        logging.basicConfig(
            filename=log_file,
            level=logging.DEBUG,
            format='%(asctime)s %(levelname)s: %(message)s'
        )
        logging.info("ScamWatch initialized Successfully")

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)
        logging.info('ScamWatch service stopping')

    def SvcRun(self):
        try:
            servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED,
                                (self._svc_name_, ''))
            
            self.main()
        except Exception as e:
            logging.error(f"Exception in SvcRun: {e}")
            servicemanager.LogErrorMsg(f"Exception in SvcRun: {e}")
            self.SvcStop()
    
    def main(self):
        rc = None
        logging.info('ScamWatch service running')
        while rc != win32event.WAIT_OBJECT_0:
            try:
                logging.info("calling main from scamwatch_main.py")
                scamwatch_main.scamwatch_main()
            except Exception as e:
                logging.error(f"Exception in main loop: {e}")
            rc = win32event.WaitForSingleObject(self.hWaitStop, 3000)
        logging.info('Service stopped by exiting loop in svc_manager!')


if __name__ == '__main__':
    servicemanager.Initialize()
    servicemanager.PrepareToHostSingle(SWWinService)
    servicemanager.StartServiceCtrlDispatcher()

And then here’s my scamwatch_main.py code. Could the admin priv check be messing with it?


# This is the main executable for ScamWatch.
import threading
import time
import sys
import logging
import os
from process_blocking import monitor_process, one_time_connection
from elevate import is_admin, run_as_admin
from port_blocking import block_all_ports

def scamwatch_main():

    logging.info("ScamWatch is running!")

    # Check if in admin mode. If not, restart as admin
    if not is_admin() and "--elevated" not in sys.argv:
        logging.info("Attempting to restart with administrative privileges...")
        if run_as_admin():
            logging.info("Restarted with administrative privileges.")
            sys.exit(0)  # Terminate the current process to restart as admin
        else:
            logging.error("Failed to restart with administrative privileges.")
            sys.exit(1)
    
    try:

        # Check and block common remote connection ports
        logging.info("Blocking remote connection ports if needed...")
        block_all_ports()

        # Begin monitoring processes for common RCA App exes
        logging.info("Now monitoring for RCA applications. Don't worry, you're safe :)")
        monitor_thread = threading.Thread(target=monitor_process)
        monitor_thread.daemon = True
        monitor_thread.start()

    except KeyboardInterrupt:
        logging.info("ScamWatch has been stopped by user!")

    except Exception as e:

        logging.error(f"Something went wrong! Here's the error info: {e}")


# Run this script as an executable, not as a file to import
if __name__ == "__main__":
    scamwatch_main()

It’s a work in progress and needs to be cleaned up, but first priority is just to get the service to work lmao

1

class SWWinService(win32serviceutil.ServiceFramework):
    def SvcRun(self):
    # This is the entry point the C framework calls when the Service is
    # started. Your Service class should implement SvcDoRun().

    

If the SvcRun method is not executed completely, it will always show “Starting” in the Service Manager.

You should start the blocking function in a new thread.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật