Home » Tutorials » How to Detect and Remove Malware in Python

How to Detect and Remove Malware in Python

In our increasingly digital world, the threat of malware looms larger than ever. Malicious software, designed to infiltrate and damage computers without user’s consent, can lead to significant privacy breaches and financial losses. As technology advances, so do the methods of attackers, making it crucial for individuals and organizations to arm themselves with effective tools to detect and neutralize these threats. Ethical hacking plays a pivotal role in this defense strategy, allowing security professionals to stay one step ahead.

In today’s tutorial, you’ll learn how to detect and remove malware in python, we will explore how to harness the power of Python for ethical hacking to create a robust malware detection and removal tool. I’ll walk you through setting up a graphical user interface (GUI) with the tkinter library, alongside leveraging the psutil library to scan for suspicious activities. So, let’s get started!

Table of Contents

Disclaimer

This content is intended for educational and ethical hacking purposes only. Using these techniques without proper authorization is illegal and subject to legal action.

Necessary Libraries

Make sure to install these libraries via the terminal or your command prompt for the code to function properly:

$ pip install tk
$ pip install psutil 

Imports

We make our program user-friendly by creating a graphical user interface through the tkinter library. Specifically, we import messagebox from tkinter to display message boxes, and Listbox, Scrollbar, and SINGLE to create lists with a scrollbar in single selection mode. Additionally, we import the os library to interact with the operating system.

Furthermore, we use psutil to retrieve information on running processes and system utilization, subprocess to execute system commands, platform to access information about the operating system, and finally, hashlib to compute file hashes.

import tkinter as tk
from tkinter import messagebox, Listbox, Scrollbar, SINGLE
import os
import psutil
import subprocess
import platform
import hashlib

Defining Suspicious Keywords and Hashes

Now we define three lists to help detect malware:

  • The first, SUSPICIOUS_KEYWORDS: is a list of words that indicate something suspicious if found in a file or process name.
  • The second, SUSPICIOUS_PATHS: is a list of directories that might contain suspicious files.
  • Finally, MALWARE_HASHES: the third is a set of known bad file hashes used to identify malware.
# Define suspicious keywords or criteria
SUSPICIOUS_KEYWORDS = ['suspicious', 'unknown', 'malware', 'random', 'temp']
SUSPICIOUS_PATHS = ['temp', 'AppData', 'Local Settings']


# Example malware hashes (in a real application, use a comprehensive database)
MALWARE_HASHES = {'example_hash1', 'example_hash2'}

Functions for Detecting and Removing Malware

get_file_hash Function

The objective of this function is to create a unique hash of a file and then check it for malware. First, it initializes a new hash instance using the hashlib.sha256() function, referred to as sha256_hash. It then opens the target file in binary mode to read its data. To handle large files efficiently, it uses iter() with a lambda function to read the file in small chunks (4096 bytes). Each chunk is added to the hash instance using sha256_hash.update().

Once all chunks are processed, the function generates a final hash value for the file and returns this value as a hexadecimal string using sha256_hash.hexdigest(). If the file is not found, the function catches a FileNotFoundError exception and returns None. Finally, it checks the generated hash against a database of known malware hashes. If no match is found, it returns None.

def get_file_hash(file_path):
   """Calculate the SHA-256 hash of a file."""
   sha256_hash = hashlib.sha256()
   try:
       with open(file_path, 'rb') as f:
           for byte_block in iter(lambda: f.read(4096), b""):
               sha256_hash.update(byte_block)
       return sha256_hash.hexdigest()
   except FileNotFoundError:
       return None

get_startup_items Function

It starts by initializing an empty list named startup_items to store information about each startup item it finds. Then, it checks if the operating system is Windows using platform.system().

  • If it is Windows, it imports the winreg module to interact with the Windows registry. Next, it creates the registry_paths list that contains the registry paths where the startup items are registered on Windows.

