怎么用脚本获取数字证书信息

wen 实用脚本 2

本文目录导读:

怎么用脚本获取数字证书信息

  1. OpenSSL 命令行工具(最常用)
  2. Bash 脚本示例
  3. Python 脚本
  4. PowerShell 脚本(Windows)
  5. Node.js 脚本
  6. 检查证书过期脚本
  7. 安装依赖

OpenSSL 命令行工具(最常用)

获取网站证书信息

# 获取HTTPS网站的证书信息
echo | openssl s_client -connect example.com:443 -servername example.com 2>/dev/null | openssl x509 -text -noout
# 只查看证书有效期
echo | openssl s_client -connect example.com:443 2>/dev/null | openssl x509 -noout -dates
# 查看证书主题和颁发者
echo | openssl s_client -connect example.com:443 2>/dev/null | openssl x509 -noout -subject -issuer

本地证书文件

# 查看PEM格式证书
openssl x509 -in certificate.pem -text -noout
# 查看DER格式证书
openssl x509 -in certificate.der -inform der -text -noout
# 查看PFX/P12格式证书
openssl pkcs12 -in certificate.pfx -nokeys | openssl x509 -text -noout

Bash 脚本示例

#!/bin/bash
# 获取证书信息的函数
get_cert_info() {
    local domain=$1
    local port=${2:-443}
    echo "=== 证书信息 for $domain:$port ==="
    # 获取证书并解析
    cert_info=$(echo | openssl s_client -connect "$domain:$port" -servername "$domain" 2>/dev/null)
    # 提取关键信息
    echo "主题: $(echo "$cert_info" | openssl x509 -noout -subject)"
    echo "颁发者: $(echo "$cert_info" | openssl x509 -noout -issuer)"
    echo "有效期开始: $(echo "$cert_info" | openssl x509 -noout -startdate)"
    echo "有效期结束: $(echo "$cert_info" | openssl x509 -noout -enddate)"
    echo "序列号: $(echo "$cert_info" | openssl x509 -noout -serial)"
    echo "SHA1指纹: $(echo "$cert_info" | openssl x509 -noout -fingerprint -sha1)"
    echo "SHA256指纹: $(echo "$cert_info" | openssl x509 -noout -fingerprint -sha256)"
}
# 使用示例
get_cert_info "www.google.com"

Python 脚本

使用 ssl 模块

import ssl
import socket
import certifi
import OpenSSL
def get_certificate_info(hostname, port=443):
    """获取SSL证书信息"""
    context = ssl.create_default_context()
    try:
        with socket.create_connection((hostname, port), timeout=10) as sock:
            with context.wrap_socket(sock, server_hostname=hostname) as ssock:
                cert = ssock.getpeercert()
                print(f"=== 证书信息 for {hostname}:{port} ===")
                print(f"主题: {cert.get('subject')}")
                print(f"颁发者: {cert.get('issuer')}")
                print(f"有效期从: {cert.get('notBefore')}")
                print(f"有效期到: {cert.get('notAfter')}")
                print(f"序列号: {cert.get('serialNumber')}")
                # 获取SAN(主题备用名称)
                san = cert.get('subjectAltName', [])
                print(f"主题备用名称: {san}")
    except Exception as e:
        print(f"错误: {e}")
# 使用示例
get_certificate_info("www.google.com")

使用 cryptography 库(需要安装)

# pip install cryptography
from cryptography import x509
from cryptography.hazmat.backends import default_backend
import requests
def get_cert_from_url(url):
    """从URL获取证书信息"""
    response = requests.get(url, verify=True)
    # 解析PEM格式证书
    cert_pem = response.text  # 或从连接获取
    # 实际使用PEM文件
    with open('certificate.pem', 'rb') as f:
        cert = x509.load_pem_x509_certificate(f.read(), default_backend())
        print(f"版本: {cert.version}")
        print(f"序列号: {cert.serial_number}")
        print(f"签名算法: {cert.signature_algorithm_oid}")
        print(f"颁发者: {cert.issuer}")
        print(f"有效期:")
        print(f"  开始: {cert.not_valid_before}")
        print(f"  结束: {cert.not_valid_after}")
        print(f"主题: {cert.subject}")

PowerShell 脚本(Windows)

# 获取远程证书信息
function Get-CertInfo {
    param(
        [string]$Hostname,
        [int]$Port = 443
    )
    $tcpClient = New-Object System.Net.Sockets.TcpClient
    $tcpClient.Connect($Hostname, $Port)
    $sslStream = New-Object System.Net.Security.SslStream($tcpClient.GetStream())
    $sslStream.AuthenticateAsClient($Hostname)
    $cert = $sslStream.RemoteCertificate
    Write-Host "=== 证书信息 for $Hostname : $Port ==="
    Write-Host "主题: $($cert.Subject)"
    Write-Host "颁发者: $($cert.Issuer)"
    Write-Host "有效期: $($cert.GetExpirationDateString())"
    Write-Host "序列号: $($cert.GetSerialNumberString())"
    Write-Host "指纹: $($cert.GetCertHashString())"
    $sslStream.Close()
    $tcpClient.Close()
}
# 使用示例
Get-CertInfo -Hostname "www.google.com"

Node.js 脚本

const https = require('https');
const tls = require('tls');
const fs = require('fs');
function getCertInfo(hostname, port = 443) {
    const options = {
        host: hostname,
        port: port,
        rejectUnauthorized: false
    };
    const socket = tls.connect(port, hostname, options, () => {
        const cert = socket.getPeerCertificate();
        console.log(`=== 证书信息 for ${hostname}:${port} ===`);
        console.log(`主题: ${cert.subject.CN}`);
        console.log(`颁发者: ${cert.issuer.CN}`);
        console.log(`有效期从: ${new Date(cert.valid_from).toISOString()}`);
        console.log(`有效期到: ${new Date(cert.valid_to).toISOString()}`);
        console.log(`序列号: ${cert.serialNumber}`);
        console.log(`指纹: ${cert.fingerprint}`);
        console.log(`指纹256: ${cert.fingerprint256}`);
        socket.end();
    });
}
// 使用示例
getCertInfo('www.google.com');

检查证书过期脚本

#!/bin/bash
# 检查证书是否即将过期
check_cert_expiry() {
    local domain=$1
    local warning_days=${2:-30}
    # 获取过期日期
    expiry_date=$(echo | openssl s_client -connect "$domain":443 2>/dev/null | \
                  openssl x509 -noout -enddate | cut -d= -f2)
    # 转换日期
    expiry_epoch=$(date -d "$expiry_date" +%s)
    current_epoch=$(date +%s)
    # 计算剩余天数
    remaining=$(( (expiry_epoch - current_epoch) / 86400 ))
    if [ $remaining -le 0 ]; then
        echo "⚠️ 证书已过期!($domain)"
    elif [ $remaining -le $warning_days ]; then
        echo "⚠️ 证书将在 $remaining 天后过期!($domain)"
    else
        echo "✅ 证书有效,剩余 $remaining 天 ($domain)"
    fi
}
# 批量检查
for domain in "www.google.com" "www.github.com" "stackoverflow.com"; do
    check_cert_expiry "$domain"
done

安装依赖

Python:

pip install cryptography pyopenssl

Node.js:

npm install node-forge

选择哪个脚本取决于你的需求和运行环境,对于日常使用,OpenSSL命令最方便;如果需要编程处理数据,Python或Node.js更合适。

抱歉,评论功能暂时关闭!