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


Posted in Python onOctober 05, 2014

本文实例讲述了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程序设计有所帮助。

Python 相关文章推荐
分析Python编程时利用wxPython来支持多线程的方法
Apr 07 Python
python3利用Dlib19.7实现人脸68个特征点标定
Feb 26 Python
python使用jieba实现中文分词去停用词方法示例
Mar 11 Python
django Serializer序列化使用方法详解
Oct 16 Python
将python运行结果保存至本地文件中的示例讲解
Jul 11 Python
Python中利用LSTM模型进行时间序列预测分析的实现
Jul 26 Python
Python基于Tensor FLow的图像处理操作详解
Jan 15 Python
将自己的数据集制作成TFRecord格式教程
Feb 17 Python
python 实现仿微信聊天时间格式化显示的代码
Apr 17 Python
如何查看Django ORM执行的SQL语句的实现
Apr 20 Python
python不到50行代码完成了多张excel合并的实现示例
May 28 Python
Pycharm中使用git进行合作开发的教程详解
Nov 17 Python
python解析xml文件操作实例
Oct 05 #Python
python写xml文件的操作实例
Oct 05 #Python
python实现上传样本到virustotal并查询扫描信息的方法
Oct 05 #Python
python实现计算资源图标crc值的方法
Oct 05 #Python
python求crc32值的方法
Oct 05 #Python
Python获取文件ssdeep值的方法
Oct 05 #Python
python获取Linux下文件版本信息、公司名和产品名的方法
Oct 05 #Python
You might like
Mac系统下安装PHP Xdebug
2018/03/30 PHP
thinkPHP框架动态配置用法实例分析
2018/06/14 PHP
php设计模式之享元模式分析【星际争霸游戏案例】
2020/03/23 PHP
JS中彻底删除JSON对象组成的数组中的元素
2020/09/22 PHP
图片完美缩放
2006/09/07 Javascript
JavaScript CSS修改学习第六章 拖拽
2010/02/19 Javascript
jquery获取input表单值的代码
2010/04/19 Javascript
setInterval,setTimeout与jquery混用的问题
2013/04/08 Javascript
JavaScript sup方法入门实例(把字符串显示为上标)
2014/10/20 Javascript
详解JavaScript中shift()方法的使用
2015/06/09 Javascript
ichart.js绘制虚线、平均分虚线效果的实现代码
2016/05/05 Javascript
如何检测JavaScript的各种类型
2016/07/30 Javascript
jquery无法为动态生成的元素添加点击事件的解决方法(推荐)
2016/12/26 Javascript
jQuery对table表格进行增删改查
2020/12/22 Javascript
纯js的右下角弹窗实例
2017/03/12 Javascript
nodejs(officegen)+vue(axios)在客户端导出word文档的方法
2018/07/31 NodeJs
vue里input根据value改变背景色的实例
2018/09/29 Javascript
详解如何在Javascript和Sass之间共享变量
2019/11/13 Javascript
TypeScript魔法堂之枚举的超实用手册
2020/10/29 Javascript
对于Python中线程问题的简单讲解
2015/04/03 Python
Python中处理字符串之endswith()方法的使用简介
2015/05/18 Python
详解Python中的动态属性和特性
2018/04/07 Python
python中不能连接超时的问题及解决方法
2018/06/10 Python
Python多线程处理实例详解【单进程/多进程】
2019/01/30 Python
python实现ip代理池功能示例
2019/07/05 Python
代码实例讲解python3的编码问题
2019/07/08 Python
Python3 使用map()批量的转换数据类型,如str转float的实现
2019/11/29 Python
在Python中使用MongoEngine操作数据库教程实例
2019/12/03 Python
pytorch 常用线性函数详解
2020/01/15 Python
电钳专业个人求职信
2014/01/04 职场文书
幼儿园招生广告
2014/03/19 职场文书
新闻专业毕业生英文求职信
2014/03/19 职场文书
优秀党员自我评价范文
2014/09/15 职场文书
办理房产证委托书
2014/09/18 职场文书
党的群众路线教育实践活动个人对照检查材料(教师)
2014/11/04 职场文书
Win11怎么添加用户?Win11添加用户账户的方法
2022/07/15 数码科技