Python implementation package gets VirusTotal scan results

Source: Internet
Author: User
This article describes a Python implementation method that encapsulates the results of a virustotal scan. Share to everyone for your reference. Here's how:

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 the report on virustotal.com APIKEY = "xxxxxxxxxxxxxxxxxx" with your own class Virustotaldatabase: "" "Database Abstrac   tion 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 have 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.PA Th.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 T EXT default null,\n "\" BitDefender text DEFAULT null,\n "\" Microsoft text D Efault 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] Ta sk["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 Non E 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 = V Irus_dict.get ("NOD32", none) BitDefender = Virus_dict.get ("BitDefender", none) Microsoft = Virus_dict.get ("Microso FT ", 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=?, N  Orman=, 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.") return False Else: #the Sample No  T in the database Try:self._cursor.execute ("INSERT into VirusTotal" \ "(MD5, Kaspersky,                    McAfee, Symantec, Norman, Avast, NOD32, bitdefender,\ Microsoft, Rising, Panda) "\ The VALUES (?,?,?,?,?,?,?,?,?,?,?); ", (MD5, Kaspersky, McAfee, Symantec, Norman, Avast, NOD32, bitdefender,\ Microsoft, Rising, Panda)) self._conn.commit () task_id = Self._cursor.lastrowid except S Qlite3. Operationalerror, Why:print "Why", str (why) return to 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 H     As 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.") 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 stat US = 1 "\" ORDER by ID DESC; ", (MD5,)) except Sqlite3. Operationalerror, Why:return None task_dict = {} for row in Self._cursor.fetchall (): Task_dict = sel   F._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_pat H, "RB"). Read () files = [("File", file_name, file_to_send)] json = P Ostfile.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"]) retur n 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)

Here's how to use it:

Config = {' input ': ' inputmd5s '} fp = open (config[' input '], "r") content = Fp.readlines () md5s = [] for MD5 in IFilter (LAMBD A 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)   

Hopefully this article will help you with Python programming.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.