Created
June 28, 2015 09:13
-
-
Save morawskim/6c9eeb09ad9e4ad6f6e8 to your computer and use it in GitHub Desktop.
Extract x509 cert
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
#Shell script to extract x509 certificate | |
#Author: Marcin Morawski <marcin@morawskim.pl> | |
#Exit immediately if a command exits with a non-zero status. | |
set -e | |
#Avoid accidental overwriting of a file | |
set -o noclobber | |
#Bin paths, change if these programs are not stored in paths of PATH environment variable | |
OPENSSL=$(which openssl) | |
SED=$(which sed) | |
AWK=$(which awk) | |
TR=$(which tr) | |
BASENAME=$(which basename) | |
if [ $# -eq 0 ]; then | |
echo 'Usage: ' `$BASENAME $0` ' host:port ' '[outputfile]' >&2 | |
exit 1 | |
fi; | |
HOST="$1" | |
if [ -z $2 ]; then | |
OUTPUT=$(echo $HOST | "$TR" ':/' ':' | "$AWK" -F ':' '{print $1}') | |
OUTPUT="$OUTPUT.crt" | |
else | |
OUTPUT="$2" | |
fi | |
#disable temporarily exit on error. We want display openssl error message | |
set +e | |
OPENSSL_OUTPUT=$($OPENSSL s_client -connect $HOST 2>&1 </dev/null) | |
if [ $? -ne 0 ]; then | |
echo 'openssl failed' >&2 | |
echo "$OPENSSL_OUTPUT" | |
exit 1 | |
fi | |
#enable again auto exit on command failure | |
set -e | |
echo "$OPENSSL_OUTPUT" | $SED -ne '/-----BEGIN CERTIFICATE-----/,/-----END CERTIFICATE-----/p' > $OUTPUT |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
usage:
eg.
This script create file named google.com.crt in working directory.
You can specify path, where save cert by second argument.
eg.