Python Forum

Full Version: Attribute error print statement error
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
#Imported modules used within the program
import pytsk3
import struct
import pyewf
import datetime 
import hashlib
from Registry import Registry


# This is a global variable which stores the Img_info object to be used by the functions
evidence_file = None
# This global variable  will store the file system variable, allowing file system to be used in all functions
file_system = None
# This global vairable will store as an empty list hence the []. 
partition_offsets = []

print '-------------------------------------'
print 'Jamshaid Alis Disk Image Analyzer'

# 2. Function to display the program's options
def display_menu():
    print "-------------------------------------"
    print "Program Options Menu"
    print "-------------------------------------"
    print "\n\n"
    print "1. Open evidence file"
    print "2. List partitions within evidence file"
    print "3. Open partition within evidence file"
    print "4. List files within partiton"
    print "5. Display details of a file"
    print "6. Hash Search"
    print "7. Display Registry details"
    print "8. Exit program"
    print "\n\n"

# Function to input an option from the user
def get_option():
    option_num = input("Please enter menu option: ")
    # This statement returns the number input by the user
    return option_num 
    
# Function to open the evidence file
def open_evidence_file():
    # This statement is needed to access the evidence file
    global evidence_file

    # Prompts the user to input the name of file desired
    evidence_filename = raw_input("Please enter name of evidence file to open: ")
    evidence_file = pytsk3.Img_Info(evidence_filename)
    # Helpful message stating the evidence file has been loaded and details about the evidence file.
    print '\t'
    print 'Loaded %s evidence file' % (evidence_filename)
    # Code shows the size of the evidence file
    # Also calculates the total number of sectors for the image
    print 'The size of this evidence file is %d bytes' % (evidence_file.get_size())
    print 'Total number of sectors in the image is %d' % (evidence_file.get_size()/512)
    print '------------------------------------------'

# Function to list the partitions
def list_partitions(): 
    global evidence_file

    # Get the partition table
    partition_table = pytsk3.Volume_Info(evidence_file)
    partitions = pytsk3.Volume_Info(evidence_file)

    # Display partition details in a table
    print 'List of partitions\n\n'
    print 'Partition number\tDesc\t\t\t\tStart Sector\tNumber of sectors'
    print '------------------------------------------------------------------------------------'

    # List variable stores start sectors for the partitions
    # Loop which processes partitions in the partition table
    partition_count = 1 
    for partition in partitions:
        print '{0:<24}{1:<32}{2:<16}{3:<16}'.format(partition_count, partition.desc, partition.start, partition.len)

        partition_count += 1
    print '\t'
    print 'The number of partitions within this table is %d' % (partition_table.info.part_count)
    print 'The Endian format used is %s' % (partition_table.info.endian)
    if partition_table.info.is_backup == True:
        print 'Partition table is a backup'
    else:
            print 'Partition table is not a backup'
    if partition_table.info.vstype == pytsk3.TSK_VS_TYPE_DOS:
        print 'The partition table is MBR'
    elif partition_table.info.vstype == pytsk3.TSK_VS_TYPE_GPT:
        print 'The partition table is GPT'
    partition_table.info.vstype
    print '\n'

    print '\n\n'

# Function to open a partition to allow access to the file system 
def open_partition():
    global partition_offsets
    global file_system

    partition_table = pytsk3.Volume_Info(evidence_file)
    #  If statement indicaes partition is MBR. Elif statement indicates GPT
    if partition_table.info.vstype == pytsk3.TSK_VS_TYPE_DOS:
        print "Partition table is MBR"
    elif partition_table.info.vstype == pytsk3.TSK_VS_TYPE_GPT:
        print "Partition table is GPT"
    
    # Displays partition details in a table
    print'Partition number\tDesc\t\t\t\tStart Sector\tNumber of sectors'
    print'------------------------------------------------------------------------------'

    # Counter variable which counts number of partitions, also displays this value in the table
    partition_count = 1
    # For loop which processes partitions in the partition table
    for partition in partition_table:
        print '{0:<24}{1:<32}{2:<16}{3:<16}'.format(partition_count, partition.desc, partition.start, partition.len)
        partition_offsets.append(partition.start)
        partition_count +=1
    # Prompts user to enter partition number to display details of
    part_num = input('Which partition would you like to display details of: ')
    print '\t'
    # File system object created for partition number input
    file_system = pytsk3.FS_Info(evidence_file, partition_offsets[part_num - 1] * 512)
    
    print 'The file system is: %s' % (file_system.info.ftype)
    print 'Block size is = %d' % (file_system.info.block_size)

