Module chuẩn ftplib cung cấp client FTP để tự động hóa tải lên/tải xuống file.
Ví dụ cơ bản
import ftplib
ftp = ftplib.FTP('ftp.yourserver.com', 'username', 'password')
print("File List:")
files = ftp.nlst() # hoặc ftp.dir() cho chi tiết
for f in files:
print(f)
ftp.cwd('/tmp') # đổi thư mục
# ftp.retrbinary('RETR filename', open('localfile', 'wb').write) # download
# ftp.storbinary('STOR filename', open('localfile', 'rb')) # upload
ftp.quit()
Các method thường dùng
| Method | Chức năng |
|---|---|
login(user, passwd) | Đăng nhập (nếu chưa trong constructor) |
cwd(path) | Đổi thư mục remote |
pwd() | Xem thư mục hiện tại |
nlst([path]) | List file (tên) |
dir([path]) | List file chi tiết (ls -l) |
retrbinary(cmd, callback) | Download binary |
storbinary(cmd, file) | Upload binary |
delete(path) | Xóa file |
mkd(path), rmd(path) | Tạo/xóa thư mục |
quit() | Đóng kết nối |
Bảo mật: FTP truyền plaintext. Nên dùng ftplib.FTP_TLS (FTPS) hoặc SFTP (qua SSH, dùng paramiko).