import argparse
# 创建解析器对象
parser = argparse.ArgumentParser(description='这是一个日志分析程序')
# 添加参数
parser.add_argument('-f', type=str, help='日志文件地址',required=True)
parser.add_argument('-ip', type=str, help='ip地址',required=False)
parser.add_argument('-s', type=str, help='状态码',required=False)
parser.add_argument('-m', type=str, help='请求方式',required=False)
# 解析参数
args = parser.parse_args()
print(args)
# 使用参数
adress=args.f
ip0=args.ip
status0=args.s
method0=args.m
# 根据参数个数执行不同的方法
condtion="not x.startswith('#')"
if args.ip:
condtion+=" and x.split()[8]==ip0"
if args.s:
condtion+=" and x.split()[13]==status0"
if args.m:
condtion+=" and x.split()[4]==method0.upper()"
#print(condtion)
# def tiaojian(x):
# condtion="not x.startswith('#')"
# if ip0 != None:
# condtion+=" and x.split()[8]==ip0"
# #return condtion and x.split()[8]==ip0
# if status0 != None:
# condtion+=" and x.split()[13]==status0"
# #return not x.startswith('#') and x.split()[8]==ip0 and x.split()[13]==status0
# if method0 != None:
# condtion+=" and x.split()[4]==method0"
# #return not x.startswith('#') and x.split()[8]==ip0 and x.split()[13]==status0 and x.split()[4]==method0
# #print(condtion)
# return eval(condtion)
with open(adress) as f:
lines=f.readlines()
filtered_numbers = [x for x in lines if eval(condtion)]
#filtered_numbers = list(filter(tiaojian, lines)) 使用filter函数
#print(filtered_numbers[0])
if len(filtered_numbers):
for line in filtered_numbers:
if line.startswith('#'):
continue
ip=line.split()[8].ljust(16)
ip1=line.split()[8]
#使用字符串的 ljust() 方法来将内容左对齐
time=line.split()[0] +'-'+ line.split()[1]
methon=line.split()[4]
url=line.split()[5]+line.split()[6]
status=line.split()[13]
tab=''.rjust(10)
print(f"ip地址: {ip} 时间: {time} 请求方式: {methon} 状态: {status} url:{url} ")
print("共"+str(len(filtered_numbers))+"条记录")
python 编写的iis日志分析小工具基本框架,可以任意修改调整成实际应用情况