# This code below displays more details about the file system
    print 'Total number of blocks is = %d' % (file_system.info.block_count)
    print 'The size of the device is = %d' % (file_system.info.dev_bsize)
    print 'Flags: %s' %(file_system.info.flags)
    #print 'The volume serial number is: ', (file_system.info.fs_id.fs_is_used)
    print 'The root directory record number is: %s' % (file_system.info.root_inum)
    print '\t'   
#/home/apdf/Desktop/DiskImage.RAW

# Function to list the files in an open partition
def list_files():
    # Global file_system needs to be here so the file_system variable can be used in this function.
    global file_system
    global partition_offsets

    #file_system = pytsk3.FS_Info(evidence_file, 34603008)

    # Displays details about the file system
    print '    File system is %s' % (file_system.info.ftype)
    print '    Block size is %d' % (file_system.info.block_size)
    # This string is for for hexadecimal values within the volume ID
    strVolID = format(file_system.info.fs_id[0], '02x')
    for idx in range(1, file_system.info.fs_id_used - 1):
        strVolID = strVolID + format(file_system.info.fs_id[idx], '02x')
    # Print statements displays more details about the file system
    print"    Block size = %d" % (file_system.info.block_count)  
    print"    Device size = %d" % (file_system.info.dev_bsize)
    print"    File system flags are %s" % (file_system.info.flags)
    print"    Serial number is %s" % (strVolID)
    print"    ROOT directory number is %d" % (file_system.info.root_inum) 

    # Table crated and displayed shows files within file system
    print 'File Number\tName\t\t\t\t\t\t\t\tType\t\tFirst block/cluster allocated to file'
    print '-------------------------------------------------------------------------------------------------------------------------------------'
    # Root directory opened here
    root_dir = file_system.open_dir(inode = file_system.info.root_inum)

    # Counter variable created for files. Number can now be displayed with the file. 
    # It can be selected later
    file_count = 1

    # For loop used to display files
    for file_obj in root_dir:
        # Assumes object is a file
        file_type_str = 'File'
        # Checks if there is a meta object before determining if the object is a file or directory
        if file_obj.info.meta != None:
            if file_obj.info.meta.type == pytsk3.TSK_FS_META_TYPE_DIR:
                file_type_str = 'Dir'
            elif file_obj.info.meta.type == pytsk3.TSK_FS_META_TYPE_VIRT:
                file_type_str = 'Virt'
        else:
            file_type_str = 'Unknown'

            

    
        # Formatted data about file or directory is displayed
        print '{0:<16}{1:<64}{2:<8}'.format(file_count, file_obj.info.name.name, file_type_str)
        # Count updated here
        file_count += 1
    if file_type_str == 'File' or file_type_str == 'Dir':
        for attribute in file_obj:
            if attribute.info.type == pytsk3.TSK_FS_ATTR_TYPE_DEFAULT or attribute.info.type == pytsk3.TSK_FS_ATTR_TYPE_NTFS_DATA:
                for data_run in attribute:
                    print '\t%d' % (data_run.addr),




# Function to display the details of a file in the opened file system
def display_file_details():
    global file_system
    global partition_offsets

    # Allows user to input file number to see more details
    file_number = input('Enter the file number to display details of: ')
    # Finds file object by counting through file system objects until number inputted is reached
    count = 1

    # File system object is stored here
    file_obj = None

    # Root directory is opened here
    root_dir = file_system.open_dir(inode = file_system.info.root_inum)

    # For loop used  to loop through file system objects in directory
    for file in root_dir:
        # Current file system object is stored here
        file_obj = file 
        # If current object count is the same as the file number input, the loop stops
        if count == file_number:
            break
        # Count updated here
        count += 1

    # /home/apdf/dog/TestImage_2.RAW                /home/apdf/j/TestImage_1.RAW


    # Displays specific details of selected file 
    print 'Name is: %s' % (file_obj.info.name.name)
    print 'Size is: %d bytes' % (file_obj.info.meta.size)

    create_datetime = datetime.datetime.utcfromtimestamp(file_obj.info.meta.crtime)
    print 'Created on:  %s' % (create_datetime.strftime('%H:%M:%S \t %d/%m/%Y'))
    create_datetime = datetime.datetime.utcfromtimestamp(file_obj.info.meta.atime)
    print 'Accessed on: %s' % (create_datetime.strftime('%H:%M:%S \t %d/%m/%Y'))
    create_datetime = datetime.datetime.utcfromtimestamp(file_obj.info.meta.mtime)
    print 'Modified on: %s' % (create_datetime.strftime('%H:%M:%S \t %d/%m/%Y'))

    print '\t'   
    
    #a_file = file_system.open(file_number)

    for attribute in file_obj:
        print 'Attribute name:  %s' % (attribute.info.name)
        print 'Attribute type:  %s' % (attribute.info.type)
        print 'Attribute id:  %d' % (attribute.info.id)
        print 'Attribute flags:  %d' % (attribute.info.flags)
        print 'Attribute size:  %d' % (attribute.info.size)

