Python脚本未产生任何输出

时间:2018-07-25 15:31:30

标签: python python-3.x

我有一个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])

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

如前所述,直接的问题似乎是您根本不调用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