【问题标题】:Python File Integrity MonitoringPython 文件完整性监控
【发布时间】:2013-02-02 07:13:31
【问题描述】:

我编写了以下代码,但无法正常工作,我不明白为什么。代码:

  1. 读取目标文件列表
  2. 遍历目录
  3. 对文件运行 MD5 哈希
  4. 检查活动文件以获取该文件以前的 md5 哈希
  5. 如果文件是新文件,它会将其记录为新文件
  6. 如果日志存在但已更改,它将写入更改并记录更改
  7. 如果不是新的并且没有变化,那就什么都不做

代码如下:

import hashlib
import logging as log
import optparse
import os
import re
import sys
import glob
import shutil

def md5(fileName):
    """Compute md5 hash of the specified file"""
    try:
        fileHandle = open(fileName, "rb")
    except IOError:
        return
    m5Hash = hashlib.md5()
    while True:
        data = fileHandle.read(8192)
        if not data:
            break
        m5Hash.update(data)
    fileHandle.close()
    return m5Hash.hexdigest()

req = open("requested.txt")
for reqline in req:
    reqName = reqline[reqline.rfind('/') + 1:len(reqline) - 1]
    reqDir = reqline[0:reqline.rfind('/') + 1] 
    tempFile = open("activetemp.txt", 'w') 
    for name in glob.glob(reqDir + reqName):    
        fileHash = md5(name) 
        actInt = 0
        if fileHash != None:

            actFile = open("activefile.txt")

            for actLine in actFile:
                actNameDir = actLine[0:actLine.rfind(' : ')]
                actHash = actLine[actLine.rfind(' : ') + 3:len(actLine) -1]
                if actNameDir == name and actHash == fileHash:
                    tempFile.write(name + " : " + fileHash + "\n")
                    actInt = 1 
                    print fileHash
                    print actHash
                    print name
                    print actNameDir
                if actNameDir == name and actHash != fileHash:
                    fimlog = open("fimlog.txt", 'a')
                    tempFile.write(name + " : " + actHash + "\n")         
                    actInt = 1
                    fimlog.write("FIM Log: The file " + name +  " was modified: " + actHash + "\n") 
            if actInt == 0: 
                fimlog = open("fimlog.txt", 'a')
                fimlog.write("FIM Log: The file " + name +  " was created: " + fileHash + "\n")
                tempFile.write(name + " : " + fileHash + "\n")                       

shutil.copyfile("activetemp.txt", "activefile.txt")

【问题讨论】:

    标签: python file hash for-loop md5


    【解决方案1】:

    您从未真正描述过问题,但一个可能的罪魁祸首是您从未关闭 tempFile(或与此相关的其他文件),因此最后的文件复制可能会失败。

    【讨论】:

    • 问题是有些文件永远不会被写入活动文件,而有些会。前 50 个左右没有写入 activefile,我不明白为什么。
    猜你喜欢
    • 1970-01-01
    • 2023-01-27
    • 1970-01-01
    • 2010-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多