首页 后端开发 Python教程 python实现封装得到virustotal扫描结果

python实现封装得到virustotal扫描结果

Jun 06, 2016 am 11:20 AM
python 封装 扫描

本文实例讲述了python实现封装得到virustotal扫描结果的方法。分享给大家供大家参考。具体方法如下:

import simplejson 
import urllib 
import urllib2 
import os, sys 
import logging 
 
try: 
  import sqlite3 
except ImportError: 
  sys.stderr.write("ERROR: Unable to locate Python SQLite3 module. " \ 
           "Please verify your installation. Exiting...\n") 
  sys.exit(-1) 
   
MD5 = "5248f774d2ee0a10936d0b1dc89107f1" 
MD5 = "12fa5fb74201d9b6a14f63fbf9a81ff6" #do not have report on virustotal.com 
      
 
APIKEY = "xxxxxxxxxxxxxxxxxx"用自己的 

class VirusTotalDatabase: 
  """ 
  Database abstraction layer. 
  """ 
  def __init__(self, db_file): 
    log = logging.getLogger("Database.Init") 
    self.__dbfile = db_file 
    self._conn = None 
    self._cursor = None 
 
    # Check if SQLite database already exists. If it doesn't exist I invoke 
    # the generation procedure. 
    if not os.path.exists(self.__dbfile): 
      if self._generate(): 
        print("Generated database \"%s\" which didn't" \ 
             " exist before." % self.__dbfile) 
      else: 
        print("Unable to generate database") 
 
    # Once the database is generated of it already has been, I can 
    # initialize the connection. 
    try: 
      self._conn = sqlite3.connect(self.__dbfile) 
      self._cursor = self._conn.cursor() 
    except Exception, why: 
      print("Unable to connect to database \"%s\": %s." 
           % (self.__dbfile, why)) 
 
    log.debug("Connected to SQLite database \"%s\"." % self.__dbfile) 
 
  def _generate(self): 
    """ 
    Creates database structure in a SQLite file. 
    """ 
    if os.path.exists(self.__dbfile): 
      return False 
 
    db_dir = os.path.dirname(self.__dbfile) 
    if not os.path.exists(db_dir): 
      try: 
        os.makedirs(db_dir) 
      except (IOError, os.error), why: 
        print("Something went wrong while creating database " \ 
             "directory \"%s\": %s" % (db_dir, why)) 
        return False 
 
    conn = sqlite3.connect(self.__dbfile) 
    cursor = conn.cursor() 
 
    cursor.execute("CREATE TABLE virustotal (\n"              \ 
            " id INTEGER PRIMARY KEY,\n"            \ 
            " md5 TEXT NOT NULL,\n"           \ 
            " Kaspersky TEXT DEFAULT NULL,\n"               \ 
            " McAfee TEXT DEFAULT NULL,\n"            \ 
            " Symantec TEXT DEFAULT NULL,\n"             \ 
            " Norman TEXT DEFAULT NULL,\n"             \ 
            " Avast TEXT DEFAULT NULL,\n"            \ 
            " NOD32 TEXT DEFAULT NULL,\n"         \ 
            " BitDefender TEXT DEFAULT NULL,\n"            \ 
            " Microsoft TEXT DEFAULT NULL,\n"            \ 
            " Rising TEXT DEFAULT NULL,\n"           \ 
            " Panda TEXT DEFAULT NULL\n"           \ 
            ");") 
    print "create db:%s sucess" % self.__dbfile 
 
    return True 
 
  def _get_task_dict(self, row): 
    try: 
      task = {} 
      task["id"] = row[0] 
      task["md5"] = row[1] 
      task["Kaspersky"] = row[2] 
      task["McAfee"] = row[3] 
      task["Symantec"] = row[4] 
      task["Norman"] = row[5] 
      task["Avast"] = row[6] 
      task["NOD32"] = row[7] 
      task["BitDefender"] = row[8] 
      task["Microsoft"] = row[9] 
      task["Rising"] = row[10] 
      task["Panda"] = row[11] 
      return task 
    except Exception, why: 
      return None 
 
  def add_sample(self, md5, virus_dict): 
    """ 
     
    """ 
    task_id = None 
 
    if not self._cursor: 
      return None 
    if not md5 or md5 == "": 
      return None 
 
    Kaspersky = virus_dict.get("Kaspersky", None) 
    McAfee = virus_dict.get("McAfee", None) 
    Symantec = virus_dict.get("Symantec", None) 
    Norman = virus_dict.get("Norman", None) 
    Avast = virus_dict.get("Avast", None) 
    NOD32 = virus_dict.get("NOD32", None) 
    BitDefender = virus_dict.get("BitDefender", None) 
    Microsoft = virus_dict.get("Microsoft", None) 
    Rising = virus_dict.get("Rising", None) 
    Panda = virus_dict.get("Panda", None) 
     
    self._conn.text_factory = str 
    try: 
      self._cursor.execute("SELECT id FROM virustotal WHERE md5 = ?;", 
                 (md5,)) 
      sample_row = self._cursor.fetchone() 
    except sqlite3.OperationalError, why: 
      print "sqlite3 error:%s\n" % str(why) 
      return False 
     
    if sample_row: 
      try: 
        sample_row = sample_row[0] 
        self._cursor.execute("UPDATE virustotal SET Kaspersky=?, McAfee=?, Symantec=?, Norman=?, Avast=?, \ 
                   NOD32=?, BitDefender=?, Microsoft=?, Rising=?, Panda=?  WHERE id = ?;", 
                   (Kaspersky, McAfee, Symantec, Norman, Avast, NOD32, BitDefender, Microsoft,\ 
                   Rising, Panda, sample_row)) 
        self._conn.commit() 
        task_id = sample_row 
      except sqlite3.OperationalError, why: 
        print("Unable to update database: %s." % why) 
        return False 
    else: #the sample not in the database 
      try: 
        self._cursor.execute("INSERT INTO virustotal " \ 
                   "(md5, Kaspersky, McAfee, Symantec, Norman, Avast, NOD32, BitDefender,\ 
                    Microsoft, Rising, Panda) " \ 
                   "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);", 
                   (md5, Kaspersky, McAfee, Symantec, Norman, Avast, NOD32, BitDefender,\ 
                    Microsoft, Rising, Panda)) 
        self._conn.commit() 
        task_id = self._cursor.lastrowid 
      except sqlite3.OperationalError, why: 
        print "why",str(why) 
        return None 
      print "add_to_db:%s, task_id:%s" % (str(self.__dbfile), str(task_id)) 
    return task_id 
 
  def get_sample(self): 
    """ 
    Gets a task from pending queue. 
    """ 
    log = logging.getLogger("Database.GetTask") 
 
    if not self._cursor: 
      log.error("Unable to acquire cursor.") 
      return None 
 
    # Select one item from the queue table with higher priority and older 
    # addition date which has not already been processed. 
    try:     
      self._cursor.execute("SELECT * FROM virustotal " \ 
                 #"WHERE lock = 0 " \ 
                 #"AND status = 0 " \ 
                 "ORDER BY id, added_on LIMIT 1;") 
    except sqlite3.OperationalError, why: 
      log.error("Unable to query database: %s." % why) 
      return None 
 
    sample_row = self._cursor.fetchone() 
 
    if sample_row: 
      return self._get_task_dict(sample_row) 
    else: 
      return None 
 
  def search_md5(self, md5): 
    """ 
    
    """ 
    if not self._cursor: 
      return None 
 
    if not md5 or len(md5) != 32: 
      return None 
 
    try: 
      self._cursor.execute("SELECT * FROM virustotal " \ 
                 "WHERE md5 = ? " \ 
                 #"AND status = 1 " \ 
                 "ORDER BY id DESC;", 
                 (md5,)) 
    except sqlite3.OperationalError, why: 
      return None 
 
    task_dict = {} 
    for row in self._cursor.fetchall(): 
      task_dict = self._get_task_dict(row) 
      #if task_dict: 
        #tasks.append(task_dict) 
 
    return task_dict 
 
   
 
