Recursive Program to Clean a USB Drive - python

couple of days back an infected computer infected my USB drive with a shortcut virus and. I had lots of software in that USB drive i plugged it in my Linux machine and cleaned a lot of files but what the virus did is it created an .exe file in each folder with that folder's name. Each .exe file is capable of infecting another PC. So me with a lot of time in my hand was trying to make a python script that goes to each folder check if a .exe file with that folder name exists delete it and run the function for every sub-folder recursively. but it is not working here what i made so far
#!/usr/bin/python
from __future__ import print_function
import os
import argparse
def deldir(fol):
# changing to the directory
os.chdir(fol)
#Trivial case delte the virus in the root folder
cwd = os.getcwd()
#getting just the name of the folder rather than full path by splitting from "/"
cwd = str(cwd).split('/')[-1]
#if any .exe file exists with that name
if any(str(cwd + '.exe') in s for s in os.listdir('.')):
# delete that file
os.remove(str(cwd + '.exe'))
print('Deleting virus file')
#making a list with all the contents in the directory
dirlist = os.listdir('.')
print(dirlist)
#Looping through the directory that we just made a list of its contents
for i in dirlist:
#checking if it is a directory or not
if os.path.isdir(i):
#changing dir to that directory
os.chdir(i)
#getting the current working directory
cwd = os.getcwd()
#getting just the name of the folder rather than full path by splitting from "/"
cwd = str(cwd).split('/')[-1]
#if any .exe file exists with that name
if any(str(cwd + '.exe') in s for s in os.listdir('.')):
# delete that file
os.remove(str(cwd + '.exe'))
print('Deleting virus file', str(cwd + '.exe'))
#listing filders in current directory
for j in os.listdir('.'):
#passing that subdirectory to the function itself if its a folder
if os.path.isdir(j):
deldir(j)
else:
print('Not a folder so skipping')
def main():
#parsing the command line arguments
parser = argparse.ArgumentParser()
parser.add_argument("fol", help="Directory to enter")
args = parser.parse_args()
#passing the command line argument with the folder path to "deldir" function
deldir(args.fol)
if __name__ == "__main__":
main()
Please point me to right direction i have no idea what i am doing wrong. Thanks for reading

Here what I see mistake in your code.
1
os.getcwd -> os.getcwd()
It's a function
2.
You using os.chdir(i) inside the for loop. this will work only first directory in that directory.
3.
The algorithm is wrong, It's not checking the directories level 1,3,5,... for virus.
As Hiro and MYGz's comments. os.walk/os.scandir is easier way to go for recursive directory. but your way is better for practice and learn programming.

