Python implementation encapsulation gets virustotal scan results _python

Source: Internet
Author: User
Tags commit md5 sqlite sqlite database

The example in this article describes how Python implements encapsulation to get virustotal scan results. Share to everyone for your reference. The specific method is as follows:

Import Simplejson Import urllib import urllib2 import OS, sys import logging try:import sqlite3 except Import Error:sys.stderr.write ("error:unable to locate Python SQLite3 module." \ "Please verify your installatio N. exiting...\n ") sys.exit ( -1) MD5 =" 5248F774D2EE0A10936D0B1DC89107F1 "MD5 =" 12fa5fb74201d9b6a14f63fbf9a81ff6 " #do not have the virustotal.com Apikey = "xxxxxxxxxxxxxxxxxx" with its own class Virustotaldatabase: "" "Da 
  Tabase 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 Connec 
    tion. Try:self._conn = Sqlite3.connect (self.__dbfile) self._cursor = Self._conn.cursor () except Exception, W 
           Hy: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 ("S Omething went wrong while creating database "\" directory \%s\ ":%s"% (Db_dir, why)) return Fals E 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["Bitdefend" er "] = row[8] task[" Microsoft "= row[9] task[" rising "] = row[10] task[" Panda "] = row[11] Retu  
    RN 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.ge T ("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 ("Micro Soft ", 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:t Ry:sample_row = sample_row[0] Self._cursor.execute ("UPDATE virustotal SET kaspersky=?, mcafee=?, Symant  ec=, norman=, avast=?, nod32=, bitdefender=, microsoft=, rising=? 
                   WHERE id =?; ", (Kaspersky, McAfee, Symantec, Norman, Avast, NOD32, BitDefender, microsoft,\ Rising, Panda, Sample_row)) self._conn.commit () task_id = Sample_row except.  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, Ava St, NOD32, bitdefender,\ Microsoft, Rising, Panda) self._conn.commit () task_id = s Elf._cursor.lastrowid except Sqlite3. Operationalerror, Why:print "Why", str (why) return None print "add_to_db:%s, task_id:%s"% (Str (s 
    Elf.__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 no 
    T already been processed. Try:self._cursor.execute ("Select * FROM VI")Rustotal "\ #" 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 (m d5)!= 32:return None try:self._cursor.execute ("SELECT * from VirusTotal" \ "whe RE MD5 =? "\ #" and status = 1 "\" ORDER by ID DESC; ", (MD5,)) except Sq Lite3. 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._vi Rus_dict = {} SELF._MD5 = MD5 Self._db_file = r "./db/virustotal.db" Self.get_report_dict () def Rep                                      
    R (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://w Ww.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 = 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.s 
    Etdefault (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)

Use the following methods:

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 
#得到扫描结果并写入数库 to 
MD5 in md5s: 
  virus_total = VirusTotal (MD5) 
  virus_total.write_to_db () 

I hope this article will help you with your Python programming.

Related Article

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.