The function then iterates through each registry path, accessing the current user registry hive and opening the specific registry path in read-only mode using winreg.OpenKey(winreg.HKEY_CURRENT_USER, path, 0, winreg.KEY_READ). Using a loop (i = 0 and while True), it continues to read all the values in the registry key. It retrieves the name and value of each startup item using winreg.EnumValue(key, i) and adds them to the startup_items list with startup_items.append(). The function increments i by 1 to read the next value. If it reaches the end of the values, it breaks out of the loop using except OSError. If the registry path is not found, it continues to the next one.

This process works only if the operating system is Windows.

  • If the operating system is Linux, the function uses platform.system() to check for Linux. It then works similarly but with different functions and directories.

For example, it starts with a list of common directories where startup items are registered. It loops through each directory using for dir in startup_dirs, checks if the directory exists, and lists all the items in it using the os module. It adds the name and path of each startup item to the startup_items list and finally returns the list of all the startup items found, whether the operating system is Windows or Linux.

def get_startup_items():
   startup_items = []
   if platform.system() == 'Windows':
       import winreg
       registry_paths = [
           r"Software\Microsoft\Windows\CurrentVersion\Run",
           r"Software\Microsoft\Windows\CurrentVersion\RunOnce",
       ]
       for path in registry_paths:
           try:
               with winreg.OpenKey(winreg.HKEY_CURRENT_USER, path, 0, winreg.KEY_READ) as key:
                   i = 0
                   while True:
                       try:
                           name, value, _ = winreg.EnumValue(key, i)
                           startup_items.append((name, value))
                           i += 1
                       except OSError:
                           break
           except FileNotFoundError:
               continue
   elif platform.system() == 'Linux':
       # Check common startup directories
       startup_dirs = [
           os.path.expanduser('~/.config/autostart'),
           '/etc/xdg/autostart'
       ]
       for dir in startup_dirs:
           if os.path.exists(dir):
               for item in os.listdir(dir):
                   startup_items.append((item, os.path.join(dir, item)))
   return startup_items

get_scheduled_tasks Function

The objective of this one is to find all the tasks that are scheduled to run automatically on our operating system and place them in a list. First, it initializes an empty list named tasks. Then, it checks whether the operating system is Windows or Linux using platform.system().

  • If the operating system is Windows, the function uses the schtasks command to query all the scheduled tasks and captures its output in CSV format. This output is then split into individual lines using result.stdout.splitlines(), with each line representing a scheduled task that is added to the tasks list. If any error occurs during this process, a message indicating the error is displayed.
  • If the operating system is Linux, the function uses the crontab command instead of schtasks to list all the scheduled tasks. The output of this command is similarly split into individual lines and added to the tasks list. If any error occurs during this process, a message indicating the error is displayed.

Finally, once the tasks list is ready, regardless of the operating system, it is returned to be displayed to the user.

def get_scheduled_tasks():
   tasks = []
   if platform.system() == 'Windows':
       try:
           result = subprocess.run(['schtasks', '/query', '/fo', 'csv', '/nh'], capture_output=True, text=True)
           tasks = result.stdout.splitlines()
       except Exception as e:
           messagebox.showerror("Error", f"Failed to get scheduled tasks: {e}")
   elif platform.system() == 'Linux':
       try:
           result = subprocess.run(['crontab', '-l'], capture_output=True, text=True)
           tasks = result.stdout.splitlines()
       except Exception as e:
           messagebox.showerror("Error", f"Failed to get crontab entries: {e}")
   return tasks

scan_processes Function

This function aims to verify all the running programs (processes) to see if they’re suspicious. It starts by creating an empty list named suspicious_processes to store any suspicious process details it finds. The function checks each process currently running on the computer, retrieving relevant information like process ID, name, and executable path using the psutil library.

It first checks if the path of the running process is missing or does not exist. If so, it adds this process to the suspicious_processes list. Additionally, there are two other ways the function searches for malware files.

  • The first is by keyword: it looks through the executable path to see if it contains any keywords listed in the suspicious_keywords and suspicious_paths lists.
  • The second way is by calling the get_file_hash() function to see if the file’s hash exists among the malware hashes. If it does, the process is added to the suspicious_processes list.

