# find files containing a specific strings like encrypted malware

#Import os module
import os
import fnmatch

# Ask the user to enter string to search
search_path = input("Enter directory path to search : ")
file_type = input("File Type : ")
search_str = input("Enter the search string : ")
result_txt_file = input("Output file : ")

def sessionSsave(nSess):
    sessFile = open(result_txt_file,"a+")
    #sessnum = sessFile.readlines()
    #numer = len(sessnum)
    sessFile.write(str(nSess))
    sessFile.close()

try:
    # Append a directory separator if not already present
    if not (search_path.endswith("/") or search_path.endswith("\\") ): 
            search_path = search_path + "/"
                                                              
    # If path does not exist, set search path to current directory
    if not os.path.exists(search_path):
            search_path ="."
    i = 1
    # Repeat for each file in the directory  
    #for fname in os.walk(search_path):
    for root, dirs, files in os.walk(search_path):

        for filename in fnmatch.filter(files, file_type):

            # Open file for reading
            fo = open(os.path.join(root, filename),  encoding="ISO-8859-1")
            
            #print (i)
            #i +=1

            # Read the first line from the file
            line = fo.readline()

            # Initialize counter for line number
            line_no = 1
            try:
                # Loop until EOF
                while line != '' :
                        # Search for string in line
                        index = line.find(search_str)
                        if ( index != -1) :
                            print(filename, "[", line_no, ",", index, "] ", line, sep="")
                            txtline =str(root)+"/"+str( filename)+ "["+ str(line_no) + ","+ str(index) + "] "+ str(line) 
                            sessionSsave( txtline)

                        # Read next line
                        line = fo.readline()  

                        # Increment line counter
                        line_no += 1
            except Exception as e:
                print ("eroor message" + str(e))
            # Close the files
            fo.close()
except Exception as e:
            print ("eroor message" + str(e))