1 from ftplib import FTP
2
3
4 class FtpManager(object):
5 def __init__(self, host: str, username: str, password: str, port: int = 21):
6 self.ftp = FTP()
7 self.ftp.set_pasv(True)
8 self.ftp.connect(host, port)
9 self.ftp.login(username, password)
10
11 def __enter__(self):
12 return self
13
14 def __exit__(self, exc_type, exc_val, exc_tb):
15 self.ftp.close()
16
17 def show_dir(self, path: str = '.'):
18 self.ftp.dir(path)
19
20 def upload_file(self, remote_path: str, local_path: str):
21 with open(local_path, 'rb') as f:
22 self.ftp.storbinary('STOR ' + remote_path, f)
23 self.ftp.set_debuglevel(0)
24
25 def download_file(self, remote_path, save_path):
26 with open(save_path, 'wb') as f:
27 self.ftp.retrbinary("RETR " + remote_path, f.write)
28 self.ftp.set_debuglevel(0)
29
30 def read_file(self, remote_path: str):
31 binary_text = []
32 self.ftp.retrbinary("RETR " + remote_path, binary_text.append)
33 self.ftp.set_debuglevel(0)
34 text = ''
35 for line in binary_text:
36 if isinstance(line, bytes):
37 line = line.decode()
38 text += line
39 return text
40
41 def remove_file(self, filename: str):
42 self.ftp.delete(filename)