【问题标题】:Python script is not producing any outputPython 脚本没有产生任何输出
【发布时间】:2018-07-25 15:31:30
【问题描述】:

我有一个 python 脚本,我正在尝试读取目录中的所有 .txt 文件,并确定它们是否针对我脚本中的任何条件返回 True 或 False。我没有收到错误消息,但脚本没有产生任何输出。我希望脚本读取包含格式为 .json 格式的文本的 .txt 文件。然后我希望脚本确定 .txt 文件是否与下面我的代码中的任何语句匹配。然后我想将结果输出到 csv 文件。非常感谢您的帮助!

#!/usr/bin/env python
# regarding whether any positive results were found for the domain on VT.


import csv
import json
import pprint
import sys
import os


CSVPATH = 'CsvResults.csv'
VTOUTPUTPATH = './output/'
VTOUTPUTEXT = '.txt'
#files_to_search = [f for f in os.listdir('./output/') if f[-4:] == '.txt']
#vt_result_path = files_to_search
#vt_result = vt_result_check(vt_result_path)

pp = pprint.PrettyPrinter(indent=4)


# Check files from VirusTotal queries for any positive results
# Result is false unless any nonzero positive result is true
def vt_result_check(vt_result_path):
    vt_result = None
    try:
        vt_result = False
        for filename in os.listdir(path):
            with open(filename, 'r', encoding='utf-16') as vt_result_file:
                vt_data = json.load(vt_result_file)
            #vt_result_path = [f for f in os.listdir('./output/') if f[-4:] == '.txt']
            #vt_result = None
            #try:
            #    vt_result = False
            #    with open(infile) as vt_result_file:
            #        vt_data = json.load(vt_result_file)

            # Look for any positive detected referrer samples
            try:
                for sample in (vt_data['detected_referrer_samples']):
                    if (sample['positives'] > 0):
                        vt_result = True
            except:
                pass

            # Look for any positive detected communicating samples
            try:
                for sample in (vt_data['detected_communicating_samples']):
                    if (sample['positives'] > 0):
                        vt_result = True
            except:
                pass

            # Look for any positive detected downloaded samples
            try:
                for sample in (vt_data['detected_downloaded_samples']):
                    if (sample['positives'] > 0):
                        vt_result = True
            except:
                pass

            # Look for any positive detected URLs
            try:
                for sample in (vt_data['detected_urls']):
                    if (sample['positives'] > 0):
                        vt_result = True
            except:
                pass

            # Look for a Dr. Web category of known infection source
            try:
                if (vt_data['Dr.Web category'] == "known infection source"):
                    vt_result = True
            except:
                pass

            # Look for a Forecepoint ThreatSeeker category of elevated exposure
            try:
                if (vt_data['Forcepoint ThreatSeeker category'] == "elevated exposure"):
                    vt_result = True
            except:
                pass

            # Look for a Forecepoint ThreatSeeker category of phishing and other frauds
            try:
                if (vt_data['Forcepoint ThreatSeeker category'] == "phishing and other frauds"):
                    vt_result = True
            except:
                pass

            # Look for a Forecepoint ThreatSeeker category of suspicious content
            try:
                if (vt_data['Forcepoint ThreatSeeker category'] == "suspicious content"):
                    vt_result = True
            except:
                pass

            #pp.pprint(vt_data)
    except:
        pass
    return vt_result



def cert_check(csvpath):
    with open(csvpath, 'w') as csvfile:
        fieldnames = ['vt_result']
        writer = csv.writer(csvfile)
        writer.writerow(['VirusTotal Results'])
        vt_result_path = VTOUTPUTPATH + subject_dom + VTOUTPUTEXT
        vt_result = vt_result_check(vt_result_file)
        writer.writerow([vt_result])

【问题讨论】:

  • 你做过调试吗?我们很难遍历一个程序,因为我们必须制作带有名称的示例文件 - 或者通读整个程序,看看我们是否可以在不运行代码的情况下看到问题
  • 脚本除了定义两个函数什么都不做。你应该运行它们。
  • @KlausD。那我怎么让它工作呢?非常感谢您的帮助?
  • @chevybow 我尝试进行一些调试,但没有收到任何错误消息。你知道该怎么做吗?
  • 那些没用的try/except: pass是怎么回事? 整个函数体周围甚至还有一个!您不会看到任何异常,只是想知道您的代码有什么问题。