If any issues occur during these operations, such as the program no longer existing or access being denied, it simply moves to the next process to examine it. Finally, the function returns the list of suspicious processes so it can be displayed.

def scan_processes():
   suspicious_processes = []
   for proc in psutil.process_iter(attrs=['pid', 'name', 'exe', 'username']):
       try:
           exe_path = proc.info['exe']
           if not exe_path or not os.path.exists(exe_path):
               suspicious_processes.append(proc.info)
               continue


           # Check for suspicious keywords in the executable path
           if any(keyword in exe_path.lower() for keyword in SUSPICIOUS_KEYWORDS + SUSPICIOUS_PATHS):
               suspicious_processes.append(proc.info)
               continue


           # Check the file hash
           file_hash = get_file_hash(exe_path)
           if file_hash in MALWARE_HASHES:
               suspicious_processes.append(proc.info)
               continue


           # (Optional) Check digital signature - omitted for simplicity


       except (psutil.NoSuchProcess, psutil.AccessDenied):
           continue
   return suspicious_processes

remove_startup_item Function

This one aims to remove any of the startup programs selected by the user that start automatically when the computer boots up. It first checks whether the operating system is Windows or Linux.

  • If it is Windows, it uses winreg.OpenKey() to access the registry location containing the startup items. Then, it uses winreg.DeleteValue() to delete the item selected by the user (specified by name). If the operation is successful, a message indicating success appears. If the item the user wants to delete is not found or if there is a problem deleting the item, a message indicating the error appears.
  • In the case of the operating system being Linux, it uses the os module to construct the path to the startup file in the user’s autostart directory and then tries to delete it. If successful, a message indicating success appears. If the file is not found or there is a problem with accessing or deleting it, a message indicating the error appears.
def remove_startup_item(name, path):
   if platform.system() == 'Windows':
       import winreg
       try:
           with winreg.OpenKey(winreg.HKEY_CURRENT_USER, path, 0, winreg.KEY_SET_VALUE) as key:
               winreg.DeleteValue(key, name)
               messagebox.showinfo("Info", f"Removed startup item: {name}")
       except FileNotFoundError:
           messagebox.showwarning("Warning", f"Startup item {name} not found.")
       except OSError as e:
           messagebox.showerror("Error", f"Failed to remove startup item {name}: {e}")
   elif platform.system() == 'Linux':
       try:
           os.remove(os.path.join(os.path.expanduser('~/.config/autostart'), name))
           messagebox.showinfo("Info", f"Removed startup item: {name}")
       except FileNotFoundError:
           messagebox.showwarning("Warning", f"Startup item {name} not found.")
       except OSError as e:
           messagebox.showerror("Error", f"Failed to remove startup item {name}: {e}")

remove_scheduled_task Function

Similarly to the previous function, this function’s objective is to delete any of the tasks selected by the user that are scheduled to run automatically. It starts by checking if the operating system is Windows or Linux.

  • If it is Windows, the function extracts the task name from the task description using task.split() and removes any surrounding quotes with strip(). It then uses the schtasks command to delete the selected task. If successful, a message indicating success appears. If it fails, a message indicating the error appears.
  • If the operating system is Linux, the function lists all the current scheduled tasks using the crontab command and splits them into individual lines with splitlines(). It then removes the task selected by the user from the list and joins the remaining lines. Finally, it updates the list with the crontab command. If successful, a message indicating success appears. If not, an error message appears.
def remove_scheduled_task(task):
   if platform.system() == 'Windows':
       try:
           task_name = task.split(",")[0].strip('"')
           subprocess.run(['schtasks', '/delete', '/tn', task_name, '/f'])
           messagebox.showinfo("Info", f"Removed scheduled task: {task_name}")
       except Exception as e:
           messagebox.showerror("Error", f"Failed to remove scheduled task: {e}")
   elif platform.system() == 'Linux':
       try:
           cron_lines = subprocess.run(['crontab', '-l'], capture_output=True, text=True).stdout.splitlines()
           cron_lines.remove(task)
           new_cron = "\n".join(cron_lines)
           subprocess.run(['crontab', '-'], input=new_cron, text=True)
           messagebox.showinfo("Info", f"Removed scheduled task: {task}")
       except ValueError:
           messagebox.showwarning("Warning", "Scheduled task not found.")
       except Exception as e:
           messagebox.showerror("Error", f"Failed to remove scheduled task: {e}")