def hash_file():
    global evidence_filename
    global hash_value
    global partition_offsets
    global file_system
    
    evidence_filename = raw_input("please enter the filename you want to process: ")
    # 15. Prompt user to input hash value
    hash_value = raw_input("Please enter the hash value you are trying to find: ")
    # 3. Create an Img_Info object to represent the image file
    evidence_filename = pytsk3.Img_Info(evidence_filename)
    # 4. Get the partitions stored in the image
    #partition = pytsk3.Volume_Info(evidence_filename)
    # 5. Get the file system in the first partition.  Note this example is hardwired to access this
    # partition.  Your programs need to be more flexible to access different partitions
    file_sys = pytsk3.FS_Info(evidence_filename, 67584 * 512)
    # 6. Get the ROOT directory
    root_dir = file_sys.open_dir('/')
    # 7. Access each file in the ROOT directory
    for file_sys_obj in root_dir:
        # 8. If the current object has metadata
        if file_sys_obj.info.meta is not None:
            # 9. Check if the file system object is a file and it has bytes
            if file_sys_obj.info.meta.type == pytsk3.TSK_FS_META_TYPE_REG and file_sys_obj.info.meta.size > 0:
                # Calculate hash value for file
                # 10. Create a MD5 object
                md5_hash = hashlib.md5()
                sha1_hash = hashlib.sha1()
                # 11. Get the size of the file
                num_bytes_to_read = file_sys_obj.info.meta.size
                # 12. Read the file's data in memory
                #will read the files data in 1024 byte chunks
                CHUNK_SIZE = 1024
                #starting at offset 0
                offset = 0
                # Repeat the process until all bytes are read
                while num_bytes_to_read > 0:
                    # Read a chunk or whatever bytes remain
                    file_data = file_sys_obj.read_random(offset, min(CHUNK_SIZE, num_bytes_to_read))

                    #Update the hash calculations
                    md5_hash.update(file_data)
                    sha1_hash.update(file_data)
                    # Updates the offset for the next chunk
                    offset += CHUNK_SIZE
                    # Reducest the file size after reading the chunk
                    num_bytes_to_read -= CHUNK_SIZE

                # 14. Display hash values
                print "File %s has the md5 hash value %s" %(file_sys_obj.info.name.name,md5_hash.hexdigest())
                print "File %s has the sha1 hash value %s" %(file_sys_obj.info.name.name,sha1_hash.hexdigest())
                # 16. Does the hash value calculated match the one typed in
                if md5_hash.hexdigest().lower() == hash_value.lower():
                    print '\tFile matches hash!!!!'
                
                if sha1_hash.hexdigest().lower() == hash_value.lower():
                    print '\tFile matches hash!!!!'

def registry_details():
    print "not done yet"
 

# Main loop function for menu
def run_main():

    # Stores the option input by the user
    selected_option = 0
		
    # Define the main loop
    while selected_option != 8:

        # Display the main menu
        display_menu()
				
        # Get option number from user
        selected_option = get_option()
				
        # Run the function associated with the input number
        if selected_option == 1:
            open_evidence_file()
        elif selected_option == 2:
            list_partitions()
        elif selected_option == 3:
            open_partition()
        elif selected_option == 4:
            list_files()
        elif selected_option == 5:
            display_file_details()
        elif selected_option == 6:
            hash_file()
        elif selected_option == 7:
            registry_details()
        elif selected_option == 8:
            print "Closing Program"
        else:
            print "Input not recognised"

# Start the main loop for menu
if __name__ == "__main__":
    run_main()




    #            /home/apdf/j/DiskImage.RAW

    #            /home/apdf/j/TestImage_1.RAW

    #       

    #            FBC1013BBA9FE8D4F8C8E1E80FD47CCE


    ################# # /home/apdf/dog/TestImage_2.RAW                /home/apdf/j/TestImage_1.RAW
i seem to be getting a error when the program tries to find out what the size of the image file in bytes is i dont understand whats causing this issue it was working fine yesterday
360 lines of code is a lot to go through. I would be a big help if you could trim down the code to isolate the error in question. And please give us the full text of the error you are receiving.

Also, the global variables are making your code hard to read. Parameters and return values make it clearer what is going on in your functions. See the function tutorial on how to do that.