Skip to main content
 首页 » 编程设计

python分析2个日志文件

2025年05月04日8me-sa

我有 2 个大日志文件。我想看看一个设备是否在 a 但不在 b 中,反之亦然(不包括设备常见的行)文件看起来像这个例子。

04/09/2010,13:11:52,Authen OK,user1,默认组,00-24-2B-A1-08-88,29,10.1.1.1,(默认),,, ,,,13,EAP-TLS,,device1,
04/19/2010,15:35:24,Authen OK,user2,默认组,00-24-2B-A1-05-EA,29,10.1.1.2,(默认),,,,,,13,EAP -TLS,,device2,
04/09/2010,13:11:52,Authen OK,user3,默认组,00-24-2B-A1-08-88,29,10.1.1.3,(默认),,,,,,13,EAP -TLS,,device3,
04/19/2010,15:35:24,Authen OK,user4,默认组,00-24-2B-A1-05-EA,29,10.1.1.4,(默认),,,,,,13,EAP -TLS,,device4,

重申一下,我需要设备(字段 [-2])和 IP(字段 [7])用于日志文件 a 但不在 b 中,并且在 b 但不在 a 中的每个设备

这是我到目前为止所做的,但看起来有点笨拙而且速度很慢(每个文件大约有 40 万行)。我交叉引用了两次。任何人都可以建议效率吗?也许我使用了错误的逻辑??

chst={} 
chbs={} 
for i,line in enumerate(open('chst.txt').readlines()): 
    line=line.split(',') 
    chst[line[-2]+','+str(i)]=','.join(line) 
 
for i,line in enumerate(open('chbs.txt').readlines()): 
    line=line.split(',') 
    chbs[line[-2]+','+str(i)]='.'.join(line) 
 
print "these lines are in CHST but not in CHBS" 
for a in chst: 
    if a.split(',')[0] not in str(chbs.values()): 
        line=chst[a].split(',') 
        print line[-2], line[7] 
 
print "\nthese lines are in CHBS but not in CHST" 
 
for a in chbs: 
    if a.split(',')[0] not in str(chst.values()): 
        line=chbs[a].split(',') 
        print line[-2], line[7] 

请您参考如下方法:

您正在寻找 symmetric difference :

chst = { ( line.split( "," )[ -2 ], line.split( "," )[ 7 ] ) for line in open( ... ) } 
chbs = { ( line.split( "," )[ -2 ], line.split( "," )[ 7 ] ) for line in open( ... ) } 
 
diff = chst ^ chbs 

如果你需要非对称差异,使用-:

chst - chbs # tuples in chst but not in chbs 
chbs - chst # tuples in chbs but not in chst 

如果您需要实际的行,而不是元组 ( device, IP ),您可以使用字典而不是集合:

chst = { ( line.split( "," )[ -2 ], line.split( "," )[ 7 ] ): line for line in open( ... ) } 
chbs = { ( line.split( "," )[ -2 ], line.split( "," )[ 7 ] ): line for line in open( ... ) } 
 
diff = chst.items( ) ^ bar.items( ) 

这是有效的,因为 dict.items( ) 返回 view在具有 setlike 属性的项目上。请注意,这在 Python 2.x 中称为 dict.viewitems( )。