Search code examples
python-3.xsubprocesstestssl.sh

Terminating a Python process based on the subprocess module once the process is finished


Overview: I am trying to develop a web-based SSL Scanner where as backend I am executing the testssl.sh script in the ubuntu distro by means of python code using the subprocess module.

Doubt: The python code that I have written (as mentioned below) keeps on executing even after the testssl.sh script has finished scanning a server configuration. I will be highly obliged if anyone could tell me as to how can I modify the code so that the code execution stops once the testssl.sh script has also finished execution.

As of now I am taking the input from the console as I am yet to work on the frontend and API development, and since it is my first time posting on this forum, I apologise for breaking any community guidelines unknowingly. And, I will be really grateful if anyone can help me with this issue as to how should I tackle this.

Code:

import subprocess

# Opens the actual path to the ubuntu.exe file and executes the ubuntu.exe file
process = subprocess.Popen(
    [r"E:\WSL\Ubuntu_2004\Ubuntu\Ubuntu_2004.2021.825.0_x64\ubuntu.exe"],
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE
)
# Change the directory where the testssl.sh script is stored
process.stdin.write(b"cd /mnt/e/WSL/Ubuntu_2004/testssl.sh-3.1dev\n")
process.stdin.flush()

# Get the Hostname from the user
hostname = # input("Enter the Hostname to test: ")

# Execute the testssl.sh script with the Hostname and redirect the output to a folder named scans as a HTML file

command = f"./testssl.sh --htmlfile ../reports/scans --openssl-timeout 5 {hostname}\n"
process.stdin.write(command.encode())
process.stdin.flush()

# process.wait(timeout=****)

I have tried using the process.wait(timeout=****), but the problem with this approach is that it is impossible for me to determine a fixed amount of timefor the timeout, and either of the two things happen:

(1) If the server configuration is not that complex and there are not many IP addresses associated then the testssl.sh script finishes within 5 to 7 minutes maximum. Thenif the timeout value is set to somewhat around 800 or 900 (seconds), which is more than 5 to 7 minutes then the program keeps on running in VSCode and after the timeout value it throws an exception.

OR,

(2) If the server configuration is complex and there multiple IP addresses associated then the testssl.sh script takes a lot of time i.e. more than the timeout(800 or 900 seconds) value. Then, in that I also get a timeout exception in the console and the testssl.sh script remains executed incompletely with respect to scanning the server configuration.


Solution

  • Have you tried reading from process.stdout until it EOFs? That will mean that the other process has ended. You then can exit your program.