import psutil
import argparse
import os
import signal
import sys
import time
def get_processes_by_file(filepath):
"""Returns a list of processes accessing the given file."""
processes = []
for proc in psutil.process_iter(['pid', 'name', 'open_files']):
try:
for open_file in proc.info['open_files']:
if open_file.path == filepath:
processes.append(proc)
break # Avoid duplicates if file is opened multiple times by the same process
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
pass
return processes
def terminate_processes(processes, force=False):
"""Terminates the given processes."""
for proc in processes:
try:
print(f"Terminating process {proc.info['name']} (PID: {proc.pid})...")
if force:
proc.kill() # Force kill
else:
proc.terminate() # Terminate gracefully
# Wait for process to terminate
proc.wait(timeout=5) #wait 5 seconds for process to terminate
if proc.is_running():
print(f"Process {proc.info['name']} (PID: {proc.pid}) did not terminate gracefully. Attempting kill.")
proc.kill()
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
print(f"Process {proc.info['name']} (PID: {proc.pid}) already terminated or does not exist.")
except Exception as e:
print(f"Error terminating process {proc.info['name']} (PID: {proc.pid}): {e}")
def monitor_file(filepath, interval=5):
"""Monitors a file for processes accessing it."""
print(f"Monitoring file: {filepath} (checking every {interval} seconds). Press Ctrl+C to stop.")
try:
while True:
processes = get_processes_by_file(filepath)
if processes:
print(f"Processes accessing {filepath}:")
for proc in processes:
print(f" - {proc.info['name']} (PID: {proc.pid})")
else:
print(f"No processes currently accessing {filepath}.")
time.sleep(interval)
except KeyboardInterrupt:
print("\nMonitoring stopped.")
def main():
parser = argparse.ArgumentParser(description="Teardown processes accessing a binary file.")
parser.add_argument("filepath", help="Path to the binary file to monitor.")
parser.add_argument("-t", "--terminate", action="store_true", help="Forcefully terminate processes accessing the file.")
parser.add_argument("-i", "--interval", type=int, default=5, help="Monitoring interval in seconds (default: 5).")
args = parser.parse_args()
if not os.path.exists(args.filepath):
print(f"Error: File not found: {args.filepath}")
sys.exit(1)
if args.terminate:
processes = get_processes_by_file(args.filepath)
terminate_processes(processes, force=True)
else:
monitor_file(args.filepath, args.interval)
if __name__ == "__main__":
main()
Add your comment