Transferring files with FTP

ftplib can be used for transferring files to and from remote machines. The constructor method of the FTP class (method __init __ ()), receives the host, user, and key as parameters, so that passing these parameters during any instance to the FTP saves the use of the connect methods (host, port, timeout) and a login (user, password).

In this screenshot, we can see more information about the FTP class and the parameters of the init method constructor:

To connect, we can do so in several ways. The first is by using the connect() method and the other is through the FTP class constructor.

In this script, we can see how to connect with an ftp server:

from ftplib import FTP
server=''
# Connect with the connect() and login() methods
ftp = FTP()
ftp.connect(server, 21)
ftp.login(‘user’, ‘password’)
# Connect in the instance to FTP
ftp_client = FTP(server, 'user', 'password')

The FTP() class takes as its parameters: the remote server, the username, and the password of the ftp user.

In this example, we connect to an FTP server in order to download a binary file from ftp.be.debian.org server.

In the following script, we can see how to connect with an anonymous FTP server and download binary files with no user and password.

You can find the following code in the filename: ftp_download_file.py:

#!/usr/bin/env python
import ftplib
FTP_SERVER_URL = 'ftp.be.debian.org'
DOWNLOAD_DIR_PATH = '/pub/linux/network/wireless/'
DOWNLOAD_FILE_NAME = 'iwd-0.3.tar.gz'

def ftp_file_download(path, username):
# open ftp connection
ftp_client = ftplib.FTP(path, username)
# list the files in the download directory
ftp_client.cwd(DOWNLOAD_DIR_PATH)
print("File list at %s:" %path)
files = ftp_client.dir()
print(files)
# download a file
file_handler = open(DOWNLOAD_FILE_NAME, 'wb')
ftp_cmd = 'RETR %s' %DOWNLOAD_FILE_NAME
ftp_client.retrbinary(ftp_cmd,file_handler.write)
file_handler.close()
qftp_client.quit()

if __name__ == '__main__':
ftp_file_download(path=FTP_SERVER_URL,username='anonymous')
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.200.14