In: Computer Science
How to create a FTP server using python and TCP Ports
How to create a FTP server using python and UDP Ports
1. How to create a FTP server using python and TCP Ports
The easiest way to run an FTP server is with a Python script that starts a simple FTP server.
There are two steps to running an FTP server:
Configuring and Starting an FTP Server
First, SSH in to your server as root and install the Python pyftpdlib library with this command:
sudo apt-get install python-pyftpdlib
Next, log out of your server as root. The rest of your steps should be done while logged in as your app's system user.Now, SSH into your server as your app's system user and create a file named ftpserver.py in the user's home directory. That is, create this file:
/srv/users/SYSUSER/ftpserver.py
In that file, put the following contents and change the name, password, and directory for the FTP user that are defined near the top of the file:
from pyftpdlib.authorizers import DummyAuthorizer from pyftpdlib.handlers import FTPHandler from pyftpdlib.servers import FTPServer # The port the FTP server will listen on. # This must be greater than 1023 unless you run this script as root. FTP_PORT = 2121 # The name of the FTP user that can log in. FTP_USER = "myuser" # The FTP user's password. FTP_PASSWORD = "change_this_password" # The directory the FTP user will have full read/write access to. FTP_DIRECTORY = "/srv/users/SYSUSER/apps/APPNAME/public/" def main(): authorizer = DummyAuthorizer() # Define a new user having full r/w permissions. authorizer.add_user(FTP_USER, FTP_PASSWORD, FTP_DIRECTORY, perm='elradfmw') handler = FTPHandler handler.authorizer = authorizer # Define a customized banner (string returned when client connects) handler.banner = "pyftpdlib based ftpd ready." # Optionally specify range of ports to use for passive connections. #handler.passive_ports = range(60000, 65535) address = ('', FTP_PORT) server = FTPServer(address, handler) server.max_cons = 256 server.max_cons_per_ip = 5 server.serve_forever() if __name__ == '__main__': main()
You can now start the FTP server with the following command:
python /srv/users/SYSUSER/ftpserver.py >>/srv/users/SYSUSER/ftpserver.log 2>&1 &
The above command will start the FTP server with a log file named ftpserver.log.
You can verify your FTP server is running with the command:
netstat -npl --inet | grep 2121
Your output should look like this:
tcp 0 0 0.0.0.0:2121 0.0.0.0:* LISTEN 29972/python
which shows your FTP server listening on port 2121.
To stop the FTP server, use the kill command with the FTP server processes' PID, which you can find with this command:
ps -ef | grep ftpserver | grep -v grep | awk '{print $2}'
Configuring Your Firewall to Allow FTP Server Access
Now that you've started your FTP server, you need to customize your server's firewall to open up the port you ran your FTP server on. For example, if you used port 2121, you'd need to open port 2121 in your server's firewall.Additionally, if you uncommented the passive port range line in the above script to enable passive FTP, you also need to open ports 60000-65535 in your server's firewall.
Starting Your FTP Server on Boot
To start your FTP server automatically when your server is rebooted, SSH in as your app's system user and create a cron job like the following:
@reboot python /srv/users/SYSUSER/ftpserver.py >>/srv/users/SYSUSER/ftpserver.log 2>&1
A code for file transfer on local host using multithread TCP:
# serverCode.py
import socket
from threading import Thread
from SocketServer import ThreadingMixIn
TCP_IP = 'localhost'
TCP_PORT = 9001
BUFFER_SIZE = 1024
class ClientThread(Thread):
def __init__(self,ip,port,sock):
Thread.__init__(self)
self.ip = ip
self.port = port
self.sock = sock
print " New thread started for "+ip+":"+str(port)
def run(self):
filename='mytext.txt'
f = open(filename,'rb')
while True:
l = f.read(BUFFER_SIZE)
while (l):
self.sock.send(l)
#print('Sent ',repr(l))
l = f.read(BUFFER_SIZE)
if not l:
f.close()
self.sock.close()
break
tcpsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
tcpsock.bind((TCP_IP, TCP_PORT))
threads = []
while True:
tcpsock.listen(5)
print "Waiting for incoming connections..."
(conn, (ip,port)) = tcpsock.accept()
print 'Got connection from ', (ip,port)
newthread = ClientThread(ip,port,conn)
newthread.start()
threads.append(newthread)
for t in threads:
t.join()
# clientCode.py
#!/usr/bin/env python
import socket
TCP_IP = 'localhost'
TCP_PORT = 9001
BUFFER_SIZE = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
with open('received_file', 'wb') as f:
print 'file opened'
while True:
#print('receiving data...')
data = s.recv(BUFFER_SIZE)
print('data=%s', (data))
if not data:
f.close()
print 'file close()'
break
# write data to a file
f.write(data)
print('Successfully get the file')
s.close()
print('connection closed')
Below is the output from the server console when we run two clients simultaneously:
$ python serverCode.py
Waiting for incoming connections...
Got connection from ('127.0.0.1', 55184)
New thread started for 127.0.0.1:55184
Waiting for incoming connections...
Got connection from ('127.0.0.1', 55185)
New thread started for 127.0.0.1:55185
Waiting for incoming connections...
2. create a FTP server using python and UDP Ports
UDP is a communication protocol that transmits independent packets over the network with no guarantee of arrival and no guarantee of the order of delivery. This protocol is suitable for applications that require efficient communication that doesn't have to worry about packet loss. The typical applications of UDP are internet telephony and video-streaming.
UDP is not suited to large transfers because 1) it has no congestion control so you will just flood the network and the packets will be dropped, and, 2) you would have to break up your packets into smaller ones usually about 1400 bytes is recommended to keep under MTU otherwise if you rely on IP fragmentation and one fragment is lost your whole file is lost .
code for FTP file transfer using UDP:
1. A simple program to transfer small text files
CLIENT CODE:
import socket
import sys
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
host = '127.0.0.1'
port=6000
msg="Trial msg"
msg=msg.encode('utf-8')
while 1:
s.sendto(msg,(host,port))
data, servaddr = s.recvfrom(1024)
data=data.decode('utf-8')
print("Server reply:", data)
break
s.settimeout(5)
filehandle=open("testing.txt","rb")
finalmsg=filehandle.read(1024)
s.sendto(finalmsg, (host,port))
SERVER CODE:
import socket
host='127.0.0.1'
port=6000
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.bind(("",port))
print("waiting on port:", port)
while 1:
data, clientaddr= s.recvfrom(1024)
data=data.decode('utf-8')
print(data)
s.settimeout(4)
break
reply="Got it thanks!"
reply=reply.encode('utf-8')
s.sendto(reply,clientaddr)
clientmsg, clientaddr=s.recvfrom(1024)