Linux CLI 檢查 HTTPS (SSL) 憑證過期時間

於 Linux CLI 想要檢查 Domain 的 HTTPS (SSL) 憑證的過期時間,要怎麼做呢?

Linux CLI 檢查 HTTPS(SSL) 憑證過期時間

Linux CLI 要如何抓取憑證的建立、過期日期,可以使用 openssl 來達成此需求

下述取自此篇:OpenSSL: Check SSL Certificate Expiration Date and More

  • 命令:echo | openssl s_client -servername NAME -connect HOST:PORT 2>/dev/null | openssl x509 -noout -dates
  • 參數:
    • -servername NAME The TLS SNI (Server Name Indication) extension (website).
    • -connect HOST:PORT The host and port to connect to.

範例

  • echo | openssl s_client -servername blog.longwin.com.tw -connect blog.longwin.com.tw:443 2>/dev/null | openssl x509 -noout -dates
    notBefore=Mar 30 03:42:10 2018 GMT
    notAfter=Jun 28 03:42:10 2018 GMT

除了過期時間外,想要另外抓到註冊商等資訊,可以使用 issuer / subject 來達成

  • echo | openssl s_client -servername blog.longwin.com.tw -connect blog.longwin.com.tw:443 2>/dev/null | openssl x509 -noout -issuer -subject -dates
    issuer=C = US, O = Let's Encrypt, CN = Let's Encrypt Authority X3
    subject=CN = blog.longwin.com.tw notBefore=Mar 30 03:42:10 2018 GMT notAfter=Jun 28 03:42:10 2018 GMT

感謝 MT 用 PHP 改寫

<?php
$hosts = [
    'longwin.com.tw',
    'www.longwin.com.tw',
    'blog.longwin.com.tw',
    'name.longwin.com.tw',
];

foreach ($hosts as $host) {
    $context = stream_context_create([
        'ssl' => [
            'capture_peer_cert' => true,
            'verify_peer' => false,
            'verify_peer_name' => false,
            'SNI_enabled' => true,
            'peer_name' => $host,
        ]
    ]);

    $socket = @stream_socket_client("ssl://$host:443", $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $context);

    if (!$socket) {
        error_log("Error: $errno - $errstr");
        continue;
    }

    $cert_data = stream_context_get_params($socket);
    $cert = openssl_x509_parse($cert_data['options']['ssl']['peer_certificate']);

    $valid_from = date('Y-m-d H:i:s', $cert['validFrom_time_t']);
    $valid_to = date('Y-m-d H:i:s', $cert['validTo_time_t']);
    $valid_days = round(($cert['validTo_time_t'] - time()) / 86400, 2);

    fclose($socket);

    echo "Host: $host\n";
    echo "Not Before: $valid_from\n";
    echo "Not After: $valid_to\n";
    echo "Days Left: $valid_days day(s)\n\n";
}
?>
Tsung: 對新奇的事物都很有興趣, 喜歡簡單的東西, 過簡單的生活.
Related Post
whatsapp
line