用python扫描目录

2024-04-27 19:43:36 发布

您现在位置:Python中文网/ 问答频道 /正文

这个问题已经困扰了一段时间了。 我用我自己的yara规则扫描一个目录,当我为单个文件尝试代码时,它可以工作,但是当我在for loop上使用相同的代码时,它与任何内容都不匹配

我试着搜索我的问题,但它总是向我展示yara的基本文档

def scan_test(): // works
    file_source = 'index.php'
    match_list = []
    externals = {'filename': file_source}
    rules = yara.compile('rules.yar', externals=externals)
    with open('filepath') as f:
        matches = rules.match(data=f.read(), externals=externals)

    if len(matches) > 0:
        match_list.append(matches)

    return match_list
    
def scan_test3(dir_source): // not working
    match_list = []
    for folder,subfolders, files in os.walk(dir_source):
        for file in files:
            path = os.path.join(folder, file)
            try:
                file_name, file_extension = os.path.splitext(file)
                if (file_extension == '.txt' or file_extension == '.php'):
                    rules = yara.compile('rules.yar', externals={'filename': file})
                    with open(path) as f:
                        matches = rules.match(data=f.read(), externals={'filename': file})
                    if len(matches) > 0:
                        match_list.append(matches)
            except Exception as e:
                print(e)
                pass
    return match_list

测试雅拉规则:

    rule test_rule
    {
        meta:
            description = "This is a test rule"
        strings:
            $a = "<?php"
        condition:
            $a and (filename matches /index\.php/ or filename matches /login\.php/)
    }

我的代码对吗? 有人能帮我吗


Tags: path代码testsourceforasmatchfilename