remove_selected_item Function

Next, let’s look at how this function helps you manage your startup items, scheduled tasks, and running processes right from the GUI. The objective here is to delete any item you select from the list displayed in the GUI, whether it’s a startup item, a scheduled task, or an active process.

First, it checks if you’ve picked something from the listbox using the curselection() method. If you have, it grabs the index to fetch the actual item from your list. Now comes the fun part—figuring out what type of item it is:

  • If a path is provided, it’s a startup item. The function then calls remove_startup_item() to get rid of it. Simple and efficient! If the item is a dictionary, it’s a process. The function tries to terminate the process using the psutil library. If the process is already gone, it lets you know with a warning message. If access is denied, it shows an error message.
  • If the item isn’t a startup item or a process, it’s a scheduled task. In this case, the function calls remove_scheduled_task() to delete the task and updates the listbox to reflect the change.

And what if you haven’t selected anything? No worries, the function gently reminds you to pick an item with a warning message. It’s all about making your system management smooth and hassle-free!

def remove_selected_item(listbox, items, path=None):
   selected_idx = listbox.curselection()
   if selected_idx:
       selected_idx = selected_idx[0]
       item = items[selected_idx]
       if path:
           remove_startup_item(item[0], path)
       elif isinstance(item, dict):
           try:
               psutil.Process(item['pid']).terminate()
               messagebox.showinfo("Info", f"Terminated process: {item['pid']} ({item['name']})")
           except psutil.NoSuchProcess:
               messagebox.showwarning("Warning", f"Process {item['pid']} no longer exists.")
           except psutil.AccessDenied:
               messagebox.showerror("Error", f"Access denied to terminate process {item['pid']}.")
       else:
           remove_scheduled_task(item)
       listbox.delete(selected_idx)
   else:
       messagebox.showwarning("Warning", "No item selected.")

Displaying Different Functions for Different Scans

display_startup_items Function

So, here’s what this function does: it starts by calling get_startup_items() to grab the list of startup items. Then, it filters this list to keep only the ones with suspicious keywords. Once that’s done, it uses display_items() to show these filtered startup items in a new window titled “Startup Items“. Plus, if you’re on Windows, it enables the remove_startup_item() function to help you delete tasks.

def display_startup_items():
   items = get_startup_items()
   suspicious_items = [item for item in items if any(keyword in item[1].lower() for keyword in SUSPICIOUS_KEYWORDS)]
   display_items(suspicious_items, "Startup Items", remove_startup_item, r"Software\Microsoft\Windows\CurrentVersion\Run" if platform.system() == 'Windows' else None)

display_scheduled_tasks Function

This function works just like the previous one, but with two key differences. First, it calls get_scheduled_tasks() to fetch the list of scheduled tasks. Second, instead of handling startup items, it uses remove_scheduled_task() to take care of removing the tasks.

def display_scheduled_tasks():
   items = get_scheduled_tasks()
   suspicious_items = [item for item in items if any(keyword in item.lower() for keyword in SUSPICIOUS_KEYWORDS)]
   display_items(suspicious_items, "Scheduled Tasks", remove_scheduled_task)

display_running_processes Function

This function works just like the previous ones, but with two main differences:

  • First, it calls scan_processes() to get the list of processes.
  • Second, it uses remove_selected_item() to handle terminating tasks.
def display_running_processes():
   items = scan_processes()
   suspicious_items = [item for item in items if any(keyword in item['name'].lower() for keyword in SUSPICIOUS_KEYWORDS)]
   display_items(suspicious_items, "Running Processes", remove_selected_item)

