#System info Start
import platform
import os
import datetime
import psutil
import winreg
import subprocess
import re
from datetime import datetime
from docx import Document

def get_original_install_date():
    try:
        registry_key = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion"
        value_name = "InstallDate"

        with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, registry_key) as key:
            install_date_raw = winreg.QueryValueEx(key, value_name)[0]

        # Convert the InstallDate to a human-readable format
        install_date_str = str(install_date_raw)
        if install_date_str.isdigit() and len(install_date_str) == 8:
            install_date = datetime.strptime(install_date_str, "%Y%m%d").strftime('%Y-%m-%d %H:%M:%S')
            return install_date
        else:
            print(f"Unexpected format for InstallDate: {install_date_str}")
            return None

    except Exception as e:
        print(f"Error retrieving original install date from registry: {e}")
        return None

def get_original_install_date_from_systeminfo():
    try:
        # Run systeminfo command and capture the output
        result = subprocess.run(['systeminfo'], capture_output=True, text=True)

        # Check if the command was successful
        if result.returncode == 0:
            return result.stdout.strip()
        else:
            print("Error running systeminfo command.")
            return None
    except Exception as e:
        print(f"Error retrieving original install date from systeminfo: {e}")
        return None

def get_system_info():
    system_info = {
        "System": platform.system(),
        "Node Name": platform.node(),
        "Release": platform.release(),
        "Version": platform.version(),
        "Processor": platform.processor(),
        "Architecture": platform.architecture(),
        "RAM (total)": round(psutil.virtual_memory().total / (1024 ** 3), 2),  # in GB
        "CPU Cores": psutil.cpu_count(logical=False),
        "Logical CPUs": psutil.cpu_count(logical=True),
        "Storage (total)": round(psutil.disk_usage('/').total / (1024 ** 3), 2),  # in GB
    }

    system_info["Registered Owner"] = os.getenv("USERNAME")
    system_info["System Manufacturer"] = platform.system()
    

    # Original Install Date from systeminfo
    install_date_systeminfo = get_original_install_date_from_systeminfo()
    system_info["Systeminfo Output"] = install_date_systeminfo

    return system_info

def run_command(command):
    try:
        result = subprocess.run(command, capture_output=True, text=True, check=True)
        return result.stdout
    except subprocess.CalledProcessError as e:
        print(f"Error executing command {command}: {e}")
        return ""

def save_to_file(filename, content):
    with open(filename, 'w') as file:
        file.write(content)

def create_docx_from_output(output, filename="system_info.docx"):
    doc = Document()
    doc.add_heading('System Information', level=1)
    for key, value in output.items():
        if key == "Commands Output":
            doc.add_heading('Commands Output', level=2)
            for command_name, command_output in value.items():
                doc.add_heading(command_name, level=3)
                doc.add_paragraph(command_output)
        else:
            doc.add_paragraph(f"{key}: {value}")

    doc.save(filename)
    print(f"DOCX file '{filename}' created successfully.")

if __name__ == "__main__":
    commands = {
        'Tasklist': ['tasklist', '/svc'],
        'Anti-Virus Products': ['powershell', '-Command', 'Get-WmiObject -Namespace "root\SecurityCenter2" -Class AntiVirusProduct -ErrorAction Stop'],
        'Processes': ['wmic', 'process', 'get', 'processid,commandline'],
        'Services': ['sc', 'query', 'state=', 'all'],
        'Network Interface Information': ['ipconfig', '/all'],
        'Local DNS Cache': ['ipconfig', '/displaydns'],
        'Connections and Ports': ['netstat', '-ano'],
        'Routing Table': ['route', 'print'],
        'ARP Table': ['arp', '-a'],
        'Wireless Profiles': ['netsh', 'wlan', 'show', 'profiles'],
        'Interface IDs/MTUs': ['netsh', 'interface', 'ip', 'show', 'interfaces'],
        'Search for Passwords': ['findstr', '/SI', 'password', '*.txt'],
        'Volume Shadow Files': ['vssadmin', 'list', 'shadows']
    }

    commands_output = {}
    for name, command in commands.items():
        output = run_command(command)
        commands_output[name] = output

    system_info = get_system_info()
    system_info["Commands Output"] = commands_output

    create_docx_from_output(system_info)