class VirusTotal: 
  """""" 
 
  def __init__(self, md5): 
    """Constructor""" 
    self._virus_dict = {} 
    self._md5 = md5 
    self._db_file = r"./db/virustotal.db" 
    self.get_report_dict() 
     
  def repr(self): 
    return str(self._virus_dict) 
   
  def submit_md5(self, file_path): 
    import postfile                                      
    #submit the file 
    FILE_NAME = os.path.basename(file_path)  
               
                                                  
    host = "www.virustotal.com"                                
    selector = "https://www.virustotal.com/vtapi/v2/file/scan"                 
    fields = [("apikey", APIKEY)] 
    file_to_send = open(file_path, "rb").read()                        
    files = [("file", FILE_NAME, file_to_send)]                        
    json = postfile.post_multipart(host, selector, fields, files)               
    print json 
    pass 
   
  def get_report_dict(self): 
    result_dict = {} 
     
    url = "https://www.virustotal.com/vtapi/v2/file/report" 
    parameters = {"resource": self._md5, 
            "apikey": APIKEY} 
    data = urllib.urlencode(parameters) 
    req = urllib2.Request(url, data) 
    response = urllib2.urlopen(req) 
    json = response.read() 
     
    response_dict = simplejson.loads(json) 
    if response_dict["response_code"]: #has result  
      scans_dict = response_dict.get("scans", {}) 
      for anti_virus_comany, virus_name in scans_dict.iteritems(): 
        if virus_name["detected"]: 
          result_dict.setdefault(anti_virus_comany, virus_name["result"]) 
    return result_dict 
   
  def write_to_db(self): 
    """""" 
    db = VirusTotalDatabase(self._db_file) 
    virus_dict = self.get_report_dict() 
    db.add_sample(self._md5, virus_dict) 
