This command allows you to extract all SSL certificate’s chain from an URL. In order to use it, replace <server_url> with the server address you want to process:
openssl s_client -showcerts -verify 5 -connect <server_URL>:443 < /dev/null | awk '/BEGIN/,/END/{ if(/BEGIN/){a++}; out="cert"a".pem"; print >out}' for cert in *.pem; do newname=$(openssl x509 -noout -subject -in $cert | sed -n 's/^.*CN=\(.*\)$/\1/; s/[ ,.*]/_/g; s/__/_/g; s/^_//g;p').pem; mv $cert $newname; done
The command will create 3 separates files, each one named with the Common Name of the corresponding certificate.