#System Info Finish
#Installed Software Start
import subprocess
import re
from datetime import datetime
from docx import Document
import sys
import winreg

def get_installed_software():
    software_list = []

    # Windows
    if sys.platform == 'win32':
        uninstall_path = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"
        hkey = winreg.HKEY_LOCAL_MACHINE

        try:
            with winreg.OpenKey(hkey, uninstall_path) as key:
                for i in range(0, winreg.QueryInfoKey(key)[0]):
                    key_name = winreg.EnumKey(key, i)
                    subkey_path = f"{uninstall_path}\\{key_name}"
                    with winreg.OpenKey(hkey, subkey_path) as subkey:
                        try:
                            name = winreg.QueryValueEx(subkey, 'DisplayName')[0]
                            version = winreg.QueryValueEx(subkey, 'DisplayVersion')[0]
                            install_date = winreg.QueryValueEx(subkey, 'InstallDate')[0]
                            install_date = datetime.strptime(str(install_date), "%Y%m%d").strftime("%Y-%m-%d")
                            publisher = winreg.QueryValueEx(subkey, 'Publisher')[0]
                            software_list.append({'Name': name, 'Version': version, 'InstallDate': install_date, 'Vendor': publisher})
                        except FileNotFoundError:
                            pass
        except Exception as e:
            print(f"Error accessing registry: {e}")

    # Linux
    elif sys.platform.startswith('linux'):
        installed_programs = subprocess.Popen(['dpkg', '--list'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, universal_newlines=True)
        installed_programs_output, error = installed_programs.communicate()

        if not error:
            packages = installed_programs_output.split('\n\n')
            for package in packages:
                lines = package.split('\n')
                if lines and len(lines) > 1:
                    package_info = lines[0].split()
                    name = package_info[1]
                    version = package_info[2]
                    software_list.append({'Name': name, 'Version': version, 'InstallDate': "N/A", 'Vendor': "N/A"})  # Install date not readily available on Linux
        
    return software_list

def save_to_docx(software_list):
    doc = Document()
    doc.add_heading('Installed Software Information', level=1)

    for software in software_list:
        doc.add_heading(f"Name: {software['Name']}", level=2)
        doc.add_paragraph(f"Vendor: {software['Vendor']}")
        doc.add_paragraph(f"Version: {software['Version']}")
        doc.add_paragraph(f"Install Date: {software['InstallDate']}")
        doc.add_paragraph("="*30)

    doc.save('installed_software_info.docx')

def main():
    installed_software = get_installed_software()
    save_to_docx(installed_software)
    print("Installed software information saved to installed_software_info.docx")

if __name__ == "__main__":
    main()

#Installed Software Finish
#Installed Software txt Start
    import wmi
from datetime import datetime

# Connect to WMI
c = wmi.WMI()

# Open a text file for writing
with open("installed_Software.txt", "w") as file:
    # Iterate over installed products
    for product in c.Win32_Product():
        # Write product information to the file
        file.write(f"Name: {product.Name}\n")
        file.write(f"Version: {product.Version}\n")
        file.write(f"Vendor: {product.Vendor}\n")
        
        # Get installation date
        install_date = getattr(product, 'InstallDate', None)
        if install_date:
            # Convert installation date to yyyy-mm-dd format
            install_date = datetime.strptime(install_date, "%Y%m%d").strftime("%Y-%m-%d")
        else:
            install_date = 'N/A'
        
        file.write(f"Install Date: {install_date}\n")
        
        file.write("\n")  # Add a blank line between entries

# Notify user that data has been saved
print("Installed product information has been saved to installed_products.txt")

#Installed Software txt End
#Browser History Start with error Handaling
import csv
import os
import sqlite3
from datetime import datetime, timedelta
import time
import psutil
import pytz

class BrowserHistoryNotFoundException(Exception):
    pass

class BrowserDatabaseNotFoundException(Exception):
    pass

def close_browser(process_name):
    """Closes the browser specified by process_name."""
    for process in psutil.process_iter(['pid', 'name']):
        if process.info['name'] == process_name:
            try:
                psutil.Process(process.info['pid']).terminate()
            except psutil.NoSuchProcess:
                pass

def get_chrome_history():
    """Gets the date, time, URL, and title from the Chrome history."""
    # Close the Chrome browser before accessing its history.
    close_browser('chrome.exe')
    # Wait for a short period to allow changes to be committed.
    time.sleep(2)  # Adjust the delay as needed
    # Get the path to the Chrome user data directory.
    chrome_user_data_dir = os.path.join(os.getenv('LOCALAPPDATA'), 'Google', 'Chrome', 'User Data', 'Default')
    # Get the path to the Chrome history database file.
    history_db_path = os.path.join(chrome_user_data_dir, 'History')
    if not os.path.exists(history_db_path):
        raise BrowserDatabaseNotFoundException("Chrome history database not found.")
    conn = sqlite3.connect(history_db_path)
    cursor = conn.cursor()
    # Execute the query to get date, time, URL, and title.
    cursor.execute("SELECT last_visit_time, url, title FROM urls")
    # Fetch all rows from the result set.
    rows = cursor.fetchall()
    # Close the cursor and connection.
    cursor.close()
    conn.close()
    # Process the rows and format the results.
    results = []
    for row in rows:
        last_visit_time_microseconds = row[0]
        last_visit_time_seconds = last_visit_time_microseconds / 1000000
        visit_datetime_utc = datetime(1601, 1, 1) + timedelta(seconds=last_visit_time_seconds)
        ist = pytz.timezone('Asia/Kolkata')
        visit_datetime_ist = visit_datetime_utc.replace(tzinfo=pytz.utc).astimezone(ist)
        url = row[1]
        title = row[2]
        results.append((visit_datetime_ist, url, title))
    return results

def get_firefox_history():
    """Gets the date, time, URL, and title from the Firefox history."""
    # Close all Firefox windows before accessing the history.
    close_browser('firefox.exe')
    conn = None
    try:
        # Path to the Firefox profiles directory
        firefox_profiles_directory = os.path.expanduser("~\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles")
        # Iterate over each directory in the Firefox profiles directory
        for profile_dir in os.listdir(firefox_profiles_directory):
            profile_path = os.path.join(firefox_profiles_directory, profile_dir)
            history_db_path = os.path.join(profile_path, "places.sqlite")
            # Check if it's a directory and if places.sqlite exists
            if os.path.isdir(profile_path) and os.path.isfile(history_db_path):
                conn = sqlite3.connect(history_db_path)
                cursor = conn.cursor()
                cursor.execute("SELECT url, title, last_visit_date FROM moz_places ORDER BY last_visit_date DESC")
                history_data = cursor.fetchall()
                results = []
                for url, title, last_visit_date in history_data:
                    if last_visit_date is not None:
                        visit_datetime_utc = datetime.utcfromtimestamp(last_visit_date / 1000000)
                        ist = pytz.timezone('Asia/Kolkata')
                        visit_datetime_ist = visit_datetime_utc.replace(tzinfo=pytz.utc).astimezone(ist)
                        results.append((visit_datetime_ist, url, title))
                return results
        raise BrowserDatabaseNotFoundException("Firefox history database not found.")
    except sqlite3.Error as e:
        print(f"Error accessing Firefox Browser history database: {e}")
    finally:
        if conn is not None:
            conn.close()

def get_brave_history():
    """Gets the date, time, URL, and title from the Brave history."""
    # Close all Brave windows before accessing the history.
    close_browser('brave.exe')
    brave_profile_directory = os.path.expanduser("~/AppData/Local/BraveSoftware/Brave-Browser/User Data/Default")
    history_db_path = os.path.join(brave_profile_directory, "History")
    try:
        if not os.path.exists(history_db_path):
            raise BrowserDatabaseNotFoundException("Brave history database not found.")
        conn = sqlite3.connect(history_db_path)
        cursor = conn.cursor()
        cursor.execute("SELECT url, title, last_visit_time FROM urls ORDER BY last_visit_time DESC")
        history_data = cursor.fetchall()
        results = []
        for url, title, last_visit_time in history_data:
            last_visit_time_seconds = last_visit_time / 1000000
            visit_datetime_utc = datetime(1601, 1, 1) + timedelta(seconds=last_visit_time_seconds)
            ist = pytz.timezone('Asia/Kolkata')
            visit_datetime_ist = visit_datetime_utc.replace(tzinfo=pytz.utc).astimezone(ist)
            results.append((visit_datetime_ist, url, title))
        return results
    except sqlite3.Error as e:
        print(f"Error accessing Brave Browser history database: {e}")
    finally:
        if conn is not None:
            conn.close()

def get_edge_history():
    """Gets the date, time, URL, and title from the Edge history."""
    # Close the Edge browser before accessing its history.
    close_browser('msedge.exe')
    # Wait for a short period to allow changes to be committed.
    time.sleep(2)  # Adjust the delay as needed
    # Get the path to the Edge user data directory.
    edge_user_data_dir = os.path.join(os.getenv('LOCALAPPDATA'), 'Microsoft', 'Edge', 'User Data', 'Default')
    # Get the path to the Edge history database file.
    history_db_path = os.path.join(edge_user_data_dir, 'History')
    try:
        if not os.path.exists(history_db_path):
            raise BrowserDatabaseNotFoundException("Edge history database not found.")
        conn = sqlite3.connect(history_db_path)
        cursor = conn.cursor()
        cursor.execute("SELECT last_visit_time, url, title FROM urls")
        rows = cursor.fetchall()
        cursor.close()
        conn.close()
        results = []
        for row in rows:
            last_visit_time_microseconds = row[0]
            last_visit_time_seconds = last_visit_time_microseconds / 1000000
            visit_datetime_utc = datetime(1601, 1, 1) + timedelta(seconds=last_visit_time_seconds)
            ist = pytz.timezone('Asia/Kolkata')
            visit_datetime_ist = visit_datetime_utc.replace(tzinfo=pytz.utc).astimezone(ist)
            url = row[1]
            title = row[2]
            results.append((visit_datetime_ist, url, title))
        return results
    except sqlite3.Error as e:
        print(f"Error accessing Edge Browser history database: {e}")
    finally:
        if conn is not None:
            conn.close()

def create_csv_file(browser_history, browser_name):
    """Creates a CSV file for browser history."""
    csv_file_path = f"{browser_name}_Browser_History.csv"
    with open(csv_file_path, mode='w', newline='', encoding='utf-8') as file:
        writer = csv.writer(file)
        writer.writerow(['Date', 'Time (IST)', 'URL', 'Title'])
        for entry in browser_history:
            writer.writerow([entry[0].date(), entry[0].time(), entry[1], entry[2]])
    print(f"CSV file saved for {browser_name} browser history: {csv_file_path}")

# Get browser history
try:
    chrome_history = get_chrome_history()
except BrowserDatabaseNotFoundException as e:
    print(e)
    chrome_history = []
except Exception as e:
    print(f"Error accessing Chrome Browser history: {e}")
    chrome_history = []

try:
    firefox_history = get_firefox_history()
except BrowserDatabaseNotFoundException as e:
    print(e)
    firefox_history = []
except Exception as e:
    print(f"Error accessing Firefox Browser history: {e}")
    firefox_history = []

try:
    brave_history = get_brave_history()
except BrowserDatabaseNotFoundException as e:
    print(e)
    brave_history = []
except Exception as e:
    print(f"Error accessing Brave Browser history: {e}")
    brave_history = []

try:
    edge_history = get_edge_history()
except BrowserDatabaseNotFoundException as e:
    print(e)
    edge_history = []
except Exception as e:
    print(f"Error accessing Edge Browser history: {e}")
    edge_history = []

# Create CSV files
create_csv_file(chrome_history, "Chrome")
create_csv_file(firefox_history, "Firefox")
create_csv_file(brave_history, "Brave")
create_csv_file(edge_history, "Edge")

#Browser History End
#Hash Function Start
#Perfect
import os
import hashlib
import xlsxwriter
from concurrent.futures import ThreadPoolExecutor, as_completed

def calculate_hashes(file_path):
    """Calculate both MD5 and SHA-256 hash values for a file."""
    md5_hash = hashlib.md5()
    sha256_hash = hashlib.sha256()

    try:
        with open(file_path, "rb") as file:
            for byte_block in iter(lambda: file.read(4096), b""):
                md5_hash.update(byte_block)
                sha256_hash.update(byte_block)

        return md5_hash.hexdigest(), sha256_hash.hexdigest()

    except Exception as e:
        return f"Error calculating hashes: {e}", ""

def process_directory(directory, file_extension=None):
    """Recursively calculate MD5 and SHA-256 hash values for files in the specified directory using threads."""
    file_hashes = {}

    try:
        with ThreadPoolExecutor() as executor:
            futures = {executor.submit(calculate_hashes, os.path.join(root, file_name)): os.path.join(root, file_name)
                       for root, _, files in os.walk(directory)
                       for file_name in files
                       if os.path.isfile(os.path.join(root, file_name)) and (file_extension is None or file_name.lower().endswith(file_extension))}

            for future in as_completed(futures):
                file_path = futures[future]
                try:
                    md5_hash, sha256_hash = future.result()
                    file_hashes[file_path] = {'md5': md5_hash, 'sha256': sha256_hash}
                except Exception as e:
                    print(f"Error calculating hashes for {file_path}: {e}")

        return file_hashes

    except FileNotFoundError:
        print(f"Error: The directory '{directory}' was not found.")
        return {}

def save_hashes_to_xls(hashes, file_path):
    """Save hash values to an XLS file."""
    workbook = xlsxwriter.Workbook(file_path)
    worksheet = workbook.add_worksheet()

    # Add headers
    worksheet.write(0, 0, 'File Path')
    worksheet.write(0, 1, 'MD5 Hash')
    worksheet.write(0, 2, 'SHA-256 Hash')

    # Write hash values to the worksheet
    row = 1
    for file_path, hash_values in hashes.items():
        md5_hash = hash_values['md5']
        sha256_hash = hash_values['sha256']
        worksheet.write(row, 0, file_path)
        worksheet.write(row, 1, md5_hash)
        worksheet.write(row, 2, sha256_hash)
        row += 1

    workbook.close()

if __name__ == "__main__":
    # Use the C drive's Program Files and Program Files (x86) directories as the default paths
    program_files = r'C:\Program Files'
    program_files_x86 = r'C:\Program Files (x86)'

    # Get hashes for .exe files in Program Files
    program_files_hashes = process_directory(program_files, file_extension='.exe')
    save_hashes_to_xls(program_files_hashes, 'program_files_hashes.xlsx')
    print("Program Files hashes saved.")

    # Get hashes for .exe files in Program Files (x86)
    program_files_x86_hashes = process_directory(program_files_x86, file_extension='.exe')
    save_hashes_to_xls(program_files_x86_hashes, 'program_files_x86_hashes.xlsx')
    print("Program Files (x86) hashes saved.")

    # Use the C drive's System32 directory as the default path
    system32_directory = r'C:\Windows\System32'

    # Get hashes for all files in System32, including .evtx files
    system32_hashes = process_directory(system32_directory)
    save_hashes_to_xls(system32_hashes, 'system32_hashes.xlsx')
    print("System32 hashes saved.")

    print("All hashes saved successfully.")
    
#Hash Function End
#Digital Forensics Start
import os
import subprocess
import shutil
import psutil
import hashlib
import csv
import platform
import sys
from datetime import datetime

# Function to run PowerShell commands
def run_powershell_command(command):
    try:
        result = subprocess.run(["powershell", "-Command", command], capture_output=True, text=True)
        return result.stdout
    except Exception as e:
        print(f"Error executing PowerShell command {command}: {e}")
        return ""

# Function to run command prompt commands
def run_cmd_command(command):
    try:
        result = subprocess.run(command, shell=True, capture_output=True, text=True)
        return result.stdout
    except Exception as e:
        print(f"Error executing command {command}: {e}")
        return ""

# Function to save output to file
def save_output_to_file(output, file_path):
    try:
        with open(file_path, 'w') as file:
            file.write(output)
    except Exception as e:
        print(f"Error saving output to {file_path}: {e}")

# Define directories containing .evtx files
evtx_directories = [
    r"C:\WINDOWS\system32\winevt\Logs",
    # Add more directories as needed
]

# Function to copy all .evtx files and their contents to a folder
def copy_evtx_files_and_contents(src_dir, dest_dir):
    for root, dirs, files in os.walk(src_dir):
        for file in files:
            if file.endswith(".evtx"):
                src_file_path = os.path.join(root, file)
                shutil.copy(src_file_path, dest_dir)

# Function to collect PowerShell history
def collect_powershell_history(destination_folder):
    # Run PowerShell command to get the history
    try:
        powershell_history = subprocess.check_output(["powershell", "Get-Content (Get-PSReadlineOption).HistorySavePath"], shell=True, text=True)
    except subprocess.CalledProcessError as e:
        print("Error:", e)
        return

    # Write the PowerShell history to a file in the destination folder
    destination_path = os.path.join(destination_folder, "powershell_history.txt")
    with open(destination_path, "w") as f:
        f.write(powershell_history)

    print("PowerShell history collected and stored in:", destination_path)

# Function to get recently accessed files
def get_recently_accessed_files(directory):
    # List to store file names and last access times
    files_list = []

    # Check if directory exists
    if not os.path.exists(directory):
        print(f"Directory '{directory}' does not exist.")
        return files_list

    # Iterate over files in the directory
    for filename in os.listdir(directory):
        filepath = os.path.join(directory, filename)
        if os.path.isfile(filepath):
            # Get the last access time of the file
            last_accessed = datetime.fromtimestamp(os.path.getatime(filepath))
            files_list.append((filename, last_accessed))

    # Sort files by last access time
    files_list.sort(key=lambda x: x[1], reverse=True)
    return files_list

# Function to save to text file
def save_to_text_file(files_list, output_file):
    # Write the list of files to the output text file
    with open(output_file, 'w') as f:
        for filename, last_accessed in files_list:
            f.write(f"{filename}\t{last_accessed}\n")

# Function to calculate file hashes
def calculate_hashes(file_path):
    md5 = hashlib.md5()
    sha1 = hashlib.sha1()
    sha256 = hashlib.sha256()
    with open(file_path, "rb") as f:
        while True:
            data = f.read(4096)
            if not data:
                break
            md5.update(data)
            sha1.update(data)
            sha256.update(data)
    return md5.hexdigest(), sha1.hexdigest(), sha256.hexdigest()

# Function to get file metadata
def get_file_metadata(file_path):
    metadata = {}
    try:
        stat = os.stat(file_path)
        metadata['size'] = stat.st_size
        metadata['permissions'] = stat.st_mode
        metadata['last_accessed'] = datetime.fromtimestamp(stat.st_atime).strftime('%Y-%m-%d %H:%M:%S')
        metadata['last_modified'] = datetime.fromtimestamp(stat.st_mtime).strftime('%Y-%m-%d %H:%M:%S')
        metadata['created'] = datetime.fromtimestamp(stat.st_ctime).strftime('%Y-%m-%d %H:%M:%S')
    except Exception as e:
        print(f"Failed to get metadata for {file_path}: {e}")
    return metadata

# Function to collect extended process information
def collect_processes_extended_info():
    processes_info = []
    for process in psutil.process_iter(['pid', 'name', 'exe', 'cmdline', 'cwd']):
        try:
            p_info = {}
            p_info['pid'] = process.info['pid']
            p_info['name'] = process.info['name']
            p_info['exe'] = process.info['exe']
            p_info['cmdline'] = process.info['cmdline']
            p_info['cwd'] = process.info['cwd']

            # Calculate hashes and get metadata of the executable file
            exe_path = process.info['exe']
            if os.path.exists(exe_path):
                md5_hash, sha1_hash, sha256_hash = calculate_hashes(exe_path)
                p_info['md5'] = md5_hash
                p_info['sha1'] = sha1_hash
                p_info['sha256'] = sha256_hash
                p_info.update(get_file_metadata(exe_path))  # Update with metadata
            else:
                p_info['md5'] = None
                p_info['sha1'] = None
                p_info['sha256'] = None
                p_info.update({'size': None, 'permissions': None, 'last_accessed': None, 'last_modified': None, 'created': None})

            # Add version of the running executable
            if process.info['name'] == os.path.basename(sys.executable):
                p_info['running_exe_version'] = sys.version

            processes_info.append(p_info)
        except Exception as e:
            print(f"Failed to collect information for process {process.info['pid']}: {e}")
    return processes_info

# Main function
def main():
    # Create a folder named "Evidence" to store data
    evidence_folder = "Evidence"
    if not os.path.exists(evidence_folder):
        os.makedirs(evidence_folder)

    # Get Win32_UserAccount information
    win32_user_account_info = run_powershell_command("Get-WmiObject Win32_UserAccount -filter LocalAccount=True")
    save_output_to_file(win32_user_account_info, os.path.join(evidence_folder, "win32_user_account_info.txt"))

    # Get schtasks information
    schtasks_info = run_cmd_command("schtasks /query")
    save_output_to_file(schtasks_info, os.path.join(evidence_folder, "schtasks_info.txt"))

    # Get nettcpconnection information
    nettcpconnection_info = run_powershell_command("get-nettcpconnection")
    save_output_to_file(nettcpconnection_info, os.path.join(evidence_folder, "nettcpconnection_info.txt"))

    # Get logged-on users information
    logged_on_users_info = run_cmd_command("query user")
    save_output_to_file(logged_on_users_info, os.path.join(evidence_folder, "logged_on_users_info.txt"))

    # Get firewall information
    firewall_info = run_cmd_command("netsh advfirewall show all")
    save_output_to_file(firewall_info, os.path.join(evidence_folder, "firewall_info.txt"))

    # Get registry information
    registry_info = run_cmd_command("reg query HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\MountPoints2")
    save_output_to_file(registry_info, os.path.join(evidence_folder, "registry_info.txt"))

    # Get service information
    service_info = run_cmd_command("sc query state= all")
    save_output_to_file(service_info, os.path.join(evidence_folder, "service_info.txt"))

    # Create a folder to store all evtx files and their contents
    evtx_output_folder = os.path.join(evidence_folder, "Evtx_Files")
    os.makedirs(evtx_output_folder, exist_ok=True)

    # Copy all .evtx files and their contents to the Evtx_Files folder
    for directory in evtx_directories:
        copy_evtx_files_and_contents(directory, evtx_output_folder)

    print("All outputs have been saved to the Evidence folder.")

    # Collect PowerShell history
    collect_powershell_history(evidence_folder)

    # Get recently accessed files
    recent_files_dir = os.path.expanduser('~') + "\\AppData\\Roaming\\Microsoft\\Windows\\Recent"
    recent_files_list = get_recently_accessed_files(recent_files_dir)
    if recent_files_list:
        output_file_path = os.path.join(evidence_folder, 'recently_accessed_files.txt')
        save_to_text_file(recent_files_list, output_file_path)
        print(f"Recently accessed files list has been saved to {output_file_path}")
    else:
        print("No recent files found.")

    # Collect extended process information and save to CSV
    processes_info = collect_processes_extended_info()
    csv_file = os.path.join(evidence_folder, 'process_info.csv')
    with open(csv_file, 'w', newline='') as csvfile:
        fieldnames = ['pid', 'name', 'exe', 'cmdline', 'cwd', 'md5', 'sha1', 'sha256', 'size', 'permissions', 'last_accessed', 'last_modified', 'created', 'running_exe_version']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writeheader()
        for process_info in processes_info:
            writer.writerow(process_info)
    print(f"Process information saved to {csv_file}.")

if __name__ == "__main__":
    main()

#Digital Forensics End
#Recycle bin Start
import winshell
import csv
import os
from datetime import datetime
import pytz

def extract_date_time(item_string):
    # Extract recycle date and time from the item string
    parts = item_string.split('recycled at ')
    if len(parts) > 1:
        recycle_date_time_str = parts[1].split('+')[0].strip()  # Remove the timezone part
        return recycle_date_time_str
    else:
        return None

def convert_to_ist(date_time_str):
    # Convert the provided UTC date and time string to IST
    utc_timezone = pytz.timezone('UTC')
    ist_timezone = pytz.timezone('Asia/Kolkata')

    utc_datetime = datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S')
    utc_datetime = utc_timezone.localize(utc_datetime)
    ist_datetime = utc_datetime.astimezone(ist_timezone)

    return ist_datetime.strftime('%Y-%m-%d %H:%M:%S IST')

if __name__ == "__main__":
    recycle_bin_data = list(winshell.recycle_bin())

    with open("Recycle bin Data.csv", "w", newline='', encoding='utf-8') as csvfile:
        fieldnames = ['Name', 'Original Location', 'Recycle Date (IST)']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writeheader()

        for item in recycle_bin_data:
            original_location = item.original_filename()
            recycle_date_time_str = extract_date_time(str(item))

            if original_location and recycle_date_time_str:
                recycle_date_time_ist = convert_to_ist(recycle_date_time_str)
                writer.writerow({
                    'Name': os.path.basename(original_location),
                    'Original Location': original_location,
                    'Recycle Date (IST)': recycle_date_time_ist
                })

#Recycle bin End

import os
import zipfile
import pyzipper

def add_folder_to_zip(zip_file, folder_path):
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            file_path = os.path.join(root, file)
            zip_file.write(file_path, os.path.relpath(file_path, folder_path))

if __name__ == "__main__":
    # Your existing code here...

    # Create a directory named "Evidence" if it doesn't exist
    evidence_dir = "Evidence"
    if not os.path.exists(evidence_dir):
        os.makedirs(evidence_dir)

    # Move all output files to the "Evidence" folder
    os.rename("system_info.docx", os.path.join(evidence_dir, "system_info.docx"))
    os.rename("installed_software_info.docx", os.path.join(evidence_dir, "installed_software_info.docx"))
    os.rename("installed_Software.txt", os.path.join(evidence_dir, "installed_Software.txt"))
    os.rename("Chrome_Browser_History.csv", os.path.join(evidence_dir, "Chrome_Browser_History.csv"))
    os.rename("Firefox_Browser_History.csv", os.path.join(evidence_dir, "Firefox_Browser_History.csv"))
    os.rename("Brave_Browser_History.csv", os.path.join(evidence_dir, "Brave_Browser_History.csv"))
    os.rename("Edge_Browser_History.csv", os.path.join(evidence_dir, "Edge_Browser_History.csv"))
    os.rename("program_files_hashes.xlsx", os.path.join(evidence_dir, "program_files_hashes.xlsx"))
    os.rename("program_files_x86_hashes.xlsx", os.path.join(evidence_dir, "program_files_x86_hashes.xlsx"))
    os.rename("system32_hashes.xlsx", os.path.join(evidence_dir, "system32_hashes.xlsx"))
    os.rename("Recycle bin Data.csv", os.path.join(evidence_dir, "Recycle bin Data.csv"))

    # Create a password-protected zip file
    zip_filename = "evidence.zip"
    password = "12345"  # Enter your password here
    with pyzipper.AESZipFile(zip_filename, 'w', compression=pyzipper.ZIP_DEFLATED, encryption=pyzipper.WZ_AES) as zipf:
        zipf.setpassword(password.encode())
        add_folder_to_zip(zipf, evidence_dir)

    # Remove the Evidence directory
    shutil.rmtree(evidence_dir)

    print("All output files moved to the 'Evidence' folder.")
