Save server certificate to your local machine using bash

To save a server certificate to your local machine, we can use openssl and read from the https port 443 and save it using echo.

HOST="poopcode.com"

file=/home/subash/Documents/certs/$HOST:443/ca.crt
if [ ! -e "$file" ] ; then
    mkdir -p "${file%/*}" && touch "$file"
fi

echo QUIT | openssl s_client -showcerts -connect $HOST:443 -servername $HOST 2>/dev/null | openssl x509 -text > file

Save the above script to a file called save_server_script.sh and give permissions.

chmod +x save_server_cert.sh

Run the script and open the directory to see the .crt file getting saved.

./save_server_cert.sh