How can I stop a program's execution with pyth

2019-07-21 19:47发布

问题:

I use a program (on Windows), whose name I won't disclose, that can be opened from the command line without going through any authentication. I'm trying to create some security to prevent others from accessing it this way.

I plan on replacing the built-in binary for this program with a batch file with a first line that points to my own authentication system (implemented in python, compiled to .exe with py2exe), and the second line to the command that opens the program.

My original plan was to have my script (auth.py) stop the batch file from executing the second line if authentication failed with something like this:

if not authenticated:
    print('Authentication failed')
    sys.exit(1)
else:
    print('Successfully authenticated!')

I had counted on sys.exit(1) to do this, and I didn't bother testing it out until I was done developing the script. Now I realize that sys.exit only exits the python process.

I either need a way to stop the batch process FROM the python script, or a way for the batch to detect the exit code from auth.py (1 if failed, 0 if passed) and execute the other program only if the exit code is 0 from there.

If anyone could give me any suggestions or help of any sort, I would really appreciate it. Thanks!

回答1:

Use subprocess to call the program on successful authentication. So your python script would launch the program, not a batch file.

if not authenticated:
    print('Authentication failed')
    sys.exit(1)
else:
    print('Successfully authenticated!')
    proc = subprocess.Popen([program])

Please note, if the user has permission to start the program from within a python or batch script, nothing is stopping them from accessing it directly. This will prevent no one from accessing the program; save maybe the extreme un-technical.



回答2:

You could do something really complicated to try and find the parent PID of the Python process and kill that or you could just check the %ERRORLEVEL% in your batch file. Something like:

python auth.py
if %ERRORLEVEL% neq 0 exit /B 1


回答3:

I found these two methods hope these might help
http://metazin.wordpress.com/2008/08/09/how-to-kill-a-process-in-windows-using-python/
http://code.activestate.com/recipes/347462-terminating-a-subprocess-on-windows/