标签: python python-3.x


【解决方案1】:

你需要真正调用函数我的家伙

def my_func(stuff):
    print(stuff) #or whatever

my_func(1234)

根据评论更新

import os
p=r'path\to\your\files' 

filelist=os.listdir(p) #creates list of all files/folders in this dir

#make a loop for each file in the dir
for file in filelist:
    f=os.path.join(p,file) #this just joins the file name and path for full file path
    your_func(f)  #here you can pass the full file name to your functions

【讨论】:

  • 感谢您的回复!我让它打印出控制台中第一个 .txt 文件的结果,但是如何让循环遍历目录中的所有文件?非常感谢您的帮助!!!
  • 当然,我更新了我的答案以展示如何做到这一点。或者至少有一种方法可以做到这一点,可能有很多
【解决方案2】:

如前所述,直接的问题似乎是您根本不会调用您的cert_check 函数。然而,虽然这个站点实际上不是用于代码审查的,但我不禁建议对您的代码进行一些改进。特别是,所有这些try/except:pass 构造使得检测代码中的任何 错误变得异常困难,因为所有异常都会被except: pass 默默地捕获和吞噬。

  • 您应该删除所有 try/except:pass 块,尤其是围绕整个函数体的块
  • 如果某些键不存在,您可以使用dict.get 代替[],这不会引发键错误,而是返回None(或一些默认值),并且您的所有检查仍将工作
  • 您可以使用|= 代替if 检查or 对变量的检查结果
  • 您可以使用any 检查某个列表中的任何元素是否满足某些条件

你的vt_result_check函数我的版本:

def vt_result_check(vt_result_path):
    vt_result = False
    for filename in os.listdir(path):
        with open(filename, 'r', encoding='utf-16') as vt_result_file:
            vt_data = json.load(vt_result_file)

        # Look for any positive detected referrer samples
        # Look for any positive detected communicating samples
        # Look for any positive detected downloaded samples
        # Look for any positive detected URLs
        sample_types = ('detected_referrer_samples', 'detected_communicating_samples',
                        'detected_downloaded_samples', 'detected_urls')
        vt_result |= any(sample['positives'] > 0 for sample_type in sample_types 
                                                 for sample in vt_data.get(sample_type, []))

        # Look for a Dr. Web category of known infection source
        vt_result |= vt_data.get('Dr.Web category') == "known infection source"

        # Look for a Forecepoint ThreatSeeker category of elevated exposure
        # Look for a Forecepoint ThreatSeeker category of phishing and other frauds
        # Look for a Forecepoint ThreatSeeker category of suspicious content
        threats = ("elevated exposure", "phishing and other frauds", "suspicious content")
        vt_result |= vt_data.get('Forcepoint ThreatSeeker category') in threats

    return vt_result

【讨论】:

  • 感谢您的回复。我厌倦了运行您的脚本,不幸的是,在第 17 行和第 22 行,我在无效语法上方收到了几条错误消息。我无法弄清楚正确的语法是什么。非常感谢您的帮助!
  • @bedford 一行中有一个不匹配的括号,但我找不到另一个语法错误。它现在可以工作,还是出现运行时错误?如果有,是哪一个?
  • 感谢您的回复!如果我设置 dunder main 并尝试像这样打印出 vt_result_check: if name == 'main': print(vt_result_check(path)) 然后我收到以下错误消息:第 33 行,在 print(vt_result_check(path))
  • 嗯,这不是在函数内部,而是代码调用函数。 path 是什么?在您的原始代码中,您使用了未定义的vt_result_file(而是vt_result_path);也许这里的问题类似?
  • 我将路径设置为这种类型的路径,并在脚本顶部声明了它。
猜你喜欢
  • 1970-01-01
  • 2023-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-27
相关资源
最近更新 更多