Ok, I'm totally baffled. I've been working on this all night and I can't get it to work. I have premission to look into the file, all I want to do is read the darn thing. Every time I try I get:
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
scan('test', rules, 0)
File "C:\Python32\PythonStuff\csc242hw7\csc242hw7.py", line 45, in scan
files = open(n, 'r')
IOError: [Errno 13] Permission denied: 'test\\test'
Here is my code. It's unfinished but I feel I should at least be getting correct values for the sections I am testing. Basically I want to look into a folder, and if there is a file scan it looking for whatever I set my signatures
to. If there are folders I will or will not scan them depending on the depth
specified. If there is a depth < 0
then it will return. If depth == 0
then it will just scan the elements in the first folder. If depth > 0
it will scan folders up until the specified depth. None of that matters thought, because for whatever reason I don't have permission to read the file. I have no idea what I am doing wrong.
def scan(pathname, signatures, depth):
'''Recusively scans all the files contained in the folder pathname up
until the specificed depth'''
# Reconstruct this!
if depth < 0:
return
elif depth == 0:
for item in os.listdir(pathname):
n = os.path.join(pathname, item)
try:
# List a directory on n
scan(n, signatures, depth)
except:
# Do what you should for a file
files = open(n, 'r')
text = file.read()
for virus in signatures:
if text.find(signatures[virus]) > 0:
print('{}, found virus {}'.format(n, virus))
files.close()
Just a quick edit:
This code below does something very similar, but I can't control the depth. It however, works fine.
def oldscan(pathname, signatures):
'''recursively scans all files contained, directly or
indirectly, in the folder pathname'''
for item in os.listdir(pathname):
n = os.path.join(pathname, item)
try:
oldscan(n, signatures)
except:
f = open(n, 'r')
s = f.read()
for virus in signatures:
if s.find(signatures[virus]) > 0:
print('{}, found virus {}'.format(n,virus))
f.close()
I venture to guess that test\test
is a directory, and some exception occurred. You catch the exception blindly and try to open the directory as a file. That gives Errno 13 on Windows.
Use os.path.isdir
to distinguish between files and directories, instead of the try...except.
for item in os.listdir(pathname):
n = os.path.join(pathname, item)
if os.path.isdir(n):
# List a directory on n
scan(n, signatures, depth)
else:
# Do what you should for a file