Here's my code for quickly uploading files to virustotal and retrieving the reports.
import postfile
import sys
import json
from StringIO import StringIO
import urllib
import urllib2
import time
import webbrowser
apikey = 'YOUR API KEY ' + \
' GOES HERE '
resources = []
for i in range(1, len(sys.argv)):
file = sys.argv[i]
print 'Preparing Scan of %s ...' % file
host = 'www.virustotal.com'
selector = 'https://www.virustotal.com/vtapi/v2/file/scan'
fields = [('apikey', apikey)]
file_to_send = open(file, 'rb').read()
files = [('file', file, file_to_send)]
print 'Uploading file...'
ret = postfile.post_multipart(host, selector, fields, files)
try:
data = json.loads(ret)
except ValueError:
print 'Cannot decode server response: '
print ret
exit()
print 'Upload done.'
# for k in data: print '%s: %s' % (k, data[k])
resources.append((file, data['resource']))
print 'Retreiving reports...'
i = 1
permalinks = []
for resource in resources:
response_code = 0
while response_code == 0:
url = 'https://www.virustotal.com/vtapi/v2/file/report'
parameters = {
'resource': resource[1],
'apikey': apikey
}
data = urllib.urlencode(parameters)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
ret = response.read()
data = json.loads(ret)
response_code = data['response_code']
#print json.dumps(data, sort_keys=True, indent=4)
if response_code == 0: time.sleep(5)
#print json.dumps(data, sort_keys=True, indent=4)
permalinks.append(data['permalink'])
print '%2i: %s' % (i, resource[0]),
print ': %i / %i' % (data['positives'], data['total'])
i += 1
wb = webbrowser.get()
selection = 0
while selection >= 0 and selection < len(permalinks):
selection = int(raw_input('Open: '))-1
if selection >= 0 and selection < len(permalinks):
wb.open(permalinks[selection])
P.S.: This is all part of a great plan I'm following at the moment.
Edit (2013-09-05): Since the VirusTotal API is now out there for a while, a lot of awesome python libraries have emerged:
* https://github.com/Erethon/vta.py
* https://github.com/Gawen/virustotal
* https://github.com/botherder/virustotal
* https://github.com/Xen0ph0n/VirusTotal_API_Tool
One Reply to “VirusTotal Python Script”