如何在单个命令中使用keytool导入和信任java中的Web服务器证书?

时间:2012-07-23 11:17:22

标签: java certificate keytool

使用案例:您的网络服务器使用的是自签名证书或不受信任的CA发出的证书,您只是想确保您的Java服务器能够与此服务器正常通信。

我在网上找到了几个教程,但没有一个使用自动/可编写脚本的方法。

1 个答案:

答案 0 :(得分:3)

同时发布为https://gist.github.com/3164098(欢迎补丁)


#!/bin/bash
REMHOST=$1
REMPORT=${2:-443}

KEYSTORE_PASS=changeit
KEYTOOL=/opt/jira/jre/bin/keytool

# 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.pem

echo -n | openssl s_client -connect $REMHOST:$REMPORT 2>/dev/null  $REMHOST.pem

if $KEYTOOL -list -storepass ${KEYSTORE_PASS} -alias $REMHOST >/dev/null
    then
    echo "Key of $REMHOST already found, skipping it."
    else
    $KEYTOOL -import -trustcacerts -noprompt -storepass ${KEYSTORE_PASS} -alias $REMHOST -file $REMHOST.pem
    fi