DeaD_EyE

find old files on a smb share

Oct 28th, 2020
812
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. """
  2. Find all files in a share and show old files
  3. """
  4. import time
  5. import sys
  6. from argparse import ArgumentParser
  7. from contextlib import closing
  8. from datetime import datetime as DateTime
  9. from datetime import timedelta as TimeDelta
  10. from typing import Union
  11.  
  12. # pip3 install pysmb
  13. from smb.base import SharedDevice, SharedFile
  14. from smb.smb_structs import OperationFailure
  15. from smb.SMBConnection import SMBConnection
  16.  
  17.  
  18. def walk(
  19.     connection: SMBConnection,
  20.     share: str,
  21.     path: str,
  22.     date_min: DateTime,
  23.     level: int = 0,
  24. ) -> None:
  25.     try:
  26.         shared_files = connection.listPath(share, path)
  27.     except OperationFailure:
  28.         return
  29.     for file in shared_files:
  30.         if file.filename == "." or file.filename == "..":
  31.             continue
  32.         name = file.filename
  33.         write = DateTime.fromtimestamp(file.last_write_time)
  34.         if write < date_min:
  35.             print(path, write.isoformat(), sep=",")
  36.         if file.isDirectory:
  37.             walk(connection, share, path + "/" + file.filename, date_min, level + 1)
  38.  
  39.  
  40. def main(host, username, password, date):
  41.     with closing(SMBConnection(username, password, username, username)) as conn:
  42.         conn.connect(host)
  43.         for share in conn.listShares():
  44.             if share.type == SharedDevice.DISK_TREE:
  45.                 print(">>", share.name, "<<")
  46.                 walk(conn, share.name, "/", date)
  47.     return 0
  48.  
  49.  
  50. def get_args():
  51.     default_date = DateTime.now() - TimeDelta(days=365 * 5)
  52.     parser = ArgumentParser()
  53.     parser.add_argument("host", help="IP Address of smb host")
  54.     parser.add_argument("username", help="username of user")
  55.     parser.add_argument("password", help="password of user")
  56.     parser.add_argument(
  57.         "date",
  58.         type=DateTime.fromisoformat,
  59.         default=default_date,
  60.         nargs="?",
  61.         help="Find files which are younger than given iso-date.",
  62.     )
  63.     return parser.parse_args()
  64.  
  65.  
  66. if __name__ == "__main__":
  67.     args = get_args()
  68.     print(f"Seeking files before {args.date}")
  69.     time.sleep(2)
  70.     try:
  71.         main(**vars(args))
  72.     except KeyboardInterrupt:
  73.         pass
  74.     except Exception as e:
  75.         print(repr(e), sys.stderr)
  76.         sys.exit(1)
  77.  
RAW Paste Data