I am trying to write a python script that executes the following terminal command:
echo -n | openssl s_client -connect {host}:{port} | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > {host}_{port}.cert
If I try to break up the command into arguments to pass to the subprocess.run it does not work (something is run but it does not store the certificate as I would like it to.
Using the below sytax correctly executes the command, however I fear it is not best practice and wanted to understand the correct way for how this should be done:
store_certificate_command = f"echo -n | openssl s_client -connect {host}:{port} | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > {host}_{port}.cert"
subprocess.run(store_certificate_command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
echoandsed? Yourechois equivalent to passingsubprocess.DEVNULLas thestdin. Yoursedcommand is trivially implementable in Python, which can write the results to the file itself. All you really need to run is theopensslcommand.runif you are doing your own plumbing. The object it returns has an attributestdoutwhich is however not a filehandle.