Question

In: Computer Science

How to create a FTP server using python and TCP Ports How to create a FTP...

How to create a FTP server using python and TCP Ports

How to create a FTP server using python and UDP Ports

Solutions

Expert Solution

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:

  1. Configuring and starting the FTP server
  2. Opening up your firewall to allow connections to your 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)


Related Solutions

in Java - implement ftp-server and ftp-client. ftp-server Logging into ftp-server from ftp-client The ftp-server is...
in Java - implement ftp-server and ftp-client. ftp-server Logging into ftp-server from ftp-client The ftp-server is an interactive, command-line program that creates a server socket, and waits for connections. Once connected, the ftp-client can send and receive files with ftp-server until ftp-client logs out. Sending and receiving files The commands sent from the ftp-client to the ftp-server must recognize and handle are these: rename- the ftp-server responds to this command by renaming the named file in its current directory to...
How do I make a simple TCP python web client and web server using only "import...
How do I make a simple TCP python web client and web server using only "import socket"? Basically, the client connects to the server, and sends a HTTP GET request for a specific file (like a text file, HTML page, jpeg, png etc), the server checks for the file and sends a copy of the data to the client along with the response headers (like 404 if not found, or 200 if okay etc). The process would be: You first...
write a skeleton Python TCP servers as follows: Multi-threaded concurrent TCP server using Python’s low-level socket...
write a skeleton Python TCP servers as follows: Multi-threaded concurrent TCP server using Python’s low-level socket module and Python’s threading library Python sockets API: s = socket(), s.bind(), s.listen(), remote_socket, remote_addr = s.accept() Python threading API: thread = threading.Thread(target, args, daemon), thread.start()
To be written in Python: Connect to a TCP-based Quote of the Day server (see RFC...
To be written in Python: Connect to a TCP-based Quote of the Day server (see RFC 865) and obtain a random quote and print it to the console.
In python please Problem Create two server objects using the class create a function, biggest_server_object_sum, outside...
In python please Problem Create two server objects using the class create a function, biggest_server_object_sum, outside of the ServerClass class, that: 1. Takes the IP 2. Sums the octets of the IP together (example 127.0.0.1 = 127+0+0+1 = 128) 3. Returns the Server object with the larger sum Example: server_one = ServerClass("127.0.0.1") server_two = ServerClass("192.168.0.1") result = biggest_ip_sum(server_one, server_two) print(result) Hint Modify get_server_ip in the previous problem. -------------------- Please use this code to start class ServerClass: """ Server class for...
TCP client and server using C programming I am having trouble on how to read in...
TCP client and server using C programming I am having trouble on how to read in the IP adress and port number from the terminal Example: Enter IP address: 127.0.0.1 Enter Port Number: 8000 in both client and server code. How do can I make I can assign the Ip address and port number using the example above. the error I get is that the client couldn't connect with the server whenever i get the port number from the user...
What is the definition of the FTP server? What are the steps to receive the files...
What is the definition of the FTP server? What are the steps to receive the files from the FTP server? Explain and justify jour answer by drawing
Suppose a TCP client needs to send 3 packets to the TCP server. Before sending the...
Suppose a TCP client needs to send 3 packets to the TCP server. Before sending the first packet, the estimated RTT is 50 ms, and the estimated deviation of the sample RTT is 10 ms. The parameters α= 0.1, and β = 0.2. The measured sample RTT for the three packets are 60ms, 70 ms, and 40 ms, respectively. Please compute the time out value that was set for each packet right after it is being transmitted out.
How to do this in Python (using Lists): Create a python program that allows a user...
How to do this in Python (using Lists): Create a python program that allows a user to display, sort and update as needed a List of U.S States containing the State Capital and State Bird. You will need to embed the State data into your Python code. The user interface will allow the user to perform the following functions: 1. Display all U.S. States in Alphabetical order along with Capital and Bird 2. Search for a specific state and display...
Using node.js, create the following tasks. 1. Set up a server and HTML file server as...
Using node.js, create the following tasks. 1. Set up a server and HTML file server as shown in the videos. Once you have it successfully running, make the following adjustments A. When a 404 error (file not found) occurs, display a funny message about the file missing and/or did you forget how to type? B. If the user enters a request for the home page (index.html) then: Display an index.html page you have created which includes your name, course number,...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT