Skip to content

Instantly share code, notes, and snippets.

@ssbarnea
Created October 4, 2012 13:14
Show Gist options
  • Save ssbarnea/3833453 to your computer and use it in GitHub Desktop.
Save ssbarnea/3833453 to your computer and use it in GitHub Desktop.
Bash script that installs SSL certificates from different services to JVMs.
#!/bin/bash
REMHOST=$1
REMPORT=${2:-443}
CACERTS=$3
KEYSTORE_PASS=changeit
KEYTOOL=keytool
# /etc/java-6-sun/security/cacerts
if [ -e "$CACERTS" ]
then
echo --- Adding certs to $CACERTS
# FYI: the default keystore is located in ~/.keystore
if [ -z "$REMHOST" ]
then
echo "ERROR: Please specify the server name to import the certificatin from, eventually followed by the port number, if other than 443."
exit 1
fi
set -e
rm -f $REMHOST:$REMPORT.pem
if openssl s_client -connect $REMHOST:$REMPORT 1>/tmp/keytool_stdout 2>/tmp/output </dev/null
then
:
else
cat /tmp/keytool_stdout
cat /tmp/output
exit 1
fi
if sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' </tmp/keytool_stdout > $REMHOST:$REMPORT.pem
then
:
else
echo "ERROR: Unable to extract the certificate from $REMHOST:$REMPORT ($?)"
cat /tmp/output
fi
if $KEYTOOL -list -storepass ${KEYSTORE_PASS} -alias $REMHOST:$REMPORT >/dev/null
then
echo "Key of $REMHOST already found, skipping it."
else
$KEYTOOL -import -trustcacerts -noprompt -storepass ${KEYSTORE_PASS} -alias $REMHOST:$REMPORT -file $REMHOST:$REMPORT.pem
fi
if $KEYTOOL -list -storepass ${KEYSTORE_PASS} -alias $REMHOST:$REMPORT -keystore $CACERTS >/dev/null
then
echo "Key of $REMHOST already found in cacerts, skipping it."
else
$KEYTOOL -import -trustcacerts -noprompt -keystore $CACERTS -storepass ${KEYSTORE_PASS} -alias $REMHOST:$REMPORT -file $REMHOST:$REMPORT.pem
fi
else
echo $CACERTS not found
fi
@tangier101
Copy link

tangier101 commented Feb 6, 2017

Thanks for sharing. This has helped with my setting up some test services with Docker containers. I'm using CXF to build a proxy service, and CXF is using the java keystore. Unfortunately the test service is using self-signed certificates, causing this script to error. Is there a way to suppress this?

@RajatmaniTripathi10
Copy link

How can I add the certificate to the shell script in GitHub?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment