最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python實現(xiàn)封裝得到virustotal掃描結(jié)果

 更新時間:2014年10月05日 15:25:34   投稿:shichen2014  
這篇文章主要介紹了python實現(xiàn)封裝得到virustotal掃描結(jié)果的方法,是比較實用的技巧,可將掃描結(jié)果寫入數(shù)據(jù)庫,需要的朋友可以參考下

本文實例講述了python實現(xiàn)封裝得到virustotal掃描結(jié)果的方法。分享給大家供大家參考。具體方法如下:

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 
#得到掃描結(jié)果并寫入數(shù)庫 
for md5 in MD5S: 
  virus_total = VirusTotal(md5) 
  virus_total.write_to_db() 

希望本文所述對大家的Python程序設(shè)計有所幫助。

相關(guān)文章

  • 用uWSGI和Nginx部署Flask項目的方法示例

    用uWSGI和Nginx部署Flask項目的方法示例

    這篇文章主要介紹了用uWSGI和Nginx部署Flask項目的方法示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2019-05-05
  • Python教程之pytest命令行方式運行用例

    Python教程之pytest命令行方式運行用例

    pytest有豐富的命令行選項,以滿足不同的需要,下面這篇文章主要給大家介紹了關(guān)于Python教程之pytest命令行方式運行的相關(guān)資料,需要的朋友可以參考下
    2021-12-12
  • python rsync服務(wù)器之間文件夾同步腳本

    python rsync服務(wù)器之間文件夾同步腳本

    這篇文章主要為大家詳細介紹了python rsync服務(wù)器之間文件夾同步腳本,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-08-08
  • Python之a(chǎn)scii轉(zhuǎn)中文的實現(xiàn)

    Python之a(chǎn)scii轉(zhuǎn)中文的實現(xiàn)

    這篇文章主要介紹了Python之a(chǎn)scii轉(zhuǎn)中文的實現(xiàn)方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-05-05
  • django 使用全局搜索功能的實例詳解

    django 使用全局搜索功能的實例詳解

    今天小編就為大家分享一篇django 使用全局搜索功能的實例詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-07-07
  • PyQt5 實現(xiàn)字體大小自適應(yīng)分辨率的方法

    PyQt5 實現(xiàn)字體大小自適應(yīng)分辨率的方法

    今天小編就為大家分享一篇PyQt5 實現(xiàn)字體大小自適應(yīng)分辨率的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-06-06
  • Python數(shù)據(jù)結(jié)構(gòu)鏈表操作從基礎(chǔ)到高級實例深究

    Python數(shù)據(jù)結(jié)構(gòu)鏈表操作從基礎(chǔ)到高級實例深究

    鏈表是一種基礎(chǔ)的數(shù)據(jù)結(jié)構(gòu),它由一系列節(jié)點組成,每個節(jié)點都包含數(shù)據(jù)和指向下一個節(jié)點的引用,在Python中,可以使用類來實現(xiàn)鏈表,本文將介紹如何實現(xiàn)鏈表,并提供一些豐富的示例代碼來幫助你更好地理解其原理和應(yīng)用
    2023-12-12
  • Python日志模塊logging的使用方法總結(jié)

    Python日志模塊logging的使用方法總結(jié)

    這篇文章主要分享的是Python日志模塊logging的使用方法總結(jié),ogging模塊默認級別是WARNING,意味著只會追蹤該級別以上的事件,除非更改日志配置,想了解更多相關(guān)資料的小伙伴可以參考下面文章內(nèi)容
    2022-05-05
  • Python中列表乘法和列表推導(dǎo)式的區(qū)別舉例詳解

    Python中列表乘法和列表推導(dǎo)式的區(qū)別舉例詳解

    在Python中列表是一種非常靈活和強大的數(shù)據(jù)結(jié)構(gòu),支持多種運算和操作,這篇文章主要介紹了Python中列表乘法和列表推導(dǎo)式區(qū)別的相關(guān)資料,文中通過代碼就介紹的非常詳細,需要的朋友可以參考下
    2025-04-04
  • python模擬重載初始化函數(shù)的方法詳解

    python模擬重載初始化函數(shù)的方法詳解

    重載初始化函數(shù),是指同一個類中定義了多個構(gòu)造函數(shù),可以通過多種不同的方法進行構(gòu)造,下面我們就來看看在python中如何實現(xiàn)類似的功能吧
    2024-11-11

最新評論

浦江县| 临西县| 汉阴县| 荆州市| 马山县| 辽阳县| 喀什市| 保靖县| 务川| 青岛市| 社旗县| 静宁县| 沭阳县| 彭水| 永修县| 蓝田县| 灌云县| 永福县| 南部县| 手机| 宁阳县| 峡江县| 马关县| 剑川县| 新巴尔虎左旗| 盘锦市| 遵化市| 玉屏| 合阳县| 大姚县| 淳安县| 普安县| 大英县| 孟州市| 禹城市| 香格里拉县| 阿图什市| 隆子县| 德州市| 天全县| 会昌县|