Skip to content

Instantly share code, notes, and snippets.

@lgh06
Created May 21, 2025 11:16
Show Gist options
  • Save lgh06/34b079f1145673e5959dc74906890970 to your computer and use it in GitHub Desktop.
Save lgh06/34b079f1145673e5959dc74906890970 to your computer and use it in GitHub Desktop.
import { connect } from 'node:tls';
// let ev = JSON.parse(event);
// let urlFromPayload = ev.payload;
// 检查SSL证书函数
async function checkSSLCertificate(hostname, port = 443) {
return new Promise((resolve, reject) => {
/**
* @type {import('node:tls').ConnectionOptions}
*/
const options = {
host: hostname,
port: port,
servername: hostname,
rejectUnauthorized: false, // 允许自签名证书
timeout: 10000, // 设置连接超时时间为10秒
allowPartialTrustChain: true, // 允许部分信任链
};
const socket = connect(options, () => {
const cert = socket.getPeerCertificate();
// 获取证书信息
const result = {
subject: cert.subject,
issuer: cert.issuer,
validFrom: new Date(cert.valid_from),
validTo: new Date(cert.valid_to),
daysRemaining: Math.floor((new Date(cert.valid_to) - new Date()) / (1000 * 60 * 60 * 24))
};
socket.end();
resolve(result);
});
socket.on('error', (error) => {
reject(error);
});
});
}
// 使用示例
const url = 'onlinetool.cc';
try {
const certInfo = await checkSSLCertificate(url);
console.log('证书信息:', certInfo);
console.log(`域名: ${url}`);
console.log(`证书有效期从: ${certInfo.validFrom}`);
console.log(`证书有效期至: ${certInfo.validTo}`);
console.log(`剩余天数: ${certInfo.daysRemaining}天`);
let returnObj = {
url: url,
daysRemaining: certInfo.daysRemaining,
validFrom: certInfo.validFrom,
validTo: certInfo.validTo
}
// return returnObj;
} catch (error) {
console.error('获取证书信息失败:', error);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment