gitlab api 获取有效用户的名称,仓库,有效期(二) 2输出文件3提取user_projects.txt文件中到期的用户信息rootrke2-10-30:~/gitlabUserExpire# more getSoonToExpire.py from datetime import datetime, timezone import re import argparse def parse_user_projects(file_path, threshold_days30): today datetime.now(timezone.utc).date() current_user results [] with open(file_path, r, encodingutf-8) as f: for line in f: line line.strip() if line.startswith(用户名:): username_part line.split(()[0].replace(用户名:, ).strip() current_user username_part elif line.startswith(-): # 优化后的正则表达式精确匹配中文冒号和括号 match re.search( r-\s*([^(]?)\s*\(([^,]?),\s*到期时间:\s*(\d{4}-\d{2}-\d{2}|永久有效)\):\s*(\S), line ) if match: project_name, _, expire_date_str, repo_url match.groups() if expire_date_str 永久有效: continue # 精确计算日期差考虑时区 expire_date datetime.strptime(expire_date_str, %Y-%m-%d).replace( tzinfotimezone.utc ).date() delta (expire_date - today).days if 0 delta threshold_days: results.append({ username: current_user, project: project_name.strip(), repo_url: repo_url.strip(), expire_date: expire_date_str, days_remaining: delta }) else: print(fDebug - 未匹配的行: {line} (正则表达式不匹配)) return results if __name__ __main__: parser argparse.ArgumentParser() parser.add_argument(--days, typeint, default30, help过滤阈值天数) parser.add_argument(--file, defaultuser_projects.txt, help输入文件路径) args parser.parse_args() # 模拟当前日期为 2025-03-26用于测试 # datetime.now lambda: datetime(2025, 3, 26, tzinfotimezone.utc) output parse_user_projects(args.file, args.days) if not output: print(未找到符合条件的记录) else: header f{用户名:15}{项目名称:20}{仓库地址:50}{到期时间:12}{剩余天数:10} print(header) print(- * len(header.expandtabs(20))) for item in output: print(f{item[username]:15}{item[project]:20}{item[repo_url]:70}{item[expire_date]:12}{item[days_remainin g]:10})3执行结果python3 getSoonToExpire.py --days 100