| 1 |
import optparse |
| 2 |
import sys |
| 3 |
|
| 4 |
import twisted.cred.checkers |
| 5 |
import twisted.cred.credentials |
| 6 |
import twisted.cred.portal |
| 7 |
import twisted.internet |
| 8 |
import twisted.protocols.ftp |
| 9 |
from twisted.python import filepath, log |
| 10 |
|
| 11 |
from zope.interface import implementer |
| 12 |
|
| 13 |
|
| 14 |
def make_ftp_shell(avatar_id, root_path): |
| 15 |
if avatar_id is twisted.cred.checkers.ANONYMOUS: |
| 16 |
return twisted.protocols.ftp.FTPAnonymousShell(root_path) |
| 17 |
else: |
| 18 |
return twisted.protocols.ftp.FTPShell(root_path) |
| 19 |
|
| 20 |
|
| 21 |
@implementer(twisted.cred.portal.IRealm) |
| 22 |
class FTPRealm(object): |
| 23 |
|
| 24 |
def __init__(self, root_path): |
| 25 |
self._root_path = filepath.FilePath(root_path) |
| 26 |
|
| 27 |
def requestAvatar(self, avatarId, mind, *interfaces): |
| 28 |
for iface in interfaces: |
| 29 |
if iface is twisted.protocols.ftp.IFTPShell: |
| 30 |
avatar = make_ftp_shell(avatarId, self._root_path) |
| 31 |
return (twisted.protocols.ftp.IFTPShell, |
| 32 |
avatar, |
| 33 |
getattr(avatar, "logout", lambda: None)) |
| 34 |
raise NotImplementedError() |
| 35 |
|
| 36 |
|
| 37 |
class FtpServerFactory(object): |
| 38 |
""" |
| 39 |
port = FtpServerFactory("/tmp", 2121).makeListner() |
| 40 |
self.addCleanup(port.stopListening) |
| 41 |
""" |
| 42 |
|
| 43 |
def __init__(self, root_path, port): |
| 44 |
factory = twisted.protocols.ftp.FTPFactory() |
| 45 |
realm = FTPRealm(root_path) |
| 46 |
portal = twisted.cred.portal.Portal(realm) |
| 47 |
portal.registerChecker(twisted.cred.checkers.AllowAnonymousAccess(), |
| 48 |
twisted.cred.credentials.IAnonymous) |
| 49 |
checker = twisted.cred.checkers.\ |
| 50 |
InMemoryUsernamePasswordDatabaseDontUse() |
| 51 |
checker.addUser("john", "john") |
| 52 |
portal.registerChecker(checker) |
| 53 |
factory.tld = root_path |
| 54 |
factory.userAnonymous = "anon" |
| 55 |
factory.portal = portal |
| 56 |
factory.protocol = twisted.protocols.ftp.FTP |
| 57 |
self._factory = factory |
| 58 |
self._port = port |
| 59 |
|
| 60 |
def makeListener(self): |
| 61 |
|
| 62 |
return twisted.internet.reactor.listenTCP( |
| 63 |
self._port, self._factory, interface="127.0.0.1") |
| 64 |
|
| 65 |
|
| 66 |
def parse_options(args): |
| 67 |
parser = optparse.OptionParser() |
| 68 |
parser.add_option("--log", action="store_true") |
| 69 |
parser.add_option("--port", type="int", default=2121) |
| 70 |
options, remaining_args = parser.parse_args(args) |
| 71 |
options.root_path = remaining_args[0] |
| 72 |
return options |
| 73 |
|
| 74 |
|
| 75 |
def main(argv): |
| 76 |
options = parse_options(argv[1:]) |
| 77 |
if options.log: |
| 78 |
log.startLogging(sys.stdout) |
| 79 |
factory = FtpServerFactory(options.root_path, options.port) |
| 80 |
factory.makeListener() |
| 81 |
twisted.internet.reactor.run() |
| 82 |
|
| 83 |
|
| 84 |
if __name__ == "__main__": |
| 85 |
main(sys.argv) |