Download a sites certificates with openssl

The following snippet can be used to download all the CA certificates from a site, into seperate .crt files. The file name will be the last CN part from the issued information.

openssl s_client -connect $SITE:443 -showcerts \
        </dev/null 2>/dev/null | \
	awk '/^ [0-9] s:/,/^[-]+END CERTIFICATE/' | \
	csplit -q -z -f cert - '/^ [0-9] s:/' '{*}'
for file in cert*; do \
	name="$(awk -F= '/^ [0-9] s:/ {gsub(/[^A-Za-z0-9.]/, "", $NF); print $NF".crt"}' "${file}")"; \
	awk '/^[-]+BEGIN CERTIFICATE/,/^[-]+END CERTIFICATE/' "${file}" > "${name}"; \
	rm "${file}"; \

Example, if running the above with

↳ openssl s_client -connect $SITE:443 -showcerts         </dev/null 2>/dev/null | awk '/^ [0-9] s:/'
 0 s:/
 1 s:/C=US/O=Let's Encrypt/CN=Let's Encrypt Authority X3

Two certificate files will be created:

↳ ls *.crt  LetsEncryptAuthorityX3.crt