I got it done the way i wanted with os.walk() it's really easy that way and that takes away the fun ! :'( . I was hoping to fix my own code but somethings not right. well anyways here's the working code if anyone encounters this type of virus or something.
#!/usr/bin/python
from __future__ import print_function
import os
import argparse
def deldir(fol):
for root, dirs, files in os.walk(fol):
try:
os.remove(str(root + '/' + str(root).split('/')[-1 ] + '.exe'))
except:
print('Does not exists' ,str(root + '/' + str(root).split('/')[-1 ] + '.exe'))
def main():
#parsing the command line arguments
parser = argparse.ArgumentParser()
parser.add_argument("fol", help="Directory to enter")
args = parser.parse_args()
#passing the command line argument with the folder path to "deldir" function
deldir(args.fol)
if __name__ == "__main__":
main()

Related

For loop with files with Python

I have this code:
import os
directory = "JeuDeDonnees"
for filename in os.listdir(directory):
print("File is: "+filename)
This code run and prints files name in a VSCode/Python environment.
However, when I run it in Sikuli-IDE I got this error:
[error] SyntaxError ( "no viable alternative at input 'for'", )
How can I make this for loop run or is there an alternative that can work?
Answer found ;
Basically, in my Sikuli-IDE environnement, there's layers of Python, Java, Jython... interlocking each other so the Path finding was tedious.
src_file_path = inspect.getfile(lambda: None) #The files we're in
folder = os.path.dirname(src_file_path) # The folder we're in
directory = folder + "\JeuDeDonnees" # Where we wanna go
for filename in os.listdir(directory) # Get the files
print(filename)
We're telling the Path where we are with the current file, get the folder we're in, then moving to "\JeuDeDonnees" and the files.

Python: how to move a file with a certain name to a folder with the same name

I have a situation in which the directory I'm working at has many files and folders (something like that):
AAA_SUBFOLDER
AAA_FILE_1
AAA_FILE_2
BBB_SUBFOLDER
BBB_FILE_1
BBB_FILE_2
So files and subfolders both starting with AAA or BBB(and so on with CCC, DDD..). What I'd like to do is a python script that moves all the AAA files to the AAA subfolder and iterate this for all the files and subfolders with the same names in order to obtain something like this:
AAA_SUBFOLDER
- AAA_FILE_1
- AAA_FILE_2
BBB_SUBFOLDER
- BBB_FILE_1
- BBB_FILE_2
...
Can you help me? Thanks in advance!
this solution should work for your requirement.
steps:
make sure you have python installed
save script to a file (lets say main.py)
run the saved file with 2 arguments - 1 for path you want to organize, 2 for the delimiter of the subfolder. example: python main.py -p "D:\path\to\files" -d "_"
!! this doesn't rearrange inner folders, only top level.
if you got any questions, I'll gladly help.
import os
import argparse
from pathlib import Path
def parse_args() -> tuple:
ap = argparse.ArgumentParser()
ap.add_argument("-p", "--path", default="./files", help="path to the folder that needs organizing")
ap.add_argument("-d", "--delimiter", default="_", help="delimiter of file names")
return ap.parse_args()
args = parse_args()
for filename in os.listdir(args.path):
file_path = os.path.join(args.path, filename)
if not os.path.isfile(file_path):
continue
subfolder_name = Path(filename).stem.split(args.delimiter)[0]
subfolder_path = os.path.join(args.path,subfolder_name)
os.makedirs(subfolder_path, exist_ok=True)
os.rename(file_path, os.path.join(subfolder_path, filename))
This is my solution using pathlib rename ;) The script as it is assume the current is the path with your files and folders.
# using pathlip
from collections import defaultdict
from pathlib import Path
TARGET_DIR = Path('.') # script dir
FILES_AND_FOLDERS = TARGET_DIR.rglob('*')
# storage with files and folders
storage = defaultdict(list)
for blob in FILES_AND_FOLDERS:
if blob.is_file():
storage['files'].append(blob)
elif blob.is_dir():
storage['dir'].append(blob)
# for each dir check if file first 3 characters
# match if so move by rename
for directory in storage['dir']:
for file in storage['files']:
if file.name[:3] == directory.name[:3]:
file.rename(directory / file)
# you can look at shutil too

Python Directory Path

I am trying to write a python script to use the linux command wc to input the amount of lines in a file. I am iterating through a directory inputted by the user. However, whenever I get the absolute path of a file in the directory, it skips the directory it is in. So, the path isn't right and when I call wc on it, it doesn't work because it is trying to find the file in the directory above. I have 2 test text files in a directory called "testdirectory" which is located directly under "projectdirectory".
Script file:
import subprocess
import os
directory = raw_input("Enter directory name: ")
for root,dirs,files in os.walk(os.path.abspath(directory)):
for file in files:
file = os.path.abspath(file)
print(path) #Checking to see the path
subprocess.call(['wc','l',file])
This is what I get when running the program:
joe#joe-VirtualBox:~/Documents/projectdirectory$ python project.py
Enter directory name: testdirectory
/home/joe/Documents/projectdirectory/file2
wc: /home/joe/Documents/projectdirectory/file2: No such file or directory
/home/joe/Documents/projectdirectory/file1
wc: /home/joe/Documents/projectdirectory/file1: No such file or directory
I don't know why the path isn't /home/joe/Documents/projectdirectory/testdirectory/file2 since that is where the file is located.
You're using the output of os.walk wrong.
abspath is related to your program's current working directory, whereas your files are in the directory as specified by root. So you want to use
file = os.path.join(root, file)
Your issue is in the use of os.path.abspath(). All that this function does is appends the current working directory onto whatever the argument to the function is. You also need to have a - before the l option for wc. I think this fix might help you:
import os
directory = input("Enter directory name: ")
full_dir_path = os.path.abspath(directory)
for root,dirs,files in os.walk(full_dir_path):
for file in files:
full_file_path = os.path.join(root, file)
print(full_file_path) #Checking to see the path
subprocess.call(['wc','-l',full_file_path])

Python os.chdir() to root directory actually changes directory to current directory

