19 set 2017

Cliente FTP em Python

Fonte: FTP client in Python

Por

This article will show you how to use the File Transfer Protocol (FTP)  with Python from a client side perspective.  We use ftplib, a library that implements the FTP protocol.   Using FTP we can create and access remote files through function calls.

Directory listing

We can list the root directory using this little snippet:

[code lang=”python”]
import ftplib

ftp = ftplib.FTP("ftp.nluug.nl")
ftp.login("anonymous", "ftplib-example-1")

data = []

ftp.dir(data.append)

ftp.quit()

for line in data:
print "-", line

[/code]

This will output the directory contents. in a simple console style output. If you want to show a specific directory you must change the directory after connecting with the ftp.cwd(‘/’) function where the parameter is the directory you want to change to.
[code lang=”python”]
import ftplib

ftp = ftplib.FTP("ftp.nluug.nl")
ftp.login("anonymous", "ftplib-example-1")

data = []

ftp.cwd(‘/pub/’) # change directory to /pub/
ftp.dir(data.append)

ftp.quit()

for line in data:
print "-", line

[/code]

Download file

To download a file we use the retrbinary() function. An example below:

[code lang=”python”]
import ftplib
import sys

def getFile(ftp, filename):
try:
ftp.retrbinary("RETR " + filename ,open(filename, ‘wb’).write)
except:
print "Error"

ftp = ftplib.FTP("ftp.nluug.nl")
ftp.login("anonymous", "ftplib-example-1")

ftp.cwd(‘/pub/’) # change directory to /pub/
getFile(ftp,’README.nluug’)

ftp.quit()

[/code]

Uploading files

We can upload files using the storlines() command.
This will upload the file README.nluug in the main directory. If you want to upload in another directory combine it with the cwd() function.

[code lang=”python”]
import ftplib
import os

def upload(ftp, file):
ext = os.path.splitext(file)[1]
if ext in (".txt", ".htm", ".html"):
ftp.storlines("STOR " + file, open(file))
else:
ftp.storbinary("STOR " + file, open(file, "rb"), 1024)

ftp = ftplib.FTP("127.0.0.1")
ftp.login("username", "password")

upload(ftp, "README.nluug")

[/code]


Outras funcionalidades você pode conferir na biblioteca da documentação oficial.

Leave a Reply