Guest User

Untitled

a guest
Apr 26th, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.25 KB | None | 0 0
  1. #!/usr/bin/python3
  2.  
  3. import os
  4. import re
  5. import argparse
  6. import subprocess
  7. from functools import reduce
  8.  
  9. def run_cmd(path, cmd, verbose):
  10. for i, el in enumerate(cmd):
  11. if '@' == el:
  12. cmd[i] = path
  13. if '@' in el:
  14. cmd[i] = el.replace('@', os.path.abspath(path))
  15.  
  16. if verbose:
  17. print('[!]', ' '.join(cmd))
  18.  
  19. subprocess.run(cmd)
  20.  
  21. def walk(start, cmd, verbose, fregex, pregex, nohidden):
  22. if len(cmd) == 0:
  23. cmd = None
  24. if not cmd is None:
  25. if not reduce(lambda x,y: x or y, map(lambda x : '@' in x, cmd)):
  26. cmd.append('@')
  27.  
  28. if nohidden:
  29. fregex = '^[^.]' + fregex
  30. pregex = '^[^.]' + pregex
  31.  
  32. frx = re.compile(fregex)
  33. prx = re.compile(pregex)
  34.  
  35. for root, dirs, files in os.walk(start):
  36. root = os.path.abspath(root)
  37.  
  38. if verbose:
  39. print('[*] Visiting',root)
  40.  
  41. for d in dirs.copy():
  42. if not prx.match(d):
  43. dirs.remove(d)
  44.  
  45. for f in files:
  46. if frx.match(f):
  47. path = os.path.join(root, f)
  48. if cmd is None:
  49. print(path)
  50. else:
  51. run_cmd(path, cmd.copy(), verbose)
  52.  
  53. if __name__ == '__main__':
  54. parser = argparse.ArgumentParser(description='Execute a command for all files')
  55. parser.add_argument('-p', '--path', default='.', help="The path to search all files on")
  56. parser.add_argument('-fr', '--file-regex', default='.+', help="A regular expression to match files to")
  57. parser.add_argument('-pr', '--path-regex', default='.+', help="A regular expression to match paths to")
  58. parser.add_argument('--nohidden', action='store_true', help="Hidden files and hidden directories will not be visited")
  59. parser.add_argument('-v', '--verbose', action='store_true', help="Have more output")
  60. parser.add_argument('command', default=None, nargs=argparse.REMAINDER, help="The command to run on all the valid files (if none is supplied all files get listed). An @ can be used as a placeholder for the file (if not supplied the filename will be appended to the command)")
  61. args = vars(parser.parse_args())
  62. walk(args['path'], args['command'], args['verbose'], args['file_regex'], args['path_regex'], args['nohidden'])
Add Comment
Please, Sign In to add comment