Tech
Infected

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


ftp-server.py:
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(("127.0.0.1", 1026), handler)
server.serve_forever()

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

ftp-client.py:
from ftplib import FTP

ftp = FTP('')
ftp.connect('localhost',1026)
ftp.login()
ftp.cwd('directory_name') #replace with your directory
ftp.retrlines('LIST')

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

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)
 ftp.quit()
 localfile.close()

uploadFile()
#downloadFile()

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
python ftp-server.py
python ftp-client.py




No comments:

Post a Comment