Пишем скрипт для работы с VirusTotal-ом

Joined
Aug 17, 2016
Messages
1,788
Reaction score
826
61834db370f449ee99b80.png

Приветствую всех! Сегодня я вам покажу как сделать скрипт, который будет загружать все что вы скачали на вирустотал, т.е это для того, чтобы не подхватить вирус. Возможно этот скрипт не будет вам полезен.

Недавно перешел на python3. Советую всем переходить))



Приступим к программированию !



По дефолту(у меня уже привычка) ставим это # -*- coding: utf-8 -*- в начале нашего скрипта.



Теперь импортируем библиотеки, которыми мы будем пользоваться.



Code:
from termcolor import *
import colorama
import os
import time
from sys import platform
import requests
import webbrowser

Я захотел сделать цветной текст, но в windows он не отображался, путем гугления нашел решение пишем: colorama.init()



Далее я создаю функцию которая отобразит банер нашего скрипта.
Code:
def banner():
    cprint('-' * 50,'green')
    cprint(' ' * 17 + 'DefendMySystem','red')
    cprint('-' * 50,'green')
Теперь я создаю функцию для очистки консоли(для красоты).

Code:
def cleaner():
    if platform == "linux" or platform == "linux2": # Определяю OC системы
        os.system('clear')
    if platform == "win32":
        os.system('cls')
Я решил, что часть настроек будет лежать в .conf файлах. Поэтому я написал функцию для проверки существования этих файлов.

Code:
def checkfiles():
    arr = os.listdir('.') # Список файлов в текущей дириктории
    for x in arr:
        if 'delay.conf' not in arr:
            handle = open('delay.conf','w')
            handle.close() # Если файла нету создать

        if 'api.conf' not in arr:
            handle = open('api.conf','w')
            handle.close() # Если файла нету создать

Потом я написал функцию настройки скрипта.

Code:
def setting():
    handle = open('config.conf')
    data = handle.read()
    handle.close()
 
    handle = open('delay.conf')
    data2 = handle.read()
    handle.close()
    if data2 == '': #Если конфиг пустой - настроить
        cprint("Установите задержку для проверки папки загрузки(в секундах)","cyan")
        delay = input(':')
        handle = open('delay.conf','w')
        handle.write(delay)
        handle.close()
        cleaner()
    handle = open('api.conf')
    data3 = handle.read()
    handle.close()

    if data3 == '': #Если конфиг пустой - настроить
        cprint("Введите ваш api ключ","cyan")
        webbrowser.open("https://www.virustotal.com/ru/", new=2)
        api = input(':')
        handle = open('api.conf','w')
        handle.write(api)
        handle.close()
        cleaner()

Далее я написал функцию отправки файла на вирустотал.

Code:
def sendfiles(filename,api):
    params = {'apikey': api} # Работу с api обычно документируют на сайте
    response = requests.post('https://www.virustotal.com/vtapi/v2/file/scan', files={'file': (filename, open(filename, 'rb'))}, params=params)
    json_response = response.json()
    dct = eval(str(json_response))
    link = dct['permalink']
    webbrowser.open(link, new=2)

Потом я написал главную функцию, которая выполняет всю тяжелую работу.

Code:
def main():
    temp = []
    path = 'C:\\Users\\Алекс\\Downloads\\' # Путь к папке куда файлы загружаются
                                            # С этой папки файлы будут слаться
    handle = open('delay.conf')
    delay = handle.read()
    handle.close()
    delay = int(delay) # Читаем конфиг

    handle = open('api.conf')
    api = handle.read() # Читаем конфиг
    handle.close()
    files = os.listdir(path) # Список файлов в path(переменная)
    while True: # Бесконечный цикл
        files2 = os.listdir(path) # Список файлов в path(переменная)
        if files != files2: # Если добавился новый файл
            for x in files2:
                if x not in files:
                    temp.append(x)
                    for x in temp:
                        filename = path + x
                    sendfiles(filename,api) # Мы его отправим и у нас откроется отчет со сканом
            temp = []
            files = files2
        time.sleep(delay) # Задержка цикла

Все готово! Теперь просто вызываю функции.


Code:
banner()
checkfiles()
setting()
try:
    main() # Если пользователь нажмет ctrl + c он просто выйдет, а не получит ошибку
except KeyboardInterrupt:
    exit()

Code:
Для удобства полный код:

Code:
# -*- coding: utf-8 -*-
from termcolor import *
import colorama
import os
import time
from sys import platform
import requests
import webbrowser

colorama.init()

def banner():
    cprint('-' * 50,'green')
    cprint(' ' * 17 + 'DefendMySystem','red')
    cprint('-' * 50,'green')

def cleaner():
    if platform == "linux" or platform == "linux2":
        os.system('clear')
    if platform == "win32":
        os.system('cls')


def checkfiles():
    arr = os.listdir('.')
    for x in arr:
        if 'delay.conf' not in arr:
            handle = open('delay.conf','w')
            handle.close()

        if 'api.conf' not in arr:
            handle = open('api.conf','w')
            handle.close()



def setting():
    handle = open('config.conf')
    data = handle.read()
    handle.close()
 
    handle = open('delay.conf')
    data2 = handle.read()
    handle.close()
    if data2 == '':
        cprint("Установите задержку для проверки папки загрузки(в секундах)","cyan")
        delay = input(':')
        handle = open('delay.conf','w')
        handle.write(delay)
        handle.close()
        cleaner()
    handle = open('api.conf')
    data3 = handle.read()
    handle.close()

    if data3 == '':
        cprint("Введите ваш api ключ","cyan")
        webbrowser.open("https://www.virustotal.com/ru/", new=2)
        api = input(':')
        handle = open('api.conf','w')
        handle.write(api)
        handle.close()
        cleaner()

def sendfiles(filename,api):
    params = {'apikey': api}
    response = requests.post('https://www.virustotal.com/vtapi/v2/file/scan', files={'file': (filename, open(filename, 'rb'))}, params=params)
    json_response = response.json()
    dct = eval(str(json_response))
    link = dct['permalink']
    webbrowser.open(link, new=2)

def main():
    temp = []
    path = 'C:\\Users\\Алекс\\Downloads\\'

    handle = open('delay.conf')
    delay = handle.read()
    handle.close()
    delay = int(delay)

    handle = open('api.conf')
    api = handle.read()
    handle.close()
    files = os.listdir(path)
    while True:
        files2 = os.listdir(path)
        if files != files2:
            for x in files2:
                if x not in files:
                    temp.append(x)
                    for x in temp:
                        filename = path + x
                    sendfiles(filename,api)
            temp = []
            files = files2
        time.sleep(delay)

banner()
checkfiles()
setting()
try:
    main()
except KeyboardInterrupt:
    exit()

На этом все. Спасибо за чтение статьи!

PS Моя версия python 3.7
 
Top