Search code examples
pythonwindowsbatch-filenat

Start and stop command periodically, in Windows


I'm using this Python program to connect to a VPS and create a NAT tunnel.

My Home Windows PC <-- My Linux VPS <-- The internet

So now, even if my PC is behind a NAT, one can access the publicly exposed VPS and it will re-reoute the request to the Python script which will then re-reoute it to my home PC.

To launch the Python script on my home PC I use this simple batch file:

cd "%~dp0"
python.exe natsrv.py --mode client --secret hunter1 --local 127.0.0.1:8080 --admin myvps.ip.here:8999

This starts-up the Python script which never stops: it goes on indefinitely until I close the batch window. Very good.

Here's the problem: if the tunnel is unused for a few minutes, it silently stops serving requests. This won't stop the execution of the Python script, which will keep on going... it just stops working, but stays on.

I could fix this in the Python script but it's quite complicated and I don't want to mess with it: I want a much simpler solution.

The batch file should stop the execution of python.exe and start it again, every 5 minutes. How can I do this?

The SLEEP and GOTO commands or anything similar that I've tried, will wait before the Python script ends before being triggered!

I need to tell the batch script (or any entity controlling it) that python.exe must be stopped and restarted every 5 minutes, regardless of wether it's still running. Is it possible?


Solution

  • You can write a python script to run natsrv.py with the same command line arguments as a child process. Terminate it after 5 minutes and repeat.

    mynatsrv.py

    import subprocess as subp
    import sys
    import time
    
    if __name__ == "__main__":
        while True:
            p = subp.Popen(["python.exe", "natsrv.py"] + sys.argv[1:])
            time.sleep(5*60)
            p.terminate()
            p.wait()
    

    and the command line is

    cd "%~dp0"
    python.exe mynatsrv.py --mode client --secret hunter1 --local 127.0.0.1:8080 --admin myvps.ip.here:8999