I am working on a project on path D:/code/project.
project.py
import os
import argparse
def create(path):
if os.path.exists(path):
os.chdir(path)
app = open("app.py", "w+")
app.write("print(\"Hello world!\")")
else:
path_list = path.split("/")
for i in path_list:
try:
os.mkdir(i)
except FileExistsError:
pass
except FileNotFoundError:
print("Invalid path")
exit()
os.chdir(i)
app = open("app.py", "w+")
app.write("print(\"Hello world!\")")
if __name__ == "__main__":
parser = argparse.ArgumentParser()
create_parser = parser.add_subparsers().add_parser("create")
create_parser.add_argument("path", nargs="?", default=".", metavar="path", type=str)
args = parser.parse_args()
create(vars(args)["path"])
Basically, it has a custom command called create which takes path as an argument. When it detects that path already exists, it will create a app.py at the directory specified, and if it does not, it will try and create the path and app.py.
However, when I run
D:/code/project> python project.py create D:/newpath
Instead of creating a new directory newpath under D:, it creates newpath under my current directory (D:/code/project).
How do I change it such that changing directory to a root directory will actually switch correctly?
Your issue is with this line:
path_list = path.split("/")
On windows, that doesn't correctly split the path. It leaves the drive letter 'D:' as a fragment all by itself, but when you try to change directory to that path, it does nothing (assuming the current directory was on D: somewhere). It is the same behavior you get with the cd command on a command prompt. Drive letters in paths are pretty weird, they don't work like normal path prefixes.
To correctly split the path, use os.path.split(path). It will correctly use 'D:/' as the first element of the path, which when you change to it will put you on the root folder of your drive.
If you're using a recent version of Python (3.4+), you could also try using the pathlib module for a better, more object oriented way of manipulating paths:
from pathlib import Path
def create(path_str):
path = Path(path_str)
path.mkdir(parents=True, exist_ok=True) # creates parent folders as needed
with open(path / 'app.py', 'w') as app: # / operator joins path fragments
app.write('print("Hello world!")')

Python - how to change directory

I am doing a school assignment where I have to take input from a user and save it to a text file.
My file structure will be something like:
- Customer register
- Customer ID
- .txt files 1-5
It can be saved in the python folder and I can make the folders like this:
os.makedirs("Customer register/Customer ID")
My question is, how do I set the path the text files are to be stored in, in the directory when I don't know the directory? So that no matter where the program is run it is saved in the "Customer ID" folder I create (but on the computer the program is run on)?
Also, how do I make this work on both windows and mac?
I also want to program to be able to be executed several times, and check if the folder is there and save to the "Customer ID" folder if it already exists. Is there a way to do that?
EDIT:
This is the code I am trying to use:
try:
dirs = os.makedirs("Folder")
path = os.getcwd()
os.chdir(path + "/Folder")
print (os.getcwd())
except:
if os.path.exists:
path = os.getcwd()
unique_filename = str(uuid.uuid4())
customerpath = os.getcwd()
os.chdir(customerpath + "/Folder/" + unique_filename)
I am able to create a folder and change the directory (everything in "try" works as I want).
When this folder is created I want to create a second folder with a random generated folder name (used for saving customer files). I can't get this to work in the same way.
Error:
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'C:\Users\48736\PycharmProjects\tina/Folder/979b9026-b2f6-4526-a17a-3b53384f60c4'
EDIT 2:
try:
os.makedirs("Folder")
path = os.getcwd()
os.chdir(path + "/Folder")
print (os.getcwd())
except:
if os.path.exists:
path = os.getcwd()
os.chdir(os.path.join(path, 'Folder'))
print(os.getcwd())
def userId(folderid):
try:
if not os.path.exists(folderid):
os.makedirs(folderid)
except:
if os.path.exists(folderid):
os.chdir(path + "/Folder/" + folderid)
userId(str(uuid.uuid4()))
print(os.getcwd())
So I can now create a folder, change directory to the folder I have created and create a new folder with a unique filename within that folder.
But I can't change the directory again to the folder with the unique filename.
Any suggestions?
I have tried:
os.chdir(path + "/Folder/" + folderid)
os.chdir(path, 'Folder', folderid)
os.chdir(os.path.join(path, 'Folder', folderid))
But is still just stays in: C:\Users\47896\PycharmProjects\tina\Folder
You can use relative paths in your create directory command, i.e.
os.makedirs("./Customer register/Customer ID")
to create folder in project root (=where the primary caller is located) or
os.makedirs("../Customer register/Customer ID") in parent directory.
You can, of course, traverse the files tree as you need.
For specific options mentioned in your question, please, see makedirs documentation at Python 3 docs
here is solution
import os
import shutil
import uuid
path_on_system = os.getcwd() # directory where you want to save data
path = r'Folder' # your working directory
dir_path = os.path.join(path_on_system, path)
if not os.path.exists(dir_path):
os.makedirs(dir_path)
file_name = str(uuid.uuid4()) # file which you have created
if os.path.exists(file_name) and os.path.exists(dir_path):
shutil.move(file_name,os.path.join(dir_path,file_name))
else:
print(" {} does not exist".format(file_name))

Categories

Resources