display_items Function

The last one uses Toplevel() to create a new window and adds a vertical scrollbar on the right. It sets up a listbox using Listbox() to display the items you can delete, adding them with listbox.insert(). To ensure the scrollbar works perfectly with the listbox, it configures them together using scrollbar.config().

Finally, it includes a “Remove Selected” button that calls the remove_selected_item() function when clicked, making the process of item deletion straightforward and user-friendly.

def display_items(items, title, remove_func=None, path=None):
   top = tk.Toplevel(root)
   top.title(title)


   scrollbar = Scrollbar(top)
   scrollbar.pack(side=tk.RIGHT, fill=tk.Y)


   listbox = Listbox(top, selectmode=SINGLE, yscrollcommand=scrollbar.set)
   for item in items:
       listbox.insert(tk.END, item)
   listbox.pack(fill=tk.BOTH, expand=True)


   scrollbar.config(command=listbox.yview)


   if remove_func:
       remove_button = tk.Button(top, text="Remove Selected", command=lambda: remove_selected_item(listbox, items, path))
       remove_button.pack(pady=10)

Defining create_gui Function

It begins by creating the main window, setting its title, and defining its geometry. It then creates a label with a specific size and font to display the script’s title. Next, it sets up four buttons: the first is named “Scan Startup Items” and calls the display_startup_items() function when clicked; the second is named “Scan Scheduled Tasks” and calls the display_scheduled_tasks() function when clicked; the third is named “Scan Running Processes” and calls the display_running_processes() function when clicked; and the fourth, labeled “Exit“, calls root.quit to close the main window.

Finally, by using root.mainloop(), it starts the main event loop, ensuring the main window remains running and responsive to the user until they choose to exit. This setup makes it easy to manage startup items, scheduled tasks, and running processes, all from a single interface.

def create_gui():
   global root
   root = tk.Tk()
   root.title("Malware Detection and Removal - The Pycodes")
   root.geometry("400x300")


   label = tk.Label(root, text="Malware Detection and Removal Tool", font=("Arial", 14))
   label.pack(pady=10)


   scan_startup_button = tk.Button(root, text="Scan Startup Items", command=display_startup_items, width=25)
   scan_startup_button.pack(pady=5)


   scan_tasks_button = tk.Button(root, text="Scan Scheduled Tasks", command=display_scheduled_tasks, width=25)
   scan_tasks_button.pack(pady=5)


   scan_processes_button = tk.Button(root, text="Scan Running Processes", command=display_running_processes, width=25)
   scan_processes_button.pack(pady=5)


   exit_button = tk.Button(root, text="Exit", command=root.quit, width=25)
   exit_button.pack(pady=5)


   root.mainloop()

Running the GUI Application

Lastly, this part ensures that the create_gui() function will be triggered only if the script is run directly and not imported as a module. This way, the graphical user interface is initialized only when you intend to run the script standalone, keeping everything clean and modular.

if __name__ == "__main__":
   create_gui()

Example

I have run this code on Windows as shown below:

Also on Linux System:

Full Code

import tkinter as tk
from tkinter import messagebox, Listbox, Scrollbar, SINGLE
import os
import psutil
import subprocess
import platform
import hashlib


# Define suspicious keywords or criteria
SUSPICIOUS_KEYWORDS = ['suspicious', 'unknown', 'malware', 'random', 'temp']
SUSPICIOUS_PATHS = ['temp', 'AppData', 'Local Settings']


# Example malware hashes (in a real application, use a comprehensive database)
MALWARE_HASHES = {'example_hash1', 'example_hash2'}


def get_file_hash(file_path):
   """Calculate the SHA-256 hash of a file."""
   sha256_hash = hashlib.sha256()
   try:
       with open(file_path, 'rb') as f:
           for byte_block in iter(lambda: f.read(4096), b""):
               sha256_hash.update(byte_block)
       return sha256_hash.hexdigest()
   except FileNotFoundError:
       return None


