Skip to content

Instantly share code, notes, and snippets.

@alukach
Created April 14, 2014 22:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alukach/10688071 to your computer and use it in GitHub Desktop.
Save alukach/10688071 to your computer and use it in GitHub Desktop.
Basic FTP server with awareness of file paths
from twisted.protocols.ftp import FTP, FTPFactory, FTPRealm
from twisted.cred.portal import Portal
from twisted.cred.checkers import FilePasswordDB
from twisted.internet import reactor
import os
# Sources
# - http://twistedmatrix.com/trac/attachment/ticket/1579/ftp_server_example.py
# - http://stackoverflow.com/questions/9790121/twisted-simple-file-completed-event-for-ftp-server
class MyFTP (FTP):
def ftp_PASS(self, *args, **kwargs):
# Get username before ftp_PASS deletes it
username = self._user
d = super(MyFTP, self).ftp_PASS(*args, **kwargs)
# Pass username to getUsername callback
d.addCallback(self.getUsername, username=username)
return d
def getUsername(self, result, username, *args, **kwargs):
# Do something with username here
self._username = username
return result
def ftp_STOR(self, path):
d = super(MyFTP, self).ftp_STOR(path)
d.addCallback(self.handleUpload, path=path)
return d
def handleUpload(self, result, path, *args, **kwargs):
full_path = os.path.join(
self.portal.realm.userHome.path,
self._username,
path
)
print(full_path)
# Do something with file
return result
p = Portal(
FTPRealm(anonymousRoot='./', userHome='./dir'),
(
FilePasswordDB("pass.dat"),
)
)
f = FTPFactory(p)
f.protocol = MyFTP
reactor.listenTCP(21, f)
reactor.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment