Linux, OpenSource, Programming And Hacks

Jul 19, 2017

Create a Simple FTP Server and Client in Python

Jul 19, 2017

FTP stands for File transfer protocol, it's used to transfer files between server and client.

Here we will see how to make a simple FTP server in python and we will do some basic example tasks like listing directories of the server and uploading and downloading files to and from the server.

we will be running both the server and client on the same local machine.

for server we will use pyftpdlib module, so first install it via pip

pip install pyftpdlib
from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer

authorizer = DummyAuthorizer()
authorizer.add_user("user", "12345", "/home/username", perm="elradfmw")
authorizer.add_anonymous("/home/username", perm="elradfmw")

handler = FTPHandler
handler.authorizer = authorizer

server = FTPServer(("", 1026), handler)

replace username with your's

keep in mind that the port number should be greater than 1024 or it will throw an error "socket.error: [Errno 13] Permission denied" because you can't bind to a port lower than 1024 as you don't have that right.

for client we are using ftplib module from the official python library
from ftplib import FTP

ftp = FTP('')
ftp.cwd('directory_name') #replace with your directory

def uploadFile():
 filename = 'testfile.txt' #replace with your file in your home folder
 ftp.storbinary('STOR '+filename, open(filename, 'rb'))

def downloadFile():
 filename = 'testfile.txt' #replace with your file in the directory ('directory_name')
 localfile = open(filename, 'wb')
 ftp.retrbinary('RETR ' + filename, localfile.write, 1024)


Note that the port number and ip should be same as the server's.

Now, run the server script first and then the client script

No comments:

Post a Comment