登录后复制

使用方法如下:

config = {'input':"inputMd5s"} 
fp = open(config['input'], "r") 
content = fp.readlines() 
MD5S = [] 
for md5 in ifilter(lambda x:len(x)>0, imap(string.strip, content)): 
  MD5S.append(md5)   
print "MD5S",MD5S 
fp.close() 
 
 
from getVirusTotalInfo import VirusTotal 
#得到扫描结果并写入数库 
for md5 in MD5S: 
  virus_total = VirusTotal(md5) 
  virus_total.write_to_db() 

登录后复制

希望本文所述对大家的Python程序设计有所帮助。

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

热门话题

Java教程
1663
14
CakePHP 教程
1420
52
Laravel 教程
1315
25
PHP教程
1266
29
C# 教程
1239
24
PHP和Python:解释了不同的范例 PHP和Python:解释了不同的范例 Apr 18, 2025 am 12:26 AM

PHP主要是过程式编程,但也支持面向对象编程(OOP);Python支持多种范式,包括OOP、函数式和过程式编程。PHP适合web开发,Python适用于多种应用,如数据分析和机器学习。

在PHP和Python之间进行选择:指南 在PHP和Python之间进行选择:指南 Apr 18, 2025 am 12:24 AM

PHP适合网页开发和快速原型开发,Python适用于数据科学和机器学习。1.PHP用于动态网页开发,语法简单,适合快速开发。2.Python语法简洁,适用于多领域,库生态系统强大。

PHP和Python:深入了解他们的历史 PHP和Python:深入了解他们的历史 Apr 18, 2025 am 12:25 AM

PHP起源于1994年,由RasmusLerdorf开发,最初用于跟踪网站访问者,逐渐演变为服务器端脚本语言,广泛应用于网页开发。Python由GuidovanRossum于1980年代末开发,1991年首次发布,强调代码可读性和简洁性,适用于科学计算、数据分析等领域。

Python vs. JavaScript:学习曲线和易用性 Python vs. JavaScript:学习曲线和易用性 Apr 16, 2025 am 12:12 AM

Python更适合初学者,学习曲线平缓,语法简洁;JavaScript适合前端开发,学习曲线较陡,语法灵活。1.Python语法直观,适用于数据科学和后端开发。2.JavaScript灵活,广泛用于前端和服务器端编程。

sublime怎么运行代码python sublime怎么运行代码python Apr 16, 2025 am 08:48 AM

在 Sublime Text 中运行 Python 代码,需先安装 Python 插件,再创建 .py 文件并编写代码,最后按 Ctrl B 运行代码,输出会在控制台中显示。

vscode在哪写代码 vscode在哪写代码 Apr 15, 2025 pm 09:54 PM

在 Visual Studio Code(VSCode)中编写代码简单易行,只需安装 VSCode、创建项目、选择语言、创建文件、编写代码、保存并运行即可。VSCode 的优点包括跨平台、免费开源、强大功能、扩展丰富,以及轻量快速。

Golang vs. Python:性能和可伸缩性 Golang vs. Python:性能和可伸缩性 Apr 19, 2025 am 12:18 AM

Golang在性能和可扩展性方面优于Python。1)Golang的编译型特性和高效并发模型使其在高并发场景下表现出色。2)Python作为解释型语言,执行速度较慢,但通过工具如Cython可优化性能。

notepad 怎么运行python notepad 怎么运行python Apr 16, 2025 pm 07:33 PM

在 Notepad 中运行 Python 代码需要安装 Python 可执行文件和 NppExec 插件。安装 Python 并为其添加 PATH 后,在 NppExec 插件中配置命令为“python”、参数为“{CURRENT_DIRECTORY}{FILE_NAME}”,即可在 Notepad 中通过快捷键“F6”运行 Python 代码。

See all articles