证书查看脚本

证书查看脚本

人懒了,一个个看证书名称和有效期太麻烦...

bash版

#!/bin/bash

GREEN='\E[32;1m'
BLUE='\E[34;1m'
END='\E[0m'

[ -f /etc/profile.d/ssl.sh ] || mv $0 /etc/profile.d/ssl.sh
[ -x /etc/profile.d/ssl.sh ] || chmod +x /etc/profile.d/ssl.sh

ssl(){
  if [[ $1 == '-h' ]] ;then
    echo -e "$BLUE 使用方法:ssl 证书 $END"
  elif [[ $1 != '' ]] ;then
    echo -e "$GREEN===================== $1 信息 ===================== $END"
    openssl x509 -in $1 -noout -issuer -subject -dates
    openssl x509 -in $1 -noout -text |grep DNS |sed -nr 's#[[:space:]]+(.*)#\1#p'
  else
    echo -e "$BLUE 使用方法:ssl 证书 $END"
  fi
}

ssl2(){
  if [[ $1 = '-h' ]] ;then
    echo -e "$BLUE 使用方法:ssl 证书1 证书2 ... $END"
  elif [[ $* != '' ]] ;then
    for i in $* ;do
      echo -e "$GREEN===================== $i 信息 ===================== $END"
      openssl x509 -in $i -noout -issuer -subject -dates
      openssl x509 -in $i -noout -text |grep DNS |sed -nr 's#[[:space:]]+(.*)#\1#p'
    done
      echo
  else
    echo -e "$BLUE 使用方法:ssl 证书1 证书2 ... $END"
  fi
}

python3版

在线获取证书信息

import socket
import ssl
from datetime import datetime

GREEN = '\033[92m'
END = '\033[0m'

def cert_expires(*hostnames):
    context = ssl.create_default_context()
    if len(hostnames) > 1:
        for hostname in hostnames:
            with socket.create_connection((hostname, 443), timeout=3) as sock:
                with context.wrap_socket(sock, server_hostname=hostname) as ssock:
                    print(GREEN + '------------------ info ------------------' + END)
                    output_info(ssock.getpeercert())
    else:
        with socket.create_connection((hostnames[0], 443), timeout=3) as sock:
            with context.wrap_socket(sock, server_hostname=hostnames[0]) as ssock:
                output_info(ssock.getpeercert())


def output_info(cert_info):
    print(f'issuer: {cert_info["issuer"][1][0][-1]}')
    print('subject: ',*tuple((v for i in cert_info["subject"] for _, v in i if _ == 'commonName')))
    try:
        print('bind dns:', *tuple((domain for i in cert_info["subjectAltName"] if i for _, domain in (i,))))
    except:
        print('bind dns: None')
    print(f'create time: {datetime.strptime(cert_info["notBefore"], "%b %d %H:%M:%S %Y %Z")}')
    print(f'expire time: {datetime.strptime(cert_info["notAfter"], "%b %d %H:%M:%S %Y %Z")}')


hostnames = (
    'www.hj.com',
    'www.qq.com'
)
cert_expires(*hostnames)

posted @ 2022-12-20 16:04  suyanhj  阅读(31)  评论(0)    收藏  举报