def virustotal(host): # VT接口,主要用来查询PDNS,绕过CDN pdns = [] history_ip = [] # sys.stdout.write(bcolors.RED + "\nPDNS:\n" + bcolors.ENDC) if VIRUSTOTAL_API: try: vtotal = Virustotal(VIRUSTOTAL_API) if re.search(r'\d+\.\d+\.\d+\.\d+', host): return None resp = vtotal.domain_report(host) if resp.get('status_code') != 403: for i in resp.get('json_resp').get('resolutions'): address = i.get('ip_address') timeout = i.get('last_resolved') if iscdn(address): history_ip.append(address + ' : ' + timeout) pdns = history_ip[10:] except: pass pdns.extend(ipinfo(host)) if pdns: for i in pdns[:10]: console('PDNS', host, i + '\n') else: console('PDNS', host, 'None\n') return pdns
def judge(self, filepath): ''' virustotal에 특정 파일 검사 :param filepath: 검사 대상 path :param api_key: virustotal API_KEY :return: 결과 boolean True : Non-malware, False : malware ''' # Normal Initialisation. vtotal = Virustotal(self.api_key) result = vtotal.file_scan(filepath) print('>> Virustotal Search report. <<') json_resp = result['json_resp'] md5 = json_resp['md5'].strip() print('result link : ', json_resp['permalink']) url = 'https://www.virustotal.com/vtapi/v2/file/report' params = {'apikey': self.api_key, 'resource': md5} response = requests.get(url, params=params) total = response.json()['total'] positives = response.json()['positives'] print('Result : (' + str(total) + ' / ' + str(positives) + ')') if positives == 0: vtotal_judge = True else: vtotal_judge = False # 최종 검사 결과, 탐지 횟 수 return vtotal_judge, positives, total, json_resp['permalink']
def isBadFileHash(self, fileHash, virustotal_api=None, session_id=None): try: if not virustotal_api: virustotal_api = ht.Config.getAPIKey('virustotal_api', session_id) self.vtotal = Virustotal(virustotal_api) resp = self.vtotal.file_report([fileHash]) if resp["status_code"] in (200, 204): if resp["status_code"] == 204: Logger.printMessage( message="isBadFileHash", description="Testing - {hash} - Waiting 2 seconds...". format(hash=fileHash), debug_module=True) time.sleep(2) return self.isBadFileHash(fileHash, virustotal_api) while resp["json_resp"]["response_code"] == -2: Logger.printMessage( message="isBadFileHash", description="Testing - {hash} - Waiting 2 seconds...". format(hash=fileHash), debug_module=True) time.sleep(2) return self.isBadFileHash(fileHash, virustotal_api) no_detected_list = [] detected_list = [] detected_types = [] for antivirus in resp["json_resp"]["scans"]: if resp["json_resp"]["scans"][antivirus]["detected"]: detected_list.append( (antivirus, resp["json_resp"]["scans"][antivirus]["version"])) if not resp["json_resp"]["scans"][antivirus][ "result"] in detected_types: detected_types.append(resp["json_resp"]["scans"] [antivirus]["result"]) else: no_detected_list.append( (antivirus, resp["json_resp"]["scans"][antivirus]["version"])) if detected_list: data = {} data["detected_list"] = detected_list data["detected_types"] = detected_types data["no_detected_list"] = no_detected_list return json.dumps({"Detected": data}, indent=4, sort_keys=True) return json.dumps({"No detected": no_detected_list}, indent=4, sort_keys=True) return resp except Exception as e: Logger.printMessage(message="isBadFileHash", description=str(e), is_error=True) return str(e)
def virustotal_object(request): API_KEY = "Insert API Key Here." yield Virustotal(API_KEY) def fin(): """ Sleep for 30 seconds after each test; to avoid Virustotal 403 rate quota limit. """ print("Sleeping for 30 seconds...") sleep(30) request.addfinalizer(fin)
def check_api(key): try: urllib.request.urlopen('https://www.duckduckgo.com') # opens url to check internet connection scanner = Virustotal(key) scanner.url_scan(['www.vulnweb.com']) report = scanner.url_report(['www.vulnweb.com']) if report['status_code'] == 403: # checks if status code is 403 return True else: return False except urllib.error.URLError: input('Connect to internet...') exit()
def virustotal(host): # VT接口,主要用来查询PDNS,绕过CDN vtotal = Virustotal(virustotal_api) if re.search(r'\d+\.\d+\.\d+\.\d+', host): return ['None'] resp = vtotal.domain_report(host) history_ip = [] if resp.get('status_code') != 403: for i in resp.get('json_resp').get('resolutions'): address = i.get('ip_address') timeout = i.get('last_resolved') if iscdn(address): history_ip.append(address + ' : ' + timeout) return history_ip[-10:] else: return ['None']
def check_file(key, file): msg() # prints scanning message scanner = Virustotal(key) # passing api key to Virustotal class scanner.file_scan(file) # scans the file for virus with open(file, 'rb') as f: # opens file in read binary mode read = f.read() # reads opened file file_hash = hashlib.sha256(read).hexdigest() # Get sha256 hash of file report = scanner.file_report([file_hash]) # passing hash value of file to file_report function and returns report try: print('\n\nREPORT:\nStatus code:', report['status_code']) # Prints all the reports print('Scan date:', report['json_resp']['scan_date']) print('Verbose msg:', report['json_resp']['verbose_msg']) print('Antivirus Scanned:', report['json_resp']['total']) print('Positives:', report['json_resp']['positives']) print('sha256:', report['json_resp']['sha256']) print('md5:', report['json_resp']['md5']) except KeyError: print('\n""Maximum four scans per minute""')
def isBadFile(self, filename, virustotal_api=None): try: if not virustotal_api: virustotal_api = ht.Config.config['API']['virustotal'] Logger.printMessage(message="isBadFile", description=filename, debug_module=True) self.vtotal = Virustotal(virustotal_api) response = self.vtotal.file_scan(filename) if response["status_code"] == 200: scan_id = str(response["json_resp"]["scan_id"]) time.sleep(2) resp = self.isBadFileHash(scan_id, virustotal_api) return resp except Exception as e: Logger.printMessage(message="isBadFile", description=str(e), is_error=True) return str(e)
def check_url(key): url = input('\nEnter URL: ') # Get url from the user try: urllib.request.urlopen('http://' + url) # Checks the given url is valid msg() # prints scanning message scanner = Virustotal(key) # passing api key to Virustotal class scanner.url_scan([url]) # passing url to url_scan function report = scanner.url_report([url]) # returns report of the url try: print('\n\nREPORT:\nStatus_code:', report['status_code']) # Prints all the reports print('Scan date:', report['json_resp']['scan_date']) print('URL:', report['json_resp']['url']) print('Verbose msg:', report['json_resp']['verbose_msg']) print('Total Scanned:', report['json_resp']['total']) print('Positives:', report['json_resp']['positives']) except KeyError: print('\n""Maximum four scans per minute""') # prints if you reach maximum attempts except: print('Invalid URL')
CONFIG = json.load(f) except FileNotFoundError: with open("Config.json", "w") as f: json.dump( { 'Discord_Bot_Token': 'YOURTOKEN', 'VirusTotalToken': 'YOURTOKEN', 'YourDiscordId': '0', 'Prefix': '&' }, f) raise Exception( "Missing Config.json. I added it, please fill it out yourself! (Intended at first excecution)" ) print("url tester unit loaded with key " + CONFIG['VirusTotalToken']) vtotal = Virustotal(API_KEY=CONFIG['VirusTotalToken'], API_VERSION="v3") async def get_url_embed(url: str, ctx): embed = discord.Embed(title="VirusTotalBot URL Check", description="Information about " + url, color=discord.Colour.green()) embed.set_author(name=str(ctx.author)) try: # See https://github.com/dbrennand/virustotal-python resp = vtotal.request("urls", data={"url": url}, method="POST") await sleep( 12 ) # This is supoptimal but seems to be necessary in order of ensuring that the url gets testet url_id = urlsafe_b64encode(url.encode()).decode().strip("=") analysis_resp = vtotal.request(f"urls/{url_id}")
def __init__(self, file, pefile_parsed=None, lief_parsed=None): super().__init__(file, pefile_parsed, lief_parsed) self.endpoint = Virustotal(API_KEY=VIRUSTOTAL_API_KEY)
import os import sqlite3 import json import shutil import hashlib from virustotal_python import Virustotal vtotal = Virustotal("Insert API key here") cwd = "/home/pixelweaver/.cuckoo" init_db = False if not os.path.isfile('samples.db'): init_db = True else: if os.path.isfile('samples.bak'): os.remove('samples.bak') shutil.copyfile('samples.db', 'samples.bak') conn = sqlite3.connect('samples.db') c = conn.cursor() if init_db: c.execute('''CREATE TABLE samples (rowid INTEGER PRIMARY KEY, sha256 TEXT, mark_count INTEGER)''') c.execute('''CREATE TABLE snapshots (sample_id INTEGER, cpu_user REAL, cpu_system REAL, cpu_idle REAL, cpu_interrupt REAL, cpu_dpc REAL, v_mem_total INTEGER, v_mem_available INTEGER, v_mem_used INTEGER, v_mem_free INTEGER, s_mem_total INTEGER, s_mem_used INTEGER, s_mem_free INTEGER, s_mem_per REAL, s_mem_sin INTEGER, s_mem_sout INTEGER, d_io_read_count INTEGER, d_io_write_count INTEGER, d_io_read_bytes INTEGER, d_io_write_bytes REAL, d_io_read_time INTEGER, d_io_write_time INTEGER, n_io_bytes_sent INTEGER, m_io_bytes_recv INTEGER, n_io_packets_sent INTEGER, n_io_packets_recv INTEGER,
from virustotal_python import Virustotal import os # from dotenv import load_dotenv import random # load_dotenv(dotenv_path='./secret.env') # Normal Initialisation. vtotal = Virustotal(os.environ.get('VIRUS_TOTAL_API_KEY')) observations = [ "This is disgusting. I hate my life.", "This URL may contain harmful code. . . Let's let Marvin look at it first :unamused:", "I hope this kills me.", "This could be my last web request. . .", "This is @ihuman 's fault, and I will never forget." ] def get_scan(url): # mock_report = # report = json.loads(mock_report) # Query url(s) to VirusTotal. # A list containing a url to be scanned by VirusTotal. # resp = vtotal.url_scan(["ihaveaproblem.info"]) # Query a single url. # A list of url(s) to be scanned by VirusTotal (MAX 4 per standard request rate). scan = vtotal.url_scan( [url] ) # Retrieve scan report(s) for given file(s) from Virustotal. # A list containing the resource (SHA256) HASH of a known malicious file. report = vtotal.url_report(
async def vt(event): await event.edit(f"Analyzing Datas......") input_str = event.pattern_match.group(1) if not os.path.isdir(TEMP_DOWNLOAD_DIRECTORY): os.makedirs(TEMP_DOWNLOAD_DIRECTORY) if "|" in input_str: url, file_name = input_str.split("|") url = url.strip() file_name = file_name.strip() head, tail = os.path.split(file_name) if head: if not os.path.isdir(os.path.join(TEMP_DOWNLOAD_DIRECTORY, head)): os.makedirs(os.path.join(TEMP_DOWNLOAD_DIRECTORY, head)) file_name = os.path.join(head, tail) downloaded_file_name = TEMP_DOWNLOAD_DIRECTORY + "" + file_name downloader = SmartDL(url, downloaded_file_name, progress_bar=False) downloader.start(blocking=False) c_time = time.time() display_message = None while not downloader.isFinished(): status = downloader.get_status().capitalize() total_length = downloader.filesize if downloader.filesize else None downloaded = downloader.get_dl_size() now = time.time() diff = now - c_time percentage = downloader.get_progress() * 100 speed = downloader.get_speed() elapsed_time = round(diff) * 1000 progress_str = "[{0}{1}] {2}%".format( ''.join(["█" for i in range(math.floor(percentage / 10))]), ''.join(["░" for i in range(10 - math.floor(percentage / 10))]), round(percentage, 2)) estimated_total_time = downloader.get_eta(human=True) try: current_message = f"{status}..\ \nURL: {url}\ \nFile Name: {file_name}\ \n{progress_str}\ \n{humanbytes(downloaded)} of {humanbytes(total_length)}\ \nETA: {estimated_total_time}" if round(diff % 10.00) == 0 and current_message != display_message: await event.edit(current_message) display_message = current_message except Exception as e: LOGS.info(str(e)) if downloader.isSuccessful(): await event.edit(f"{text} \n\nDownloaded successfully !!") else: await event.edit("Incorrect URL\n{}".format(url)) elif event.reply_to_msg_id: try: c_time = time.time() downloaded_file_name = await event.client.download_media( await event.get_reply_message(), TEMP_DOWNLOAD_DIRECTORY, progress_callback=lambda d, t: asyncio.get_event_loop( ).create_task( progress(d, t, event, c_time, f"{text} \n\nDownloading..."))) except Exception as e: # pylint:disable=C0103,W0703 await event.edit(str(e)) else: await event.edit(f"{text} \n\nDownloaded successfully !!") else: return await event.edit(f"Error\n`Reply to a file to scan.`") await event.edit(" `Scanning......`") vscan = downloaded_file_name if a ==2: return await event.edit("`You need to Update wolfs to use this command.......`") if not vscan: return await event.edit("`Unknown command type !help virus_scan for more info`") try: vtotal = Virustotal(Vapi) except: return await event.edit("Failed to connect virus total , is api key added? type `!help virus_scan` for more info") try: vr = vtotal.file_scan(vscan) except: return await event.edit("`Unknown command type !help virus_scan for more info") test = vr['json_resp'] ; link = test['permalink'] ; scan_id = test['scan_id'] ; response_code = test['response_code'] return await event.edit("" f"• **Virus Total Response Code:** `{response_code}`\n" f"• **Scan Results:** [ClickHere]({link}) ")
from virustotal_python import Virustotal import time import json from pprint import pprint import re # api_key = <YOUR VIRUSTOTAL API KEY> get one here: https://developers.virustotal.com/reference # save your api key in a text file named "vt_api.txt". This snippet of code will read the api key instead of hardcoding it, for security. # or delete this and hard code it above with open("vt_api.txt", "r") as f: api_key = f.readline() vtotal = Virustotal(api_key) # virustotal API key # the urls flagged malicious are saved here LIKELY_PHISHES = [] API_LIMIT_SECONDS = 15 GET_SCAN_REPORT_SECONDS = 5 def main(): print( "Welcome. Enter 1 or more URLS. Press ENTER again after last entry:") urls = get_urls() decoded_urls = decode_url(urls) scan_all_urls(decoded_urls) print( str(len(LIKELY_PHISHES)) + " out of " + str(len(decoded_urls)) + " are phishes.\nHere they are:") display_phishes()
Auth = 'Bearer ' + Access_Token headers2 = {'Authorization': Auth, 'Content-Type': 'text/plain'} response2 = requests.post(Url2, headers=headers2, data=payload2).json() print("[+] Incident Details were received Successfully") #Entities loading Entities = response2["Tables"][0]["Rows"][0][21] Parsed_Entities = json.loads(Entities) print("[+] Entities were received Successfully") for i in range(len(Parsed_Entities)): if "Value" in Parsed_Entities[i]: hash = Parsed_Entities[i]["Value"] vtotal = Virustotal(API_KEY=VT_API_KEY, API_VERSION="v3") """ Public API constraints and restrictions The Public API is limited to 500 requests per day and a rate of 4 requests per minute. The Public API must not be used in commercial products or services. The Public API must not be used in business workflows that do not contribute new files. """ VT_resp = vtotal.request(f"files/{hash}").json() results = VT_resp["data"]["attributes"]["last_analysis_results"] magic = VT_resp["data"]["attributes"]["magic"] print("[+] The File Magic is: " + magic) for key, value in results.items(): print("[+] " + value["engine_name"] + " - The scan result is: " +
from virustotal_python import Virustotal from pprint import pprint import json import streamlit as st url = st.text_input('Enter the url') vtotal = Virustotal( "939b160778c93a24ed0985dbc90a98d2def25cf82ed92046a95cfe553f63ade1") url_scan = vtotal.url_report([url]) a = url_scan['json_resp']['positives'] if (a > 0): print('malicious website') else: print('Clean Website')
def virustotal(host): # VT接口,主要用来查询PDNS,绕过CDN vtotal = Virustotal(virustotal_api) if re.search(r'\d+\.\d+\.\d+\.\d+', host): return ['None'] resp = vtotal.domain_report(host) history_ip = [] # 通过VT查询pdns,然后排除国内外常见的cdn段,如果出现极有可能是真实ip cdns = [ '173.245.48.0/20', '103.21.244.0/22', '103.22.200.0/22', '103.31.4.0/22', '141.101.64.0/18', '108.162.192.0/18', '190.93.240.0/20', '188.114.96.0/20', '197.234.240.0/22', '198.41.128.0/17', '162.158.0.0/15', '104.16.0.0/12', '172.64.0.0/13', '131.0.72.0/22', '13.124.199.0/24', '144.220.0.0/16', '34.226.14.0/24', '52.124.128.0/17', '54.230.0.0/16', '54.239.128.0/18', '52.82.128.0/19', '99.84.0.0/16', '52.15.127.128/26', '35.158.136.0/24', '52.57.254.0/24', '18.216.170.128/25', '13.54.63.128/26', '13.59.250.0/26', '13.210.67.128/26', '35.167.191.128/26', '52.47.139.0/24', '52.199.127.192/26', '52.212.248.0/26', '205.251.192.0/19', '52.66.194.128/26', '54.239.192.0/19', '70.132.0.0/18', '13.32.0.0/15', '13.224.0.0/14', '13.113.203.0/24', '34.195.252.0/24', '35.162.63.192/26', '34.223.12.224/27', '13.35.0.0/16', '204.246.172.0/23', '204.246.164.0/22', '52.56.127.0/25', '204.246.168.0/22', '13.228.69.0/24', '34.216.51.0/25', '71.152.0.0/17', '216.137.32.0/19', '205.251.249.0/24', '99.86.0.0/16', '52.46.0.0/18', '52.84.0.0/15', '54.233.255.128/26', '130.176.0.0/16', '64.252.64.0/18', '52.52.191.128/26', '204.246.174.0/23', '64.252.128.0/18', '205.251.254.0/24', '143.204.0.0/16', '205.251.252.0/23', '52.78.247.128/26', '204.246.176.0/20', '52.220.191.0/26', '13.249.0.0/16', '54.240.128.0/18', '205.251.250.0/23', '52.222.128.0/17', '54.182.0.0/16', '54.192.0.0/16', '34.232.163.208/29', '58.250.143.0/24', '58.251.121.0/24', '59.36.120.0/24', '61.151.163.0/24', '101.227.163.0/24', '111.161.109.0/24', '116.128.128.0/24', '123.151.76.0/24', '125.39.46.0/24', '140.207.120.0/24', '180.163.22.0/24', '183.3.254.0/24', '223.166.151.0/24', '113.107.238.0/24', '106.42.25.0/24', '183.222.96.0/24', '117.21.219.0/24', '116.55.250.0/24', '111.202.98.0/24', '111.13.147.0/24', '122.228.238.0/24', '58.58.81.0/24', '1.31.128.0/24', '123.155.158.0/24', '106.119.182.0/24', '180.97.158.0/24', '113.207.76.0/24', '117.23.61.0/24', '118.212.233.0/24', '111.47.226.0/24', '219.153.73.0/24', '113.200.91.0/24', '1.32.240.0/24', '203.90.247.0/24', '183.110.242.0/24', '202.162.109.0/24', '182.23.211.0/24', '1.32.242.0/24', '1.32.241.0/24', '202.162.108.0/24', '185.254.242.0/24', '109.94.168.0/24', '109.94.169.0/24', '1.32.243.0/24', '61.120.154.0/24', '1.255.41.0/24', '112.90.216.0/24', '61.213.176.0/24', '1.32.238.0/24', '1.32.239.0/24', '1.32.244.0/24', '111.32.135.0/24', '111.32.136.0/24', '125.39.174.0/24', '125.39.239.0/24', '112.65.73.0/24', '112.65.74.0/24', '112.65.75.0/24', '119.84.92.0/24', '119.84.93.0/24', '113.207.100.0/24', '113.207.101.0/24', '113.207.102.0/24', '180.163.188.0/24', '180.163.189.0/24', '163.53.89.0/24', '101.227.206.0/24', '101.227.207.0/24', '119.188.97.0/24', '119.188.9.0/24', '61.155.149.0/24', '61.156.149.0/24', '61.155.165.0/24', '61.182.137.0/24', '61.182.136.0/24', '120.52.29.0/24', '120.52.113.0/24', '222.216.190.0/24', '219.159.84.0/24', '183.60.235.0/24', '116.31.126.0/24', '116.31.127.0/24', '117.34.13.0/24', '117.34.14.0/24', '42.236.93.0/24', '42.236.94.0/24', '119.167.246.0/24', '150.138.149.0/24', '150.138.150.0/24', '150.138.151.0/24', '117.27.149.0/24', '59.51.81.0/24', '220.170.185.0/24', '220.170.186.0/24', '183.61.236.0/24', '14.17.71.0/24', '119.147.134.0/24', '124.95.168.0/24', '124.95.188.0/24', '61.54.46.0/24', '61.54.47.0/24', '101.71.55.0/24', '101.71.56.0/24', '183.232.51.0/24', '183.232.53.0/24', '157.255.25.0/24', '157.255.26.0/24', '112.25.90.0/24', '112.25.91.0/24', '58.211.2.0/24', '58.211.137.0/24', '122.190.2.0/24', '122.190.3.0/24', '183.61.177.0/24', '183.61.190.0/24', '117.148.160.0/24', '117.148.161.0/24', '115.231.186.0/24', '115.231.187.0/24', '113.31.27.0/24', '222.186.19.0/24', '122.226.182.0/24', '36.99.18.0/24', '123.133.84.0/24', '221.204.202.0/24', '42.236.6.0/24', '61.130.28.0/24', '61.174.9.0/24', '223.94.66.0/24', '222.88.94.0/24', '61.163.30.0/24', '223.94.95.0/24', '223.112.227.0/24', '183.250.179.0/24', '120.241.102.0/24', '125.39.5.0/24', '124.193.166.0/24', '122.70.134.0/24', '111.6.191.0/24', '122.228.198.0/24', '121.12.98.0/24', '60.12.166.0/24', '118.180.50.0/24', '183.203.7.0/24', '61.133.127.0/24', '113.7.183.0/24', '210.22.63.0/24', '60.221.236.0/24', '122.227.237.0/24', '123.6.13.0/24', '202.102.85.0/24', '61.160.224.0/24', '182.140.227.0/24', '221.204.14.0/24', '222.73.144.0/24', '61.240.144.0/24', '36.27.212.0/24', '125.88.189.0/24', '120.52.18.0/24', '119.84.15.0/24', '180.163.224.0/24' ] if resp.get('status_code') != 403: for i in resp.get('json_resp').get('resolutions'): address = i.get('ip_address') timeout = i.get('last_resolved') result = True for cdn in cdns: if (ipaddress.ip_address(address) in ipaddress.ip_network(cdn)): result = False if result: history_ip.append(address + ' : ' + timeout) return history_ip[-10:] else: return ['None']
def set_virus_total_key(self, key): self.virus_total = Virustotal(key)
import requests from virustotal_python import Virustotal import os.path import time import 文件操作 # 初始化对象,填入API_Key # vtotal = Virustotal("51f9194a2d0e7d60cb7952f8bed2849a65617614e9edaa615c1e7d3ea45cb954") vtotal = Virustotal( "5af41c462b8cb6b9b02f1641ab3ebbbe6bc289b723de142c9765beb691f704b6") # 上传文件,参数为文件路径,返回值为查询结果 def scanFile(filePath): file_hash_list = [文件操作.getFileMD5(filePath)] try: resp = vtotal.file_report(file_hash_list) except Exception as e: print(e) time.sleep(5) try: resp = vtotal.file_report(file_hash_list) except Exception as err: print("重试失败") print(err) return None file_report_num = 0 while resp["status_code"] == 204: print("超过请求速率", filePath, "将在60S后重试") time.sleep(60) try:
import olefile import os import sys import shutil import hashlib from virustotal_python import Virustotal import json from pprint import pprint BUFFER_SIZE=8899 file_l=[] virus_total = Virustotal("#virus_total api key") def hash_to_vtotal(): global ole_win file_hash_SHA256= hashlib.sha256() file_hash_MD5=hashlib.md5() for file in file_l: with open(file,'rb') as f: file_bs=f.read(BUFFER_SIZE) while len(file_bs)>0: file_bs=f.read(BUFFER_SIZE) file_hash_SHA256.update(file_bs) file_hash_MD5.update(file_bs) print(file) print(file+":macro/vba detected") print(os.path.abspath(file)) print('SHA-256:',file_hash_SHA256.hexdigest()) print('MD5:',file_hash_MD5.hexdigest()) meta=ole_win.get_metadata() shutil.copy(file,sys.argv[2]) print('Macro copied to',sys.argv[2])
async def vt(event): await event.edit(f"Analyzing Datas......") input_str = event.pattern_match.group(1) if not os.path.isdir(TEMP_DOWNLOAD_DIRECTORY): os.makedirs(TEMP_DOWNLOAD_DIRECTORY) if "|" in input_str: url, file_name = input_str.split("|") url = url.strip() file_name = file_name.strip() head, tail = os.path.split(file_name) if head: if not os.path.isdir(os.path.join(TEMP_DOWNLOAD_DIRECTORY, head)): os.makedirs(os.path.join(TEMP_DOWNLOAD_DIRECTORY, head)) file_name = os.path.join(head, tail) downloaded_file_name = TEMP_DOWNLOAD_DIRECTORY + "" + file_name downloader = SmartDL(url, downloaded_file_name, progress_bar=False) downloader.start(blocking=False) c_time = time.time() display_message = None while not downloader.isFinished(): status = downloader.get_status().capitalize() total_length = downloader.filesize if downloader.filesize else None downloaded = downloader.get_dl_size() now = time.time() diff = now - c_time percentage = downloader.get_progress() * 100 speed = downloader.get_speed() elapsed_time = round(diff) * 1000 progress_str = "[{0}{1}] {2}%".format( ''.join(["█" for i in range(math.floor(percentage / 10))]), ''.join(["░" for i in range(10 - math.floor(percentage / 10))]), round(percentage, 2)) estimated_total_time = downloader.get_eta(human=True) try: current_message = f"{status}..\ \nURL: {url}\ \nFile Name: {file_name}\ \n{progress_str}\ \n{humanbytes(downloaded)} of {humanbytes(total_length)}\ \nETA: {estimated_total_time}" if round(diff % 10.00) == 0 and current_message != display_message: await event.edit(current_message) display_message = current_message except Exception as e: LOGS.info(str(e)) if downloader.isSuccessful(): await event.edit(f"{text} \n\nDownloaded successfully !!") else: await event.edit("Incorrect URL\n{}".format(url)) elif event.reply_to_msg_id: try: c_time = time.time() downloaded_file_name = await event.client.download_media( await event.get_reply_message(), TEMP_DOWNLOAD_DIRECTORY, progress_callback=lambda d, t: asyncio.get_event_loop( ).create_task( progress(d, t, event, c_time, f"{text} \n\nDownloading...") )) except Exception as e: # pylint:disable=C0103,W0703 await event.edit(str(e)) else: await event.edit(f"{text} \n\nDownloaded successfully !!") else: return await event.edit(f"Error\n`Reply to a file to scan.`") await event.edit(" `Scanning......`") vscan = downloaded_file_name if not vscan: return await event.edit("`downloaded_file missing`") try: vtotal = Virustotal(Vapi) except: return await event.edit( "Failed to connect virus total , is api key added? type `!help virus_scan` for more info" ) try: vr = vtotal.file_scan(vscan) test = vr['json_resp'] link = test['permalink'] scan_id = test['scan_id'] response_code = test['response_code'] return await event.edit( "" f"• **Virus Total Response Code:** `{response_code}`\n" f"• **Scan Results:** [ClickHere]({link}) ") except: url = "https://www.virustotal.com/vtapi/v2/file/scan" params = {"apikey": Vapi} files = { "file": (downloaded_file_name, open(downloaded_file_name, "rb")) } response = requests.post(url, files=files, params=params) try: a = response.json() b = a["permalink"] except Exception as e: await event.edit(str(e)) try: await event.edit( f"<b><u> File Scan Request Complete</u></b>\n\n<b>Link of the report:-</b>\n{b}\n\nNote:- Please open the link after 5-10 minutes.", parse_mode="HTML", ) except Exception as e: await event.edit(str(e)) else: await event.edit("Some Internal Issus")
Retrieve information about a file from the VirusTotal API. Documentation: * v2 documentation - https://developers.virustotal.com/reference#file-report * v3 documentation - https://developers.virustotal.com/v3.0/reference#file-info """ from virustotal_python import Virustotal from pprint import pprint API_KEY = "Insert API key here." # The ID (either SHA-256, SHA-1 or MD5) identifying the file FILE_ID = "9f101483662fc071b7c10f81c64bb34491ca4a877191d464ff46fd94c7247115" # v2 example vtotal = Virustotal(API_KEY=API_KEY) resp = vtotal.request("file/report", {"resource": FILE_ID}) print(resp.response_code) pprint(resp.json()) # v3 example vtotal = Virustotal(API_KEY=API_KEY, API_VERSION="v3") resp = vtotal.request(f"files/{FILE_ID}") pprint(resp.data)
def main(): parser = argparse.ArgumentParser( description= "Scan a single file in VirusTotal and waits until report is complete") parser.add_argument('file', help='File to be scanned') args = parser.parse_args() if 'VT_API_KEY' not in os.environ: LOGGER.error('VT_API_KEY environment variable not set.') sys.exit(SCAN_ERROR) LOGGER.debug('Initialzing VirusTotal API') vt_api_key = os.environ['VT_API_KEY'] vt = Virustotal(vt_api_key) # Hash file LOGGER.info('Checking if report already exists via file hash.') file_hash = sha256sum(args.file) try: response = vt.file_report([file_hash]) except ConnectionError as e: err_str = str(e) LOGGER.error(f"Connection error to VT: {err_str}.") sys.exit(SCAN_ERROR) ret = parse_response(response) # If report is available, just exit with the appropriate RC if ret != SCAN_NOT_FOUND: ret_str = RET_STR_INFECTED if ret else RET_STR_CLEAN LOGGER.info(f"Report found. Status: {ret_str}.") sys.exit(ret) # Send file to VT for scanning try: LOGGER.info( 'Report not found. Sending file to VirusTotal for scanning.') vt.file_scan(args.file) except ConnectionError as e: err_str = str(e) LOGGER.error(f"Connection error to VT: {err_str}") sys.exit(SCAN_ERROR) while ret == SCAN_NOT_FOUND: LOGGER.info(f"Scan still running, sleeping for {WAIT_TIME} seconds.") sleep(WAIT_TIME) # Try again try: response = vt.file_report([file_hash]) except ConnectionError as e: err_str = str(e) LOGGER.error( f"Temporary connection error to VT: {err_str}... Retrying in {WAIT_TIME} seconds." ) continue ret = parse_response(response) ret_str = RET_STR_INFECTED if ret else RET_STR_CLEAN LOGGER.info(f"Scan finished. Status: {ret_str}.") sys.exit(ret)
#!/usr/bin/python3 #Author: Nicholas Roddy #The goal of this program is to take a malicious URL and defang it inorder to allow it to be shared safely, or for it to be refanged for further analysis. #Additionally, this program takes the refanged URL and runs scans against it using the Virus Total API and returns the results for initial analysis. #Imports modules for menu and defanging process import argparse from pprint import pprint from defang import defang, refang from pyfiglet import Figlet from colorama import init, Fore, Style from virustotal_python import Virustotal from virustotal_python.virustotal import VirustotalError init(convert=True) #Allows colorama to be initialized vtotal = Virustotal(API_KEY="ENTER API KEY") #imports Virus Total API #Takes a Malcious URL and defangs them def defang_func(): #Determines fonts custom_fig = Figlet(font='doom') subtext_fig = Figlet(font='digital') sub = "With all the stuff you care about & none of the stuff you don\'t!" #Subtext for menu #Main Menu print(Fore.CYAN + custom_fig.renderText('URL Pacifier v4.1')) print(Style.DIM + Fore.YELLOW + subtext_fig.renderText(sub.center(40))) print( Fore.CYAN +
from virustotal_python import Virustotal from pprint import pprint from json2html import * import json vtotal = Virustotal( "50473a41f47913496c613e67dee646f6a36ebf434ce4e99fec30198f5014d29c") resp = vtotal.file_report( ["09de776902ca7d32abdab8a7ccd177fb917addf502bd4bd5aa25a93ab41cc869"]) data = json.dumps(resp) data = data.replace("'", '"') html_parser = json2html.convert(json=data) with open("./templates/program/data_tep.html", "w") as f: f.write(html_parser)
import os import hashlib import colors from virustotal_python import Virustotal from vt_config import VIRUS_TOTAL_API_KEY vtotal = Virustotal(VIRUS_TOTAL_API_KEY) def find_files(path): for root, dirs, files in os.walk(path): for name in files: filepath = os.path.join(root, name) hash_file(filepath) def hash_file(filepath): md5_hash = hashlib.md5() with open(filepath, 'rb') as f: for byte_block in iter(lambda: f.read(4096), b''): md5_hash.update(byte_block) hash = md5_hash.hexdigest() colors.print_success(f'[+] File: {filepath}') colors.print_header(f' [~] Size: {os.path.getsize(filepath)} kbs') colors.print_header(f' [~] Hash: {hash}') check_hash(hash) def check_hash(hash): try: res = vtotal.file_report([hash])