def get_startup_items():
   startup_items = []
   if platform.system() == 'Windows':
       import winreg
       registry_paths = [
           r"Software\Microsoft\Windows\CurrentVersion\Run",
           r"Software\Microsoft\Windows\CurrentVersion\RunOnce",
       ]
       for path in registry_paths:
           try:
               with winreg.OpenKey(winreg.HKEY_CURRENT_USER, path, 0, winreg.KEY_READ) as key:
                   i = 0
                   while True:
                       try:
                           name, value, _ = winreg.EnumValue(key, i)
                           startup_items.append((name, value))
                           i += 1
                       except OSError:
                           break
           except FileNotFoundError:
               continue
   elif platform.system() == 'Linux':
       # Check common startup directories
       startup_dirs = [
           os.path.expanduser('~/.config/autostart'),
           '/etc/xdg/autostart'
       ]
       for dir in startup_dirs:
           if os.path.exists(dir):
               for item in os.listdir(dir):
                   startup_items.append((item, os.path.join(dir, item)))
   return startup_items


def get_scheduled_tasks():
   tasks = []
   if platform.system() == 'Windows':
       try:
           result = subprocess.run(['schtasks', '/query', '/fo', 'csv', '/nh'], capture_output=True, text=True)
           tasks = result.stdout.splitlines()
       except Exception as e:
           messagebox.showerror("Error", f"Failed to get scheduled tasks: {e}")
   elif platform.system() == 'Linux':
       try:
           result = subprocess.run(['crontab', '-l'], capture_output=True, text=True)
           tasks = result.stdout.splitlines()
       except Exception as e:
           messagebox.showerror("Error", f"Failed to get crontab entries: {e}")
   return tasks


def scan_processes():
   suspicious_processes = []
   for proc in psutil.process_iter(attrs=['pid', 'name', 'exe', 'username']):
       try:
           exe_path = proc.info['exe']
           if not exe_path or not os.path.exists(exe_path):
               suspicious_processes.append(proc.info)
               continue


           # Check for suspicious keywords in the executable path
           if any(keyword in exe_path.lower() for keyword in SUSPICIOUS_KEYWORDS + SUSPICIOUS_PATHS):
               suspicious_processes.append(proc.info)
               continue


           # Check the file hash
           file_hash = get_file_hash(exe_path)
           if file_hash in MALWARE_HASHES:
               suspicious_processes.append(proc.info)
               continue


           # (Optional) Check digital signature - omitted for simplicity


       except (psutil.NoSuchProcess, psutil.AccessDenied):
           continue
   return suspicious_processes


def remove_startup_item(name, path):
   if platform.system() == 'Windows':
       import winreg
       try:
           with winreg.OpenKey(winreg.HKEY_CURRENT_USER, path, 0, winreg.KEY_SET_VALUE) as key:
               winreg.DeleteValue(key, name)
               messagebox.showinfo("Info", f"Removed startup item: {name}")
       except FileNotFoundError:
           messagebox.showwarning("Warning", f"Startup item {name} not found.")
       except OSError as e:
           messagebox.showerror("Error", f"Failed to remove startup item {name}: {e}")
   elif platform.system() == 'Linux':
       try:
           os.remove(os.path.join(os.path.expanduser('~/.config/autostart'), name))
           messagebox.showinfo("Info", f"Removed startup item: {name}")
       except FileNotFoundError:
           messagebox.showwarning("Warning", f"Startup item {name} not found.")
       except OSError as e:
           messagebox.showerror("Error", f"Failed to remove startup item {name}: {e}")


def remove_scheduled_task(task):
   if platform.system() == 'Windows':
       try:
           task_name = task.split(",")[0].strip('"')
           subprocess.run(['schtasks', '/delete', '/tn', task_name, '/f'])
           messagebox.showinfo("Info", f"Removed scheduled task: {task_name}")
       except Exception as e:
           messagebox.showerror("Error", f"Failed to remove scheduled task: {e}")
   elif platform.system() == 'Linux':
       try:
           cron_lines = subprocess.run(['crontab', '-l'], capture_output=True, text=True).stdout.splitlines()
           cron_lines.remove(task)
           new_cron = "\n".join(cron_lines)
           subprocess.run(['crontab', '-'], input=new_cron, text=True)
           messagebox.showinfo("Info", f"Removed scheduled task: {task}")
       except ValueError:
           messagebox.showwarning("Warning", "Scheduled task not found.")
       except Exception as e:
           messagebox.showerror("Error", f"Failed to remove scheduled task: {e}")


