如何按行读取域名文件并对每个域名单独执行证书检测函数
问题修复与实现方案
你现有代码的核心问题是checkcert()没有接收域名参数,直接使用了存储全量域名的列表hostname作为连接参数,自然无法实现逐个域名检测的需求。
以下是可直接运行的最简实现代码:
import socket import ssl from datetime import datetime # 固定配置 PORT = 443 # 初始化SSL上下文 context = ssl.create_default_context() def check_cert(hostname: str, port: int = PORT) -> None: try: # 增加5秒超时避免长时间卡住 with socket.create_connection((hostname, port), timeout=5) as sock: with context.wrap_socket(sock, server_hostname=hostname) as ssock: certificate = ssock.getpeercert() cert_expires = datetime.strptime(certificate['notAfter'], '%b %d %H:%M:%S %Y %Z') # 此处可替换为你自己的业务逻辑,比如判断是否即将过期 print(f"域名 {hostname} 证书到期时间:{cert_expires.strftime('%Y-%m-%d %H:%M:%S')}") except Exception as e: print(f"域名 {hostname} 检测失败:{str(e)}") if __name__ == "__main__": # 直接迭代文件对象逐行读取,不需要提前加载全量内容到内存 with open('domains', 'r', encoding='utf-8') as f: for line in f: domain = line.strip() # 跳过空行 if not domain: continue check_cert(domain)
核心改动说明
- 给
check_cert函数增加hostname入参,每次循环传入单个域名调用函数 - 增加异常捕获和超时配置,避免单个域名检测失败、连接超时导致整个程序退出
- 优化了文件读取逻辑:不需要提前把所有域名加载到列表,直接逐行迭代文件对象即可,大文件场景下更节省内存
- 补充了必要的依赖导入、配置项定义,补全了结果打印的示例逻辑
问题解答
不需要提前拆分存储全量域名,直接迭代文件对象本身就是按行读取的最简实现。迭代循环是遍历多个域名执行相同逻辑的最优方案,没有更简便的替代写法。
内容的提问来源于stack exchange,提问作者misterrm
相关产品推荐
相关产品推荐

