Thursday 20 May 2021

Python script for recursively executing a tool/command on each file in a directory

While using some of the pentesting tools in Kali Linux, I could observe that some of the tools/commands are designed to work on a single target file. What if we have a lot of samples to analyze and need to save the whole output in a text file? Here is a simple Python script to automate such tasks. Replace the parameter 'Your_tool_command_here' with the command and corresponding arguments you wanted to execute.

Example: 'file' command to find file type of each file in a directory and sub-directories.

import os
import sys
import time
print "Opening a file 'results' for storing data"
f=open("results.txt","w+") #open a file for saving output
for root, subFolder, files in os.walk("."):
for item in files:
if not item.endswith("results.txt"):
fileNamePath = str(os.path.join(root,item)) #recursively find each file
f.write(fileNamePath+'\n')
f.write("...................................................."+'\n')
stream = os.popen('<Your_tool_command_here>'+" "+fileNamePath)
time.sleep(3)
output = stream.read() #command output
f.write(output+'\n') #write command output to file
f.write("...................................................."+'\n')
f.close()
print "Process completed !"

The code is self-explanatory. But here is a simple description. The script recursively collects each and every file under a root directory and executes the tool or command on each file and the final output is saved in a text file. The output will contain filename and tool execution result. 

Enjoy automating things!!