我编写了一个作为 Windows 服务运行的 python 脚本来反向转发端口。当使用管理员帐户登录时,该服务可以正常工作。但是当它通过本地系统帐户登录时,该服务仍然运行但不起作用。为什么?
我已将 /python 和 /python/Scripts 添加到系统路径中。以下是我的代码:
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()
此外,我还测试了运行其他命令,例如“date /t”。然后服务就可以通过本地系统帐户记录正常工作了。
他们自己回答吧。通过C#和ssh.net重新实现该功能可以避免该问题。