Python implements encapsulation to obtain the virustotal scan result, pythonvirustotal

Source: Internet
Author: User

Python implements encapsulation to obtain the virustotal scan result, pythonvirustotal

This example describes how to encapsulate virustotal scan results in python. Share it with you for your reference. The specific method is as follows:

Import simplejson import urllib import urllib2 import OS, sys import logging try: import sqlite3 failed t ImportError: sys. stderr. write ("ERROR: Unable to locate Python SQLite3 module. "\" Please verify your installation. exiting... \ n ") sys. exit (-1) MD5 = "failed" MD5 = "12fa5fb74201d9b6a14f63fbf9a81ff6" # do not have report on virustotal.com APIKEY = "xxxxxxxxxxxxxxxxxx" Use your own Class VirusTotalDatabase: "" Database isolation action 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 () failed t 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) handle T (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.exe cute ("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 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] 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 failed t 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 = encrypt ("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.exe cute ("SELECT id FROM virustotal WHERE md5 = ?; ", (Md5,) sample_row = self. _ cursor. fetchone () blocks t sqlite3.OperationalError, why: print "sqlite3 error: % s \ n" % str (why) return False if sample_row: try: sample_row = sample_row [0] self._cursor.exe cute ("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 handle T sqlite3.OperationalError, why: print ("Unable to update database: % s. "% why) return False else: # the sample not in the database try: self._cursor.exe cute (" insert into virustotal "\" (md5, Kaspersky, McAfee, Symantec, Norman, Avast, NOD32, BitDe Fender, \ Microsoft, Rising, Panda) "\" VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?); ", (Md5, Kaspersky, McAfee, Symantec, Norman, Avast, NOD32, BitDefender, \ Microsoft, Rising, Panda) self. _ conn. commit () task_id = self. _ cursor. lastrowid failed t 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 ("Data Base. 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.exe cute ("SELECT * FROM virustotal" \ # "WHERE lock = 0" \ # "AND status = 0" \ "order by id, added_on LIMIT 1 ;") handle t sqlite3.OperationalError, why: log. error ("Unable t O 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.exe cute ("SELECT * FROM virustotal" \ "WHERE md5 =? "\ #" AND status = 1 "\" order by id DESC; ", (md5,) handle T 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_co1_, 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)

The usage is as follows:

Config = {'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 # Get the scan result and write the data library for md5 in MD5S: virus_total = VirusTotal (md5) virus_total.write_to_db ()

I hope this article will help you with Python programming.


How to encapsulate the following code using python?

From ctypes import *
Class fft_downloader_params_udp_s (Structure ):
_ Fields _ = [
("ServerIp", c_char * IP_BYTES_MAX ),
("ServerPort", c_char * SERVER_PORT_BYTES_MAX ),
("InputFileName", c_char * FNAME_BYTES_MAX ),
]
For more information, see python gray hat.

How to encapsulate python into exe

Answer:
After actual tests, PyInstaller is easy to use.
You cannot perform tedious configuration. You can directly generate a single exe file by adding-F.
Great results.

Py2exe has never been used, but it requires complicated configuration and tossing to see online tutorials.
Therefore, PyInstaller is much easier to use than py2exe.

Details:
[Record] package the Python code BlogsToWordPress into an exe executable file.

(No post address is provided here. Please search for the title on google to find the post address)

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.