Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

FTP Protocol Client ใน Python (ftplib)

คลาส FTP ในโมดูล ftplib นำ Client Side ของ FTP Protocol ไปใช้งาน

เพื่อสร้างการเชื่อมต่อกับ FTP Server ให้สร้าง FTP Object

con = FTP(hostname)

เมธอดสำคัญของ FTP Class

เมธอดคำอธิบาย
connect()เชื่อมต่อกับ Host และ Port ที่กำหนด (Default Port 21)
getwelcome()คืน Welcome Message จาก Server
login(user='anonymous', passwd='', acct='')Login เป็น User ที่กำหนด Default เป็น anonymous
abort()ยกเลิกการถ่ายโอนไฟล์ที่กำลังดำเนินอยู่
retrbinary(cmd, callback, blocksize=8192, rest=None)ดึงไฟล์โหมด Binary คำสั่ง RETR filename
storbinary(cmd, fp, blocksize=8192, callback=None, rest=None)เก็บไฟล์โหมด Binary คำสั่ง STOR filename
dir()แสดง Directory Listing จากคำสั่ง LIST
delete(filename)ลบไฟล์จาก Server
cwd(pathname)ตั้ง Current Directory บน Server
mkd(pathname)สร้าง Directory ใหม่บน Server
pwd()คืน Pathname ของ Current Directory
rmd(dirname)ลบ Directory บน Server
size(filename)ขอขนาดไฟล์ คืน Integer หรือ None
quit()ส่ง QUIT Command และปิดการเชื่อมต่อ

ตัวอย่าง: ดาวน์โหลดและอัปโหลดไฟล์

from ftplib import FTP
import os

def download_file(ftp):
    filename = 'README.MIRRORS'
    with open(filename, 'wb') as localfile:
        ftp.retrbinary('RETR ' + filename, localfile.write, 1024)

def upload_file(ftp):
    filename = '/home/user/file.txt'
    with open(filename, 'rb') as localfile:
        ftp.storbinary('STOR ' + filename, localfile)

with FTP("ftp1.at.proftpd.org") as ftp:
    ftp.login()
    ftp.getwelcome()
    ftp.dir()
    download_file(ftp)
    upload_file(ftp)