Created
April 14, 2014 22:46
-
-
Save alukach/10688071 to your computer and use it in GitHub Desktop.
Basic FTP server with awareness of file paths
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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