I write a python script used to reversely forward a port. I use pywin32 to convert the python codes as a win10 service. The service runs ok when python version is 3.10. However, after I upgrade the python from version 3.10 to 3.12, The service stop immediatly everytime I start it. I don't know why. Can anyone give some suggestions? Thanks a lot. The following is my python codes:
import time
import sys
import subprocess as sp
import win32serviceutil # ServiceFramework and commandline helper
import win32service # Events
import servicemanager # Simple setup and logging
class MyService:
def stop(self):
self.running = False
def run(self):
rport=55009
cmd=f'ssh -fNR {rport}:127.0.0.1:3389 username@remotehost -p 22'
cmd1='ssh -tt username@remotehost -p 22 \"netstat -tpa | grep \'**:{} **\'\"'.format(rport)
while True:
a=sp.run(cmd1,capture_output=True,shell=True).stdout.decode("utf-8")
# print('one turn')
if f":{rport}" not in a:
try:
p=sp.Popen(cmd,shell=True)
p.wait(2)
except sp.TimeoutExpired:
p.kill()
except:
print('execution failed')
elif not "ESTABLISHED" in a:
cmd2="\"ps aux | grep '**xiaoya**'| awk '{print $2}' | xargs -r kill\""
cmd2="ssh -tt username@remotehost -p 22 "+cmd2
try:
a=sp.run(cmd2,shell=True)
p=sp.Popen(cmd,shell=True)
p.wait(2)
except sp.TimeoutExpired:
p.kill()
except:
print('execution failed')
time.sleep(5*1)
servicemanager.LogInfoMsg("Service running...")
class MyServiceFramework(win32serviceutil.ServiceFramework):
_svc_name_ = 'autossh1'
_svc_display_name_ = 'autossh1'
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
self.service_impl.stop()
self.ReportServiceStatus(win32service.SERVICE_STOPPED)
def SvcDoRun(self):
self.ReportServiceStatus(win32service.SERVICE_START_PENDING)
self.service_impl = MyService()
self.ReportServiceStatus(win32service.SERVICE_RUNNING)
# Run the service
self.service_impl.run()
def init():
if len(sys.argv) == 1:
servicemanager.Initialize()
servicemanager.PrepareToHostSingle(MyServiceFramework)
servicemanager.StartServiceCtrlDispatcher()
else:
win32serviceutil.HandleCommandLine(MyServiceFramework)
if __name__ == '__main__':
init()
This appears to be a bug with LogInfoMsg and Python 3.12.
As a workaround, try LogMsg with the info type:
servicemanager.LogMsg( servicemanager.EVENTLOG_INFORMATION_TYPE, 0xF000, ( "Service running...", "" ) )