def remove_selected_item(listbox, items, path=None):
   selected_idx = listbox.curselection()
   if selected_idx:
       selected_idx = selected_idx[0]
       item = items[selected_idx]
       if path:
           remove_startup_item(item[0], path)
       elif isinstance(item, dict):
           try:
               psutil.Process(item['pid']).terminate()
               messagebox.showinfo("Info", f"Terminated process: {item['pid']} ({item['name']})")
           except psutil.NoSuchProcess:
               messagebox.showwarning("Warning", f"Process {item['pid']} no longer exists.")
           except psutil.AccessDenied:
               messagebox.showerror("Error", f"Access denied to terminate process {item['pid']}.")
       else:
           remove_scheduled_task(item)
       listbox.delete(selected_idx)
   else:
       messagebox.showwarning("Warning", "No item selected.")


def display_startup_items():
   items = get_startup_items()
   suspicious_items = [item for item in items if any(keyword in item[1].lower() for keyword in SUSPICIOUS_KEYWORDS)]
   display_items(suspicious_items, "Startup Items", remove_startup_item, r"Software\Microsoft\Windows\CurrentVersion\Run" if platform.system() == 'Windows' else None)


def display_scheduled_tasks():
   items = get_scheduled_tasks()
   suspicious_items = [item for item in items if any(keyword in item.lower() for keyword in SUSPICIOUS_KEYWORDS)]
   display_items(suspicious_items, "Scheduled Tasks", remove_scheduled_task)


def display_running_processes():
   items = scan_processes()
   suspicious_items = [item for item in items if any(keyword in item['name'].lower() for keyword in SUSPICIOUS_KEYWORDS)]
   display_items(suspicious_items, "Running Processes", remove_selected_item)


def display_items(items, title, remove_func=None, path=None):
   top = tk.Toplevel(root)
   top.title(title)


   scrollbar = Scrollbar(top)
   scrollbar.pack(side=tk.RIGHT, fill=tk.Y)


   listbox = Listbox(top, selectmode=SINGLE, yscrollcommand=scrollbar.set)
   for item in items:
       listbox.insert(tk.END, item)
   listbox.pack(fill=tk.BOTH, expand=True)


   scrollbar.config(command=listbox.yview)


   if remove_func:
       remove_button = tk.Button(top, text="Remove Selected", command=lambda: remove_selected_item(listbox, items, path))
       remove_button.pack(pady=10)


def create_gui():
   global root
   root = tk.Tk()
   root.title("Malware Detection and Removal - The Pycodes")
   root.geometry("400x300")


   label = tk.Label(root, text="Malware Detection and Removal Tool", font=("Arial", 14))
   label.pack(pady=10)


   scan_startup_button = tk.Button(root, text="Scan Startup Items", command=display_startup_items, width=25)
   scan_startup_button.pack(pady=5)


   scan_tasks_button = tk.Button(root, text="Scan Scheduled Tasks", command=display_scheduled_tasks, width=25)
   scan_tasks_button.pack(pady=5)


   scan_processes_button = tk.Button(root, text="Scan Running Processes", command=display_running_processes, width=25)
   scan_processes_button.pack(pady=5)


   exit_button = tk.Button(root, text="Exit", command=root.quit, width=25)
   exit_button.pack(pady=5)


   root.mainloop()


if __name__ == "__main__":
   create_gui()

Happy Coding!

Check out our Ethical Hacking tutorials here.

Subscribe for Top Free Python Tutorials!

Receive the best directly.  Elevate Your Coding Journey!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top
×