Advertisement
hxrussia

Remove executables recursively in Linux (using Python)

Aug 29th, 2014
323
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.26 KB | None | 0 0
  1. #!/usr/bin/env python2
  2. # -*- coding: utf-8 -*-
  3.  
  4. import os
  5. import sys
  6.  
  7. total_count = 0
  8. files = []
  9. exec_size = 0
  10. total_size = 0
  11.  
  12. desired_type = 'x-executable; charset=binary'
  13.  
  14. def check(path):
  15.     global total_count, exec_size, total_size
  16.    
  17.     total_count += 1
  18.     size = os.stat(path).st_size
  19.     total_size += size
  20.     cmd = "file -i '%s' | grep '%s' > /dev/null"
  21.     if not os.system(cmd % (path, desired_type)):
  22.         files.append(path)
  23.         exec_size += size
  24.         print path
  25.  
  26. def find(directory):
  27.     for name in os.listdir(directory):
  28.         path = os.path.join(directory, name)
  29.         if os.path.isdir(path):
  30.             find(path)
  31.         elif os.path.isfile(path):
  32.             check(path)
  33.  
  34. base = 1024 ** 2
  35.  
  36. print '[*] Search for files...'
  37. directory = sys.argv[1] if len(sys.argv) >= 2 else os.path.curdir
  38. find(directory)
  39. label = '[*] Directory contains %s files (total size %.1lf Mb)'
  40. print label % (total_count, total_size / float(base))
  41. label = '[?] Are you sure to remove %s files (total size %.1lf Mb)? [yes/no]'
  42. print label % (len(files), exec_size / float(base))
  43. if raw_input() == 'yes':
  44.     for path in files:
  45.         os.remove(path)
  46.     print '[+] Operation complete'
  47. else:
  48.     print '[